1. Home
  2. Explore
  3. Computer Science
  4. Python Strings, Input, and Decisions

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Python Strings, Input, and Decisions

Python Objects, Strings, Input and Output, and Decisions

Objects, variables, expressions, and assignment

A Python program works with objects. Every object has a type, which determines what kinds of operations can be performed on it. For example, integers and floating-point numbers support arithmetic, while strings support operations such as concatenation and slicing.

A variable is a name bound to an object in memory. When Python encounters a variable name in an expression, it looks up the object associated with that name.

pi = 3.14
radius = 2.2
area = pi * radius**2

For the assignment to area, Python first evaluates the expression on the right: it retrieves the values bound to pi and radius, calculates the result, and then binds the name area to that result.

Assignment is not mathematical equality

The single equals sign, =, means assignment: evaluate the right-hand side and bind its result to the name on the left. For example:

radius = radius + 1

Python first evaluates the right side using the current value of radius. If the value was 2.22.22.2, the new result is 3.23.23.2, and the name radius is then bound to that result. This is not an assertion that a number equals itself plus one.

In this model, an operation such as addition creates a result object rather than changing the original numeric object. The variable name is then bound to the result.

Expressions can produce different kinds of values

An expression is something Python evaluates to a value. Expressions can include arithmetic, variable names, function calls, and other operations.

For example:

var = type(5 * 4)

Python evaluates 5 * 4 to 20, determines that 20 has type int, and binds the type object int to var. Variables can therefore refer to objects other than numbers, including strings and types.


Strings

A string is an ordered sequence of characters. It can contain lowercase and uppercase letters, digits, punctuation, spaces, and special characters such as newline and tab characters. Strings are case-sensitive, so uppercase and lowercase letters are different characters.

String literals are written inside quotation marks:

a = "me"
z = "you"

The quotation marks indicate to Python that the enclosed characters form a string. The variable names provide convenient ways to refer to those string objects.

Concatenation

The + operator concatenates strings by placing their characters together in order. It does not automatically add a space.

a = "me"
b = "myself"
c = a + b

The value of c is "memyself". To include a space, the space must be part of one of the strings being combined:

d = a + " " + b

The value of d is "me myself".

Repetition

The * operator repeats a string when one operand is a string and the other is an integer.

silly = "me" * 3

The resulting string is "mememe". Repetition works with the integer and string in either order. A string cannot be repeated a fractional number of times; the repetition count must be an integer.

If a string is stored in h, then "a b" * int(h) repeats it the number of times represented by h, provided h can be converted to an integer. Attempting to multiply a string by a numeric-looking string without converting it first causes a type error: Python sees a string and a non-integer, not a string and an integer.

Length

The built-in len operation returns the number of characters in a string:

s = "abc"
chars = len(s)

Here, chars is bound to the integer 3. Spaces and other characters count as characters too.

Indexing individual characters

Indexing retrieves the character at a particular position. In Python, positions start at zero:

  • The first character is at index 000.

  • The second character is at index 111.

  • The third character is at index 222.

s = "abc"
first = s[0]
second = s[1]
third = s[2]

These expressions produce "a", "b", and "c" respectively. Trying to access s[3] raises an index error because there is no character at that position.

Negative indices count from the end of the string:

  • Index −1-1−1 is the last character.

  • Index −2-2−2 is the second-to-last character.

For example, s[-1] returns "c". An index that goes beyond either end of the string, such as s[-4] for a three-character string, raises an index error.

An index can itself be an expression. For example, s[len(s) - 1] retrieves the final character by calculating the last valid nonnegative index first.

Slicing substrings

Slicing extracts a portion of a string. The general form is:

s[start:stop:step]
  • start is the index where extraction begins.

  • stop is the boundary where extraction ends; the character at the stop index is not included.

  • step determines how far the index advances between selected characters.

For a positive step, Python proceeds from left to right. A step of 111 takes every character; a step of 222 takes every other character.

s = "abcdefgh"
  • s[3:6] produces "def": it begins at index 333 and stops before index 666.

  • s[3:6:2] produces "df": it takes the character at index 333, skips one, and then takes the character at index 555.

If the step is omitted, it defaults to 111. If a slice’s boundaries are omitted, Python uses the appropriate end of the string. Thus, s[:] makes a full slice of the string, while s[::-1] traverses the string in reverse and produces "hgfedcba".

For a negative step, Python proceeds from right to left. For example, with s = "abcdefgh", the slice s[4:1:-2] begins at index 444 ("e"), moves left by two indices to index 222 ("c"), and stops before index 111. The result is "ec".

A slice can validly produce the empty string, written as "", if its start, stop, and step do not select any characters. For example, a slice moving to the right cannot collect characters if its stop boundary lies behind its starting position.

Key slicing rule: The start index is included, but the stop index is excluded. The step determines the direction and spacing of the selected characters.

Strings are immutable

Strings are immutable: once created, their characters cannot be changed in place. For example, Python does not allow an assignment that tries to replace the character at index 000 of an existing string.

To obtain a changed string, a program must create a new string and, if desired, bind a variable name to it. The original string object is not modified. Reassigning a variable to a new object changes what that name refers to; it does not rewrite the old object.


Program output with print

The interactive Python shell displays the value of an expression typed directly into it. This is useful for quickly inspecting a result, but it is not the same as printing output from a program file.

In a program file, evaluating an expression does not automatically display its value. To show a result to the user, the program must explicitly use print:

s = "abc"
print(len(s))
print(s[-1])

This program prints 3 and then c, each on its own line. Each print call ends its output with a newline by default.

Printing several objects

A print call can take several objects separated by commas:

print("the", 3, "musketeers")

Python prints the objects on one line and inserts a space between them. This works for objects of different types, such as strings and integers.

By contrast, concatenation requires strings. An expression that tries to add a string and an integer raises a type error. If concatenation is needed, a non-string value can first be converted using str:

print("the " + str(3) + " musketeers")

This produces one concatenated string, with spaces included only where the program explicitly placed them.


Getting user input

The built-in input operation displays an optional prompt, waits for the user to type a response and press Enter, and returns the response as a string.

text = input("Type anything: ")

If the user types howdy, the returned value is the string "howdy", and text is bound to that string.

Even when the user types digits, input returns characters, not a number. For instance, typing 3 produces the string "3". This distinction affects later operations:

  • Repeating "3" five times produces "33333".

  • Multiplying the integer 333 by 555 produces 151515.

To perform numerical operations on input, the program must convert it to a numeric type:

num = int(input("Type a number: "))

Here, the user’s response is first received as a string and then converted to an integer. A program can also use float when a floating-point value is needed. Conversion will fail if the response is not a valid representation of the requested numeric type.

Combining input, conversion, and output

A program can use input to build an interactive exchange. For example, it can ask for a verb, include the response in a sentence, and repeat it:

verb = input("Type a verb: ")
print("I can", verb, "better than you")
print((verb + " ") * 5)

The comma-separated values in the first print call are separated by spaces. In the second statement, the program explicitly concatenates a space to the verb before repeating it. That form leaves a trailing space after the final repetition; a more polished program could construct the output so it inserts spaces only between repetitions.


Expressions inside output: f-strings

An f-string provides a convenient way to combine literal text with values or expressions. It begins with f before the opening quotation mark. Expressions are placed inside curly braces and evaluated before the string is printed:

num = 20
fraction = 0.15
print(f"{num * fraction} is {fraction * 100}% of {num}")

Text outside the braces is printed literally. Expressions inside the braces are evaluated, and their results are formatted as part of the string. This avoids manually converting values to strings and concatenating them. It also gives precise control over spacing and punctuation; for example, a percent sign can be placed directly after a value.

Expressions can appear in many parts of Python code, including assignments, indices, function arguments, and f-strings. Python evaluates each expression when needed and uses its resulting value.


A numerical example: one Newton-method update

Newton’s method can approximate roots of a function through successive guesses. For finding the cube root of a value xxx, a current guess ggg can be updated using:

gnext=g−g3−x3g2g_{\text{next}} = g - \frac{g^3 - x}{3g^2}gnext​=g−3g2g3−x​

The numerator is the function value g3−xg^3 - xg3−x, and the denominator is its derivative, 3g23g^23g2. A program can ask the user for xxx and an initial guess ggg, then calculate and display one updated guess.

The program must encode the function and derivative formulas itself; Python does not automatically infer them from an expression. A single update provides the next estimate but does not repeat the process. Repeating updates requires a looping construct, which is a separate control-flow feature.


Boolean values and comparisons

A Boolean value is either True or False. Comparisons and logical operations produce Boolean results, which allows programs to test conditions and make decisions.

Assignment versus equality

A single equals sign assigns a value to a variable. A double equals sign, ==, asks whether two values are equal and produces a Boolean result.

secret = 5
guess = 5
matches = (secret == guess)

Here, matches is True. If the values differ, the comparison produces False.

Comparison operators

Common comparison operators include:

  • == — equal to

  • != — not equal to

  • < — less than

  • <= — less than or equal to

  • > — greater than

  • >= — greater than or equal to

For example, 2<32 < 32<3 evaluates to True, while 2==32 == 32==3 evaluates to False. Comparisons can also be used with strings. Because strings are case-sensitive, "a" == "A" is False.

Combining Boolean expressions

The logical operator not reverses a Boolean value: not True is False, and not False is True.

The operator and produces True only when both of its Boolean expressions are true. If either one is false, the combined result is false.

The operator or produces True when at least one of its Boolean expressions is true. It is false only when both expressions are false.

These operators allow a program to express more complex conditions. For example, a program could test whether one number is greater than another and whether a second comparison is also true. The word and is Python’s logical operator; it is not interchangeable with a different operator that performs bit-level operations.


Conditional branching

Programs without conditionals generally execute statements in sequence. Conditionals introduce decision points: the program evaluates a Boolean condition and selects which block of code to run.

if statements

An if statement runs its indented block only when its condition is true:

if condition:
    # statements in the block

The colon marks the start of the block. Indentation identifies the statements that belong to it. If the condition is false, Python skips the block and continues with the next statement at the surrounding indentation level.

if and else

An else block provides an alternative when the if condition is false:

if condition:
    # run when condition is true
else:
    # run when condition is false

Exactly one of these two blocks runs. Afterward, execution continues with the statements following the conditional.

Multiple alternatives with elif

An elif (“else if”) adds another condition to check when the preceding condition or conditions were false:

if first_condition:
    # first choice
elif second_condition:
    # second choice
elif third_condition:
    # third choice
else:
    # catch-all choice

Python checks the conditions in order and executes the block belonging to the first true condition. No later alternative is checked once a block has been selected. If no condition is true, the else block runs, if one is present. Without an else, it is possible for none of the blocks to run.

The order of conditions matters. For example, if a program tests whether a value is greater than or equal to a target before testing whether it is exactly equal to the target, the equality case will be captured by the first condition. To give equality its own branch, the first test should use a strict greater-than comparison, followed by the equality test.

Indentation and nested conditionals

Indentation is part of Python’s syntax. A statement indented under a conditional belongs to that block; a statement at the original indentation level belongs to the surrounding program. A statement mistakenly left outside a block will run regardless of the condition.

Conditionals can be nested: an if statement can appear inside another conditional’s block. The inner conditional is considered only when execution reaches the outer block containing it. This makes it possible to test a general condition first and then test a more specific condition within that case.

Separate if statements are not the same as an if/elif chain. Each separate if is evaluated independently, so more than one of their blocks can run. In an if/elif chain, at most one alternative block runs.

Example: classify a guess

A number-guessing program can compare a user’s integer guess with a secret integer:

secret = 5
guess = int(input("Guess a number: "))

if guess > secret:
    print("Too high")
elif guess == secret:
    print("Equal")
else:
    print("Too low")

The else handles the remaining possibility: the guess is less than the secret. It is unnecessary to write an explicit final less-than condition when all other possibilities have already been covered. Converting the user’s input to an integer is important; otherwise the program would be comparing strings rather than numeric values.


Testing and debugging programs

A program can appear correct in one case and fail in another. Testing different inputs helps reveal boundary mistakes, incorrect condition ordering, and type errors. For a guessing program, useful tests include a guess that is lower than the secret, a guess that is equal to it, and a guess that is higher.

When output is unexpected, the program can be run with carefully chosen inputs to trace which condition is true and which block executes. Checking whether a statement is indented inside or outside the intended block is also an important debugging step. Regular testing helps catch errors before they affect later parts of a program.

Input and output make programs interactive, Boolean comparisons provide conditions, and branching lets programs choose which instructions to execute based on those conditions.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent