Skip to content
FORGENO ADS GAMESUnlock all $8

Python Programming · Unit 2 of 8

Unit 2: Strings and decisions

Indexing, slicing and string methods, comparisons and True or False logic, truthiness, if, elif and else, and while loops that repeat until a condition changes.

Opens the first lesson of this unit in Python Programming. Every lesson is open from the start.

Lesson 1: Working with strings

Goal: Index, slice and transform strings with methods, and explain why strings never change in place.

A string is a sequence of characters, and each character has a position called an index. Indexes start at 0, so in word = "Python", word[0] is "P" and word[5] is "n". Negative indexes count from the end: word[-1] is the last character, "n", and word[-2] is "o". Asking for word[6] raises an IndexError, because a string of length 6 has positions 0 to 5. len(word) gives the length, 6.

A slice takes a piece: word[start:stop] gives the characters from start up to but not including stop. So word[0:2] is "Py" and word[2:6] is "thon". Leave out start or stop to mean "from the beginning" or "to the end": word[:3] is "Pyt" and word[3:] is "hon". A third number is a step: word[::-1] reverses the string. Slices never raise errors; asking for too much just gives what exists.

word = "Python"
# index:   P  y  t  h  o  n
#          0  1  2  3  4  5
#         -6 -5 -4 -3 -2 -1
print(word[0], word[-1], len(word))
print(word[1:4], word[:2], word[2:], word[::-1])

Strings are immutable: once created, they never change. word[0] = "J" raises a TypeError. Every string method returns a new string and leaves the original alone, which is why you must keep the result: name.strip() on its own line does nothing useful, but name = name.strip() does. Methods are called with a dot after the value.

Everyday string methods
MethodExampleResult
strip()" hi ".strip()"hi" (also lstrip, rstrip)
lower() / upper() / title()"aNa".title()"Ana"
replace(old, new)"a-b-c".replace("-", "/")"a/b/c"
split(sep)"a,b,c".split(",")["a", "b", "c"]; with no argument it splits on any spaces
sep.join(list)"-".join(["a", "b"])"a-b"
startswith / endswith"report.csv".endswith(".csv")True
find(sub) / count(sub)"banana".count("a")3 (find gives the first index, or -1)
isdigit()"42".isdigit()True

Worked example: cleaning an email address someone typed

  1. The user typed " Ana.Lopez@SHOP.example ", with spaces and odd capitals.
  2. email = raw.strip().lower() removes the outer spaces, then makes it lower case: "ana.lopez@shop.example". Each method works on the result of the one before.
  3. "@" in email is True: the in operator checks for a piece of text.
  4. user, domain = email.split("@") splits at the @ into two strings, "ana.lopez" and "shop.example".

Cleaning input before storing or comparing it is routine at work: "Ana@x" and " ana@x " should be the same customer.

Hands-on lab in the room: Python playground.

Hands-on lab in the room: Unit 2 coding exercises. Graded exercise: chain three string methods.

Index
The position of an item in a sequence, starting at 0; negative indexes count from the end.
Slice
A piece of a sequence, s[start:stop], from start up to but not including stop.
Immutable
Unable to change after creation. Strings and tuples are immutable.
Method
A function that belongs to a value, called with a dot: name.upper().
Sequence
An ordered collection you can index and slice, such as a string, list or tuple.

Remember: Indexes start at 0; slices stop before the stop index. String methods return new strings, so keep the result.

Lesson 2: Booleans, comparisons and logic

Goal: Write comparisons, combine them with and, or and not, and predict truthiness.

Programs make decisions by asking yes-or-no questions. In Python the answer is a bool: True or False. Comparison operators produce bools: == (equal), != (not equal), <, >, <= and >=. Note the difference between =, which assigns, and ==, which asks whether two values are equal. Python also allows chained comparisons that read like maths: 0 < age < 120.

Strings compare character by character, by their character codes, which is roughly alphabetical with one catch: every capital letter comes before every lower-case letter, so "Zoe" < "ana" is True. Comparing text that holds numbers is a classic bug: "9" > "10" is True, because the character 9 comes after 1. Convert to numbers before comparing numbers.

Logical operators
OperatorTrue whenExample
a and bboth are trueage >= 18 and has_ticket
a or bat least one is trueday == "Sat" or day == "Sun"
not aa is falsenot is_closed

and and or are short-circuit operators: Python stops as soon as the answer is known. In count > 0 and total / count > 10, the division never runs when count is 0, which prevents a ZeroDivisionError. Use parentheses when you mix and with or, so the meaning is obvious.

Truthiness: anywhere Python expects a bool, it accepts other values. These are falsy (treated as False): 0, 0.0, "" (the empty string), [], {}, set() and None. Almost everything else is truthy. So if name: means "if name is not empty", and if items: means "if the list has anything in it". To test for None, write if result is None:; is checks that it is that exact object.

answer = "no"
if answer == "yes" or "y":
    print("Python thinks the answer is yes!")

Worked example: the "or" trap

  1. Python reads the condition as (answer == "yes") or ("y").
  2. answer == "yes" is False, so or looks at its right side: the string "y".
  3. "y" is a non-empty string, so it is truthy, and the whole condition is truthy.
  4. The fix compares twice, answer == "yes" or answer == "y", or uses membership: answer in ("yes", "y").

This bug is common enough that the debugging lab has a version of it.

Hands-on lab in the room: Python playground.

Boolean expression
An expression that evaluates to True or False, such as age >= 18 and has_ticket.
Comparison operator
An operator that compares two values and gives a bool: == != < > <= >=.
Short-circuit
and/or stop evaluating as soon as the result is known.
Truthy / falsy
Values treated as True or False in a condition; 0, empty strings and collections, and None are falsy.
is
An operator that checks whether two names refer to the very same object; use it for None.

Remember: = assigns, == compares. Empty things, zero and None are falsy. Write each comparison in full: x == "a" or x == "b".

Lesson 3: if, elif and else

Goal: Choose between paths with if, elif and else, order conditions correctly and read indentation as structure.

An if statement runs a block of code only when its condition is truthy. The line ends with a colon, and the block is every following line indented one level further (four spaces is the standard). In Python, indentation is not decoration: it decides which lines belong to the if. The first line back at the outer level is no longer part of it.

temp = 31
if temp >= 30:
    print("Hot day")        # inside the if
    print("Drink water")    # inside the if
print("Done")               # always runs

elif (short for else if) adds more conditions and else catches everything left. Python checks the conditions from top to bottom and runs only the first block whose condition is true; the rest are skipped, even if they would also be true. That makes order matter: put the most specific or most extreme case first.

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)

Worked example: grading a score, and an ordering bug

  1. 85 >= 90 is False, so Python moves on.
  2. 85 >= 80 is True, so grade = "B" runs and the rest of the chain is skipped.
  3. Each elif can be simple because the ones above have already ruled out bigger scores.
  4. Bug: if the score >= 70 test came first, every score of 70 or more, including 95, would get a C, because the first true branch wins.

Output: B. Test the boundaries (90, 89, 80, 70, 69) to prove a chain like this is right.

You can nest an if inside another, but deep nesting is hard to read. Often a combined condition (if member and total > 50:) or an early exit is clearer. For a simple either-or value there is the conditional expression: label = "even" if n % 2 == 0 else "odd". If a block must exist but should do nothing yet, write pass.

Hands-on lab in the room: Python playground. Try the boundaries: set score to 90, 89, 70 and 69 and predict each grade first.

Hands-on lab in the room: Unit 2 coding exercises. Graded exercise: a three-way decision with careful boundaries.

Block
The indented lines that belong to a statement ending with a colon, such as an if or a loop.
Indentation
Spaces at the start of a line; in Python it defines which block a line belongs to.
elif
Short for "else if": another condition, checked only when all the earlier ones were false.
Conditional expression
A one-line choice between two values: a if condition else b.
pass
A statement that does nothing, used where a block is required but no code is needed yet.

Remember: Python runs only the first true branch of an if/elif chain, so order matters. Indentation decides what is inside.

Lesson 4: while loops

Goal: Repeat code with while, stop it with a condition, a sentinel or break, and spot loops that never end.

A while loop repeats its block as long as its condition is true. Python checks the condition, runs the block, checks again, and so on; the moment the condition is false at a check, the loop ends and the program continues after it. For the loop to end, something inside it must eventually make the condition false.

count = 3
while count > 0:
    print("Count:", count)
    count -= 1          # moves the loop toward its end
print("Liftoff!")

Forget that last step and you have an infinite loop: the condition stays true forever. On your own computer you would press Ctrl+C; in this page, press Stop, or the program is stopped after 10 seconds. An infinite loop is not a disaster, just a bug: find the variable the condition depends on and check that the loop really changes it.

break leaves a loop immediately, and continue skips the rest of this round and goes back to the condition. A common, clear pattern for "keep asking until the user says stop" is while True: with a break. A special value that means stop, such as done or an empty line, is called a sentinel.

while True:
    text = input("Quantity (1-10): ").strip()
    if not text.isdigit():
        print("Please type a whole number.")
        continue                     # back to the top: ask again
    qty = int(text)
    if 1 <= qty <= 10:
        break                        # valid: leave the loop
    print("Between 1 and 10, please.")
print("You chose", qty)

Worked example: asking until the input is valid

  1. Input abc: isdigit() is False, so it prints a message and continue jumps back to ask again.
  2. Input 40: it is a number but out of range, so the loop prints a reminder and repeats.
  3. Input 4: in range, so break ends the loop and the last line runs.
  4. The loop has two different exits: a message plus another try, or a valid value plus break.

Validation loops like this protect every program that takes input from people.

Hands-on lab in the room: Python playground. The program input gives it three tries: abc, 40 and 4. Change them and predict the output.

Hands-on lab in the room: Unit 2 coding exercises. Graded exercise: a sentinel loop with a running total.

while loop
A loop that repeats its block as long as its condition is true.
Infinite loop
A loop whose condition never becomes false, so it never ends on its own.
break
A statement that ends the loop it is in immediately.
continue
A statement that skips the rest of the current round of a loop.
Sentinel
A special value, such as "done", that signals the end of input.

Remember: A while loop needs something inside it that moves toward the end. while True plus break is the clean way to loop until a sentinel.

Practise it in Python Programming

Each lesson ends with three questions that check you can use the idea, not just recognise it. Wrong answers explain why and come back in Review. The unit ends with a 7-question quiz; pass it with 80% or more to master the unit. Hands-on lab: Unit 2 coding exercises.

Every lesson is free: no ads, no lives and no paywall.