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 Strings, Input and Output, and Decisions

A Python program begins with objects and expressions, but it becomes much more useful when it can work with text, communicate with a person, and choose which instructions to follow. This lesson develops those ideas in sequence: first, how Python stores and evaluates values; then how strings represent text; next, how programs receive input and display output; and finally, how Boolean conditions create decision points.

Objects, variables, and assignment

Every value in Python is an object, and every object has a type. A type tells Python what kinds of operations make sense for that object. For example, numbers support arithmetic, while strings support operations such as joining and repeating text.

A variable is a name bound to an object. Consider:

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

Python evaluates the expression on the right side of an assignment before binding its result to the name on the left. For area, Python retrieves the values bound to pi and radius, calculates the expression, creates the resulting object, and binds that object to area.

Assignment is not the same as mathematical equality. In Python, the statement

radius = radius + 1

means “evaluate the current value of radius plus 111, then bind the resulting object to the name radius.” If radius was bound to 2.22.22.2, the expression evaluates to 3.23.23.2, and the name is rebound to that new value. The original object is not changed by the arithmetic operation.

Expressions can also produce values that are not ordinary numbers. For example:

var = type(5 * 4)

Python first evaluates 5 * 4, which gives 202020, and then evaluates its type, which is int. The name var is therefore bound to the type object int.

Assignment binds a name to the value of an expression. It does not mean that the two sides of the assignment are mathematically equal.

Think About It: If a variable is rebound to a new object, does that necessarily mean the old object was modified?

Strings: representing and combining text

A string is a sequence of characters. Its characters can include lowercase and uppercase letters, digits, punctuation, spaces, and special characters such as newlines and tabs. Strings are written inside quotation marks:

a = "me"
z = "you"

Quotation marks tell Python that the enclosed characters are text. They also make the string case-sensitive: "a" and "A" are different strings.

Joining and repeating strings

The + operator concatenates strings: it joins their characters in order and creates a new string.

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

The value of c is "memyself". Concatenation does not insert a space automatically. A space must be included explicitly:

d = a + " " + b

Now d is "me myself".

The * operator can repeat a string when the other operand is an integer:

silly = a * 3

The result is "mememe". The order of the operands can also be reversed: 3 * a repeats the string in the same way. A string cannot be repeated by multiplying it by another string or by a non-integer value.

This distinction follows from types. For instance, if h is the string "3", then "ab" * h does not work: the multiplier is text, not an integer. Converting it first makes the intended operation possible:

h = "3"
result = "ab" * int(h)

Here, int(h) converts the string to the integer 333, so the result is "ababab". A type error often indicates that an operation received a value of the wrong type.

String length and indexing

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

s = "abc"
chars = len(s)

Here, chars is 333.

To retrieve one character, Python uses square brackets and an index. Indexing starts at 000, so the first character is at index 000, the second at index 111, and the third at index 222:

s[0]  # "a"
s[1]  # "b"
s[2]  # "c"

An index outside the string’s valid positions causes an index error. For example, s[3] asks for a fourth character, but "abc" has only three.

Negative indices count from the end. The index −1-1−1 means the last character, −2-2−2 the second-to-last, and so on:

s[-1]  # "c"

This is a convenient way to get the final character without first calculating the string’s length. For a string of length nnn, the last character also has index n−1n-1n−1.

Slicing: retrieving a substring

Slicing retrieves a portion of a string. Its general form is:

string[start:stop:step]
  • start is the index where the slice begins.
  • stop is the boundary where it ends; the character at the stop index is not included.
  • step determines how far the index moves each time.

For example, suppose:

s = "abcdefgh"

Then:

s[3:6]

starts at index 333 and stops before index 666, producing "def". Since the step is omitted, Python uses a step of 111 and takes every character along the way.

A step of 222 skips every other character:

s[3:6:2]

This produces "df": it takes the character at index 333, skips the next, then takes the character at index 555.

A positive step moves from left to right. A negative step moves from right to left. For example:

s[::-1]

uses a negative step and produces the string backward: "hgfedcba".

The stop boundary remains exclusive even when moving backward. For instance:

s[4:1:-1]

starts at index 444, moves left, and stops before index 111. It therefore takes the characters at indices 444, 333, and 222.

An omitted start or stop lets Python use a boundary appropriate to the direction of travel. A slice can also be empty. For example, s[6:3] uses the default positive step, but the stop lies to the left of the start, so there are no characters to take. The result is the empty string, written as "".

Strings are immutable

Strings are immutable, meaning a string object cannot be changed after it has been created. A statement that tries to replace a character at a particular index, such as assigning a new letter to s[0], is not allowed.

To get a different string, an expression must create a new one. The original string remains unchanged; a variable can then be rebound to the new string. This is the same general pattern seen with numeric operations: an operation creates a result object rather than changing the original object.

Think About It: In the slice "abcdefgh"[3:6], why is the character at index 666 excluded?

Input and output: communicating with a program

A program typed into an interactive Python shell can show the value of an expression automatically. That is useful for trying small expressions, but it is not the same as displaying output from a program saved in a file. In a file-based program, an expression can be evaluated without its value being shown. To display a result deliberately, the program uses print.

Printing results

A print statement displays its contents and then moves to a new line:

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

This displays the length and last character on separate lines.

Several values can be printed in one print statement by separating them with commas:

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

Python prints the values on one line, putting a space between the items. This is convenient when the values have different types.

String concatenation, by contrast, requires strings on both sides. To combine text with a number using +, the number must be converted to a string:

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

The str function converts the integer to text. Without that conversion, Python raises a type error because it cannot concatenate an integer directly with strings.

Getting input

The input function displays a prompt and waits for the user to type a response and press Enter:

text = input("Type anything: ")

The typed response is returned as a string, regardless of what it looks like. If the user types howdy, text is bound to "howdy". If the user types 3, the program receives the string "3", not the integer 333.

That difference affects later operations:

num1 = input("Type a number: ")
print(5 * num1)

If the user enters 3, num1 is the string "3", so the multiplication repeats the text and prints "33333".

To perform arithmetic, the input must be converted to a numeric type:

num2 = int(input("Type a number: "))
print(5 * num2)

Now the entered text is first converted to an integer. If the user enters 3, the program calculates 5×35 \times 35×3 and prints 151515.

A simple interactive program can combine input with both kinds of output:

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

If the user enters run, the first line displays a sentence and the second repeats the verb five times. Because " " is included in the repeated string, each repetition has a following space. This also leaves a space after the final repetition. That small formatting detail illustrates why checking actual program output matters.

Printing expressions with f-strings

An f-string makes it easier to print literal text mixed with values or expressions. It begins with f, and expressions to evaluate are placed inside curly braces:

num = 27
fraction = 0.1
print(f"{num * fraction} is {fraction * 100}% of {num}")

Text outside the braces is printed literally. Python evaluates the expressions inside the braces before displaying the result. An f-string avoids the need to manually concatenate each piece or convert every number to a string.

More generally, expressions can appear in many contexts: on the right side of assignments, inside function calls, within indices, and inside f-strings. Python evaluates each expression where it appears and uses the resulting value.

A numerical application: the next Newton estimate

The same ideas can be used in a numerical calculation. Newton’s method estimates roots of a function through successive approximations. A complete method repeatedly updates a guess, but even a single update demonstrates how input, expressions, and output work together.

To estimate the cube root of a number xxx, let ggg be the current guess. The function whose root is sought is f(g)=g3−xf(g)=g^3-xf(g)=g3−x, and its derivative is 3g23g^23g2. Newton’s update is:

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

A program can ask for the target number and an initial guess, then calculate one next estimate:

x = float(input("What number should be cube-rooted? "))
g = float(input("What is the starting guess? "))

print("Current guess cubed:", g**3)
next_guess = g - (g**3 - x) / (3 * g**2)
print("Next guess:", next_guess)

The program writes out the function and derivative expressions itself; it does not automatically derive them. For example, if the target is 272727 and the starting guess is 555, the current guess cubed is 125125125, and the next estimate is approximately 3.693.693.69. This example performs only one update. Repeating the update requires a way to repeat instructions, which is a separate control-flow idea.

Think About It: Why does entering the characters "3" produce repetition in one program but arithmetic in another?

Booleans and comparison expressions

A program can make a decision only if it can determine whether a condition is satisfied. Python represents such results with the Boolean type, which has two values: True and False.

One equal sign, =, assigns a value to a name. Two equal signs, ==, compare two expressions and produce a Boolean:

x = 5
x == 5

The comparison evaluates to True. By contrast, x == 4 evaluates to False.

Python provides several comparison operators:

  • == tests whether two values are equal.
  • != tests whether they are not equal.
  • < and > test whether one value is less than or greater than another.
  • <= and >= include equality in those comparisons.

Comparisons also work on strings, but they are case-sensitive: "a" == "A" is False because the characters differ.

Boolean expressions can be combined with not, and, and or. The word and is the Python operator; it is not interchangeable with a symbol used for bitwise operations.

  • not reverses a Boolean value: not True is False.
  • and is true only when both component expressions are true.
  • or is true when at least one component expression is true.

For example, if a program checks whether two conditions are both satisfied, it can use condition1 and condition2. If either condition is false, the combined result is false. With condition1 or condition2, the result is false only when both conditions are false.

A Boolean can also be stored in a variable and combined with other Boolean variables:

drive = True
drink = False
both = drink and drive
print(both)

Here, both is False, because both values would need to be true for an and expression to be true.

Branching: choosing which instructions run

Without branching, a program runs its statements in sequence. Conditionals let a program choose different instructions based on a Boolean expression.

if and else

An if statement checks a condition:

if condition:
    # instructions to run when condition is True

If the condition is true, Python runs the indented instructions. If it is false, Python skips that block and continues with the next statement at the original indentation level.

An else adds an alternative:

if condition:
    # instructions for the True case
else:
    # instructions for the False case

Exactly one of these two blocks runs. The colon marks the start of the block, and indentation shows which statements belong to it. Python relies on this indentation as part of its syntax, so consistent indentation is essential.

The location of a statement matters. A statement indented inside an if block runs only when that condition is true. A statement aligned with the if runs after the conditional, regardless of whether the condition was true.

Multiple alternatives with elif

When a program needs to test several possibilities, it can use elif, short for “else if”:

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

Python checks these conditions in order. It runs the block belonging to the first condition that is true, then skips the remaining alternatives. If none is true, the optional else block runs. Without an else, it is possible for none of the blocks to run.

For example, a number-guessing program can report whether a guess is too high, correct, or too low:

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

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

The first condition uses > rather than >=. If it used >=, a correct guess would be classified as too high before Python ever reached the equality test. The ordering and boundaries of conditions therefore matter.

Separate if statements and nested conditionals

Several independent if statements are not equivalent to one if/elif chain. Each independent if is checked separately, so more than one block can run:

if condition_a:
    # this block may run
if condition_b:
    # this block may also run

An if/elif chain instead chooses at most one alternative. This distinction helps determine whether conditions should be independent or mutually exclusive.

A conditional can also be placed inside another conditional. This is called nesting:

if x == y:
    print("The values are equal")
    if y != 0:
        print("Their shared value is not zero")

The inner condition is considered only when the outer condition is true, because the inner if is part of the outer block.

Conditionals as an algorithm

Conditionals can describe a sequence of choices, not just compare numbers. Imagine navigating a maze while keeping a hand against the right-hand wall. A simple rule set is:

  1. If the right side is clear, move right.
  2. Otherwise, if forward is clear, move forward.
  3. Otherwise, if the left side is clear, move left.
  4. If all those directions are blocked, move backward.

Each rule is a decision based on the current surroundings. In a maze without isolated “islands” of walls, this kind of wall-following strategy can eventually lead through the maze. The example shows how a series of conditional choices can form an algorithm.

Checking and debugging conditional code

A program can be syntactically valid and still make the wrong choice. Testing different cases helps reveal errors. For a guessing program, useful tests include a guess that is too high, one that is equal to the secret, and one that is too low. Testing only one case might miss a misplaced comparison or an incorrect indentation level.

Small tests are especially helpful when conditions have boundaries, such as “greater than” versus “greater than or equal to.” Debugging early and often makes it easier to identify the statement responsible for an unexpected result.

Think About It: If two conditions can both be true, should they be written as separate if statements or as alternatives in an if/elif chain?

Comprehensive review

Python programs are built from typed objects, names bound to those objects, and expressions that evaluate to new values. Strings add text to the range of objects a program can handle. They can be joined with concatenation, repeated with an integer multiplier, measured with len, and inspected by indexing or slicing. Because strings are immutable, a changed version must be created as a new string.

Input and output make a program interactive. input returns text, so numeric responses must be converted before arithmetic. print deliberately displays results, while commas separate printed items with spaces, string conversion enables concatenation, and f-strings combine literal text with evaluated expressions.

Finally, comparisons produce Booleans, and conditionals use those Booleans to control which instructions run. if, elif, and else form ordered alternatives; independent if statements can each run, and nested conditionals create decisions within decisions. Careful attention to types, boundaries, indentation, and tests makes these programs easier to understand and more reliable.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent