Python Strings, Input, and Decisions


Python Strings, Input, and Decisions

Maria
Today we’re building on the basics of Python objects and expressions. We’ll look at strings, user input and output, and conditional statements—code that lets a program make decisions. Before that, let’s quickly recall the memory model: every object has a type, and a variable name is bound to an object in memory.

Simon
And an assignment evaluates the expression on the right before binding its result to the name on the left. If pi is 3.14 and radius is 2.2, then area equals pi times radius squared creates a new result object and binds area to it.

Maria
Right. Reassigning radius to radius plus one doesn’t alter the original 2.2 object; Python calculates 3.2 and binds the name radius to that value instead. We can also bind a name to something that isn’t an ordinary number: for example, type of 5 times 4 evaluates to the type int, so var can be bound to int.

Simon
That leads to today’s new object type: a string. A string is a sequence of case-sensitive characters. It can contain lowercase or uppercase letters, digits, punctuation, spaces, and special characters such as a newline or tab.

Maria
We write a string by enclosing its characters in quotation marks. For instance, a could refer to the string me, and b could refer to myself. The quotes tell Python that these characters form a string object; the variable names give us convenient ways to refer to those objects.

Simon
The plus operator concatenates strings: it joins their characters into a new string. So a plus b gives the characters of me followed immediately by the characters of myself. It does not insert a space automatically.

Maria
If we want a space, we have to include one ourselves—for example, concatenate a, a string containing a space, and b. That creates a different string, one with me space myself. In both cases, the resulting string can be bound to a new variable.

Simon
The multiplication operator can repeat a string, as long as the other value is an integer. If a is me, then a times 3 makes the string me repeated three times. A string times another string isn’t the operation we want.

Maria
And the types matter. Suppose f is the string a, g is the string space b, and h is the string 3. Then f plus g gives a space b. But h is still a string, even though it looks like a number. Convert it with int of h to get the integer 3; then multiplying f plus g by that integer repeats the whole phrase three times.

Simon
Without that conversion, trying to repeat a string by h gives a type error: Python needs an integer repetition count. Errors like that are useful clues that the objects involved aren’t the types an operation expects.

Maria
A common string operation is len, which counts the characters. If s is abc, len of s is 3, and assigning chars to len of s binds chars to the integer 3.

Simon
To get one character, use square brackets with an index. Python counts from zero: in abc, index 0 is a, index 1 is b, and index 2 is c. Asking for index 3 is too far, so Python raises an index error.

Maria
Negative indices count from the right. For s equal to abc, s at index negative 1 gives c, the last character. You can also put an expression inside the brackets: len of s minus 1 evaluates to 2, so s at that index is c as well.

Simon
To get a substring, use slicing with a start, a stop, and optionally a step inside the square brackets. The start is included, but the stop is not. With s equal to abcdefgh, s from index 3 up to index 6 gives def: it starts at d and stops before the character at index 6, g.

Maria
The step controls how far to move between characters. A step of 1 takes every character; a step of 2 takes every other character. So the slice from 3 to 6 by 2 selects d and f. If you leave the step out, it defaults to 1.

Simon
The direction depends on the step’s sign. A positive step moves left to right, while a negative step moves right to left. For example, a step of negative 1 with the start and stop omitted is a convenient way to reverse the whole string.

Maria
A slice can also include an expression as an index, such as len of s minus 1. And if the start, stop, and direction don’t allow any characters to be selected, the result is an empty string. These rules can take practice, so trying slices in the Python shell is a useful way to see exactly what they do.

Simon
There’s one more important property of strings: they’re immutable. Once a string object exists, you can’t change one of its characters in place. Trying to replace the character at index 0 of car with b is not allowed.

Maria
Instead, make a new string containing the characters you want and bind a name to that new object. The original string remains unchanged; if you reassign its variable, you’re changing the binding, not modifying the object itself.

Simon
Now let’s distinguish the Python shell from a program saved in a file. In the shell, typing an expression displays its value, which is handy for quick exploration. But if you put an expression in a file and run the file, Python doesn’t automatically display that expression’s value.

Maria
For output from a running program, use print. For example, print of len of s displays 3. Each print call ends with a new line, so two print calls ordinarily put their results on separate lines.

Simon
You can print multiple objects in one call by separating them with commas. Python displays each object and puts a space between them. That’s convenient, but the space may not always be what you want.

Maria
If you try to concatenate a string, an integer, and another string, Python reports a type error: plus joins strings, not a string and an integer. One fix is to convert the integer with str, then concatenate the resulting strings. That gives you control over whether there’s a space.

Simon
Another convenient option is an f-string. Put an f before the quotation mark, write literal text as usual, and put expressions inside curly braces. Python evaluates those expressions before printing the result, so you can mix text and values without manually converting each value to a string.

Maria
For example, an f-string can place a number right beside a percent sign, avoiding the extra space that print would put between comma-separated objects. The general idea is that expressions can appear in many places—inside a print call, an index, or an f-string—and Python evaluates them as it processes the code.

Simon
Input makes a program interactive. The input command often contains a prompt string, and its result is assigned to a variable. Python displays the prompt, waits for the user to type something and press Enter, and returns what the user typed as a string.

Maria
That last point is crucial: even if the user types the character 3, input returns the string 3. If we print that string five times, we get 33333. If we want numerical multiplication instead, we must convert the input to an integer—for example, assign num to int of input with a prompt, then five times num gives 15.

Simon
A small interactive program can ask for a verb, then print a sentence such as, “I can run better than you,” followed by the verb repeated five times. The prompt’s input goes into a variable; print can combine that variable with literal text, and string multiplication can produce the repeated verb.

Maria
If we build the repeated phrase by multiplying a string that contains a space after the verb, we may end up with an extra space at the end. That’s a useful detail to notice when checking output: the program may work, but the formatting can still be improved.

Simon
Input and expressions can also be used in numerical examples. Newton’s method estimates roots through successive approximations. With the material we have so far, we can calculate one next guess from an initial guess, even though we haven’t yet learned how to repeat that calculation automatically.

Maria
For a cube root of x, if the current guess is g, the next guess is g minus the quantity g cubed minus x divided by 3g squared. A program can ask the user for x and g, print the current guess cubed, and calculate that next estimate.

Simon
Python won’t automatically infer the function or its derivative for this example. We write the formula explicitly: the function is g cubed minus x, and its derivative is 3g squared. For x equal to 27 and a starting guess of 5, the program can show that 5 cubed is 125 and calculate a next guess of about 3.69.

Maria
That program stops after finding one next guess. Taking that result and repeatedly finding another guess requires a way to repeat commands, which is a topic for a later lesson.

Simon
The final major topic today is branching: making a program choose which code to run. Programs so far have mostly followed their lines in order. A conditional lets some code run only when a condition is true.

Maria
To create conditions, distinguish assignment from comparison. One equal sign assigns the value on the right to the variable on the left. Two equal signs ask whether two expressions are equivalent, producing a Boolean value: true or false.

Simon
For example, 2 less than 3 evaluates to true, while 2 double-equals 3 evaluates to false. Python also has not-equal, written with an exclamation mark followed by an equal sign, and the comparison operators less than, less than or equal to, greater than, and greater than or equal to.

Maria
Comparisons can apply to strings too, but case matters: lowercase a and uppercase A are not the same character. The result of a comparison is still a Boolean, which is what makes comparisons useful for deciding what a program should do.

Simon
You can combine Boolean expressions. The operator not reverses a Boolean value. With and, both parts must be true for the whole expression to be true; if either part is false, the result is false.

Maria
With or, the result is true if at least one part is true. It’s false only when both parts are false. For example, if one Boolean variable is true and another is false, their and is false, while their or is true.

Simon
Now for the basic conditional syntax: write if, then a condition, then a colon. The indented lines below it are the code block. If the condition is true, Python runs that block; if it’s false, Python skips it and continues with the next line at the original indentation level.

Maria
Indentation tells Python which commands belong to which block. An if can also have an else: if the condition is true, run the if block; otherwise, run the else block. Only one of those two blocks runs, and then execution continues after them.

Simon
For more than two possibilities, use elif, short for “else if.” Python checks those conditions in order and runs the block for the first one that’s true. If none is true, it skips the blocks unless you add an else at the end as a catch-all.

Maria
For instance, a schedule program might check whether pset time plus sleep time is greater than 24, whether it equals 24, or whether it’s less. Those cases can lead to different messages or calculations, after which the program continues at the code that follows the whole conditional.

Simon
Be careful about where that following code is indented. If a print statement is meant to happen only when x equals y, it has to be indented into that if block. If it’s at the same indentation as the if, it runs afterward whether or not the condition was true.

Maria
Conditionals can be nested. Inside one if block, you can put another if statement to check a more specific condition. The inner condition is reached only when execution enters the outer block; after the nested block finishes, execution continues in the surrounding program.

Simon
You can also use two separate if statements. Each one is checked independently, so both blocks can run if both conditions are true. That’s different from if, elif, and else, where the alternatives form one chain and at most one block is selected.

Maria
A number-guessing program brings these ideas together. Read the guess as an integer, compare it with a secret number, and use if for a guess that’s too high, elif for a guess equal to the secret, and else for a guess that’s too low.

Simon
The comparison details matter. If the first condition says the guess is greater than or equal to the secret, the equal case is captured as “too high” before Python can reach the equality check. Using greater than instead leaves equality available for the elif.

Maria
Testing several inputs helps catch that kind of bug. Try a guess that’s high, one that matches, and one that’s low. Debug early and often, and remember to cast user input when you intend to compare numbers rather than strings.

Simon
So today we learned how strings work, how programs can receive input and show selected output, and how Boolean conditions create decision points. Next comes more branching and then loops, which will let programs repeat commands.

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