Python,
Week 2
Meaningful names, string methods, conditionals and your first modules: where Python code starts to look like real programs.
Chapters
Variables: Names, Comments and Typing
How to name variables, document code, assign several names at once and update values with short-hand operators.
1.1Meaningful variable names
Programmers write variables all the time, so a name that describes the stored information makes a program easier to read. Names such as a, b or x are fine for a tiny calculation, but they hide what the value means.
a = "Ayush"
b = 18
print(a)
print(b)Ayush
18name = "Ayush"
age = 18
print(name)
print(age)Ayush
18Meaningful names improve readability and make the purpose of a variable clear. The output is the same; only the human reading it benefits.
1.2Comments
Comments explain code to other people. A # starts a single-line comment; Python ignores everything after it on that line.
name = "Ayush"
# This variable stores my name
age = 18
# This variable stores my age
print(name)
print(age)Ayush
18#starts a single-line comment.- Comments are ignored during execution.
- Their purpose is explanation and understanding.
x = 5 # a comment can follow code on the same line
# print("this line never runs")
print(x)51.3Dynamic typing
Python is a dynamically typed language: a variable can refer to values of different types at different points of the run. You never declare a type before assigning.
thing = "Hello World"
print(type(thing))
thing = 12
print(type(thing))<class 'str'>
<class 'int'>1.4Rules for variable names
- Start with a letter or underscore (
_); never with a digit. - Names are case-sensitive:
ageandAgeare different. - Only letters, digits and underscores are allowed.
- It must not be a keyword (
and,or,not,for,if,else,while, ...).
| Name | Valid? | Why |
|---|---|---|
student_name | valid | letters and underscore |
_age | valid | may start with an underscore |
marks2 | valid | digit is fine after the first character |
2nd_place | invalid | starts with a digit |
first-name | invalid | - is not allowed |
for | invalid | reserved keyword |
student_name = "A"
_age = 20
marks2 = 95
print(student_name, _age, marks2)A 20 95age = 18
print(Age)NameError: name 'Age' is not definedThe last block shows case-sensitivity: Age was never created, so Python raises a NameError.
1.5Multiple assignment and unpacking
x, y = 1, 2
print(x, y)1 2x = y = z = 8
print(x, y, z)8 8 8x, y = 1, 2 gives each name its own value; x = y = z = 8 gives all the names the same value. Values taken from a collection can be unpacked into several names:
a, b, c = (100, 200, 300)
print(a)
print(b)
print(c)
print(type(a), type(b))100
200
300
<class 'int'> <class 'int'>a, b = 1, 2, 3ValueError: too many values to unpack (expected 2, got 3)ValueError.1.6Deleting a variable
x = 3
print(x)
del x
print(x)3
NameError: name 'x' is not definedAfter del x the name no longer exists, so using it raises a NameError. (The source shows the last print as a comment for this reason.)
1.7Short-hand assignment operators
| Operator | Example | Equivalent |
|---|---|---|
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
//= | x //= 3 | x = x // 3 |
**= | x **= 3 | x = x ** 3 |
x = 10
x += 3
print("+= ", x)
x -= 2
print("-= ", x)
x *= 2
print("*= ", x)
x /= 2
print("/= ", x)
x %= 3
print("%= ", x)
x //= 2
print("//= ", x)
x **= 3
print("**= ", x)+= 13
-= 11
*= 22
/= 11.0
%= 2.0
//= 1.0
**= 1.0After x /= 2 the value becomes a float (11.0), so every later step stays a float: 2.0, 1.0, 1.0.
1.8Going deeper
- Naming style (extra). Python programmers usually write multi-word names in
snake_casesuch asstudent_name. - The same operator works on strings (extra).
s += "x"meanss = s + "x". - Swapping (extra). The tuple form makes a swap one line:
x, y = y, x.
s = "Py"
s += "thon"
print(s)
x, y = 1, 2
x, y = y, x
print(x, y)Python
2 11.9Exam tips and common mistakes
- For "is this a valid name?" check the four rules in order: first character, allowed characters, keyword, then case only matters when comparing two names.
- Trace short-hand operators line by line and write the type (int or float) next to each value.
- Writing
first-nameor2nd_placeas a name. - Using a variable after
del. - Forgetting that
/=turns an int into a float. - Unpacking three values into two names.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
Which of these is a valid variable name?
2nd_placefirst-name_totalforCheck the first character, the allowed characters and the keyword list.
_totalstarts with an underscore and has only allowed characters.2nd_placestarts with a digit,first-namehas a hyphen, andforis a keyword.- Answer: option 3.
Numerical Answer Type (NAT).
What does this program print?
x = 10
x += 3
x -= 2
x *= 2
x /= 2
x %= 3
x //= 2
x **= 3
print(x)Trace x line by line; after /= it is a float.
x = 10
x += 3
x -= 2
x *= 2
x /= 2
x %= 3
x //= 2
x **= 3
print(x)1.0- 10 → 13 → 11 → 22 →
11.0→2.0→1.0→1.0. - Answer: 1.0
Multiple Choice Question (MCQ): choose the one correct option.
What does the program do?
x = y = z = 8
print(x, z)
del y
print(y)8 8 only8 8, then raises a NameError for yNonedel y removes only the name y.
x = y = z = 8
print(x, z)
del y
print(y)8 8
NameError: name 'y' is not definedx = y = z = 8gives all three names the value 8;print(x, z)prints8 8.- After
del y,print(y)raisesNameError. - Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What happens when this runs?
a, b = 1, 2, 31 21 2 3Count the names and the values.
a, b = 1, 2, 3ValueError: too many values to unpack (expected 2, got 3)- Two names but three values: the numbers do not match, so Python raises
ValueError. - Answer: option 3.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
Age and age are the same variable.Recall dynamic typing and case-sensitivity.
- Statements 1 and 3 are true.
- Statement 2 is false (no declaration), and statement 4 is false (names are case-sensitive).
- Answer: options 1 and 3.
Numerical Answer Type (NAT).
What is printed? (Give the two numbers separated by a space.)
x, y = 1, 2
x, y = y, x
print(x, y)The right side is evaluated first.
x, y = 1, 2
x, y = y, x
print(x, y)2 1x, y = y, xbuilds(2, 1)first and then assigns, so the values swap.- Answer: 2 1
snake_case (extra)
No -, no keywords
Case-sensitive
the type
x = y = z = 8
unpacking: counts match
then x is a NameError
/= gives a float
Operators and Strings: Membership, Chaining, Escapes, Quotes
Testing membership, chaining comparisons, and writing special characters and multi-line text in strings.
2.1Membership operators
| Operator | Meaning | Example |
|---|---|---|
in | value is present | x in y |
not in | value is not present | x not in y |
sentence = "I am Ayush"
print("Ayush" in sentence)
print("boy" not in sentence)True
TrueA membership test always gives True or False. For strings it checks for a substring, not just a whole word.
sentence = "I am Ayush"
print("Ay" in sentence)
print("ayush" in sentence)
print(" " in sentence)
print(3 in [1, 2, 3])True
False
True
True"ayush" in sentence is False. For a list, in needs a whole element.2.2Chaining comparison operators
x < y < z is equivalent to x < y and y < z. The middle expression is evaluated only once. Similarly a < b > c means (a < b) and (b > c).
x = 5
print(1 < x < 10)
print(10 < x < 20)
print(x < 10 < x * 10 < 100)True
False
True1 < 5 < 10: both1 < 5and5 < 10are true, soTrue.10 < 5 < 20: the first test10 < 5is false, soFalse.5 < 10 < 50 < 100: three tests, all true, soTrue.
a, b, c = 1, 5, 3
print(a < b > c)
print((a < b) and (b > c))True
True2.3Escape characters
| Escape | Result |
|---|---|
\' | single quote |
\" | double quote |
\n | new line |
\t | tab |
print("It's Python")
print("He said \"Hello\"")
print("First line\nSecond line")
print("Name:\tEngiKode")It's Python
He said "Hello"
First line
Second line
Name: EngiKodetext = 'We are the so called \'Viking\' from north.'
print(text)We are the so called 'Viking' from north.\n is written with two characters but is stored as one: len("a\tb") is 3.2.4Different types of quotes
- Single quotes
'...'and double quotes"..."make ordinary strings; they behave the same. - Triple quotes (
'''...'''or"""...""") can span multiple lines.
single = 'Python'
double = "Python"
triple_single = '''Python
Week 2'''
triple_double = """EngiKode
Python"""
print(single)
print(double)
print(triple_single)
print(triple_double)Python
Python
Python
Week 2
EngiKode
Python"It's Python" needs no backslash because the outer quotes are double. Use whichever quote type does not appear inside the text.
2.5Exam tips and common mistakes
- Expand a chain into
andparts and test them left to right; stop at the first false part. - Read the escape sequences first, then count what is printed on each line.
- Treating
\nas two printed characters. - Thinking
a < b < ccomparesawithconly. - Forgetting that
inis case-sensitive.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
x = 5
print(1 < x < 10)
print(10 < x < 20)
print(x < 10 < x * 10 < 100)True False True on three linesTrue True True on three linesFalse False True on three linesExpand each chain into and parts.
x = 5
print(1 < x < 10)
print(10 < x < 20)
print(x < 10 < x * 10 < 100)True
False
True1 < 5 < 10: True.10 < 5 < 20: False.5 < 10 < 50 < 100: True.- Answer: option 1.
Multiple Select Question (MSQ): select all that apply.
With s = "I am Ayush", which expressions are True?
s = "I am Ayush"
print("Ayush" in s)
print("boy" not in s)
print("ayush" in s)
print("Ay" in s)"Ayush" in s"boy" not in s"ayush" in s"Ay" in sStrings are searched for substrings, with case.
s = "I am Ayush"
print("Ayush" in s)
print("boy" not in s)
print("ayush" in s)
print("Ay" in s)True
True
False
True- Options 1, 2 and 4 are True. Option 3 is False because of the lower-case
a. - Answer: options 1, 2 and 4.
Multiple Choice Question (MCQ): choose the one correct option.
How many lines does this print, and what does the second one show?
print("First\n\tEngiKode")Second line shown with a tabEngiKode\tEngiKode as text\n breaks the line, \t inserts a tab.
print("First\n\tEngiKode")First
EngiKode\nends the first line, so there are two lines.\tis a tab character, so the second line starts with a tab space beforeEngiKode.- Answer: option 2.
Numerical Answer Type (NAT).
What does the program print?
print(len("a\tb\n"))Each escape is a single character.
print(len("a\tb\n"))4"a\tb\n"has the charactersa, tab,b, newline: 4.- Answer: 4
Multiple Choice Question (MCQ): choose the one correct option.
With a = 1, b = 5, c = 9, what is a < b > c?
a, b, c = 1, 5, 9
print(a < b > c)TrueFalse5It means (a < b) and (b > c).
a, b, c = 1, 5, 9
print(a < b > c)False1 < 5is True but5 > 9is False, so the whole chain isFalse.- Answer: option 2.
True or False
substring for strings
x < y and y < z
one character each
triple spans lines
String Methods and the Caesar Cipher
The Week 2 string methods, and a cipher that shifts letters with % 26.
Week 2 has a large set of string methods. For each one know what it does and whether it transforms the string (returns a new string) or checks a condition (returns True/False).
3.1Case methods: lower, upper, capitalize, title, swapcase
| Method | What it does | Result for the sample |
|---|---|---|
lower() | all characters lowercase | python |
upper() | all characters uppercase | PYTHON |
capitalize() | first character uppercase | I love python |
title() | first character of each word uppercase | I Love Python |
swapcase() | lower ↔ upper | pYthON |
x = "PyTHon"
print(x.lower())
print(x.upper())
print(x.swapcase())
y = "i love python"
print(y.capitalize())
print(y.title())python
PYTHON
pYthON
I love python
I Love Python3.2Check methods: islower, isupper, istitle, isdigit, isalpha, isalnum
These return True or False.
| Method | True when | Example |
|---|---|---|
islower() | all (cased) characters are lowercase | "python".islower() → True, "Python".islower() → False |
isupper() | all (cased) characters are uppercase | "PYTHON".isupper() → True, "Python".isupper() → False |
istitle() | title-case rules hold | "Python String Methods".istitle() → True |
isdigit() | all characters are digits | "123".isdigit() → True, "123abc".isdigit() → False |
isalpha() | all characters are letters | "abc".isalpha() → True, "abc123".isalpha() → False |
isalnum() | all characters are letters or digits | "abc123".isalnum() → True, "abc123#".isalnum() → False |
print("python".islower())
print("Python".islower())
print("PYTHON".isupper())
print("Python".isupper())
print("Python String Methods".istitle())
print("Python string methods".istitle())
print("123".isdigit())
print("123abc".isdigit())
print("abc".isalpha())
print("abc123".isalpha())
print("abc123".isalnum())
print("abc123#".isalnum())True
False
True
False
True
False
True
False
True
False
True
False"".isdigit() (an empty string) is False, and a space or # is neither a letter nor a digit, which is why "abc123#".isalnum() is False.3.3Trimming: strip, lstrip, rstrip
| Method | Purpose |
|---|---|
strip() | removes specified characters from both ends |
lstrip() | removes them from the left |
rstrip() | removes them from the right |
x = "---Python---"
print(x.strip("-"))
print(x.lstrip("-"))
print(x.rstrip("-"))Python
Python---
---Pythonstrip() removes whitespace. Characters in the middle are never removed.print(" hi ".strip() + "|")
print("--a-b--".strip("-"))hi|
a-b3.4Searching and replacing
| Method | Returns |
|---|---|
startswith(v) | True if the string starts with v |
endswith(v) | True if it ends with v |
count(v) | how many times v occurs |
index(v) | position of v; ValueError if absent |
replace(old, new) | a string with old replaced by new |
x = "Python"
print(x.startswith("P"))
print(x.startswith("p"))
print(x.endswith("n"))
print(x.endswith("N"))True
False
True
Falsex = "python string methods"
print(x.count("t"))
print(x.count("s"))
print("python".index("t"))3
2
2x = "python string methods"
x = x.replace("python", "Python")
x = x.replace("methods", "Methods")
print(x)Python string Methodsprint("python".index("z"))ValueError: substring not foundindex() raises ValueError when the value is not found. (Extra: find() returns -1 instead.)3.5Methods return new strings
Strings cannot be changed in place. A method such as upper() or replace() returns a new string and leaves the original untouched. That is why the replace example assigns back: x = x.replace(...).
x = "python"
x.upper()
print(x)
x = x.upper()
print(x)python
PYTHON3.6Quick table
| Method | Main use |
|---|---|
lower() upper() | lowercase / uppercase |
capitalize() title() | first character / each word |
swapcase() | swap letter case |
islower() isupper() istitle() | case checks |
isdigit() isalpha() isalnum() | content checks |
strip() lstrip() rstrip() | trim both / left / right |
startswith() endswith() | start / end checks |
count() index() replace() | count, find position, replace |
3.7The Caesar cipher
A Caesar cipher is a substitution technique: each character is replaced by the character a fixed number of places further along the alphabet. The fixed number is the shift. With a shift of 1: A → B, B → C, C → D, ...
The alphabet has 26 letters, so % 26 wraps an index that goes beyond 25 back to the start:
alpha = "abcdefghijklmnopqrstuvwxyz"
i = 25
print(alpha[i % 26])
j = 28
print(alpha[j % 26])
k = 26
print(alpha[k % 26])z
c
aalpha[(alpha.index(character) + shift) % 26]
Find the letter's position, add the shift, wrap with % 26, and read the letter at the new position.
alpha = "abcdefghijklmnopqrstuvwxyz"
name = "sky"
copy = ""
k = 1
copy = copy + alpha[(alpha.index(name[0]) + k) % 26]
copy = copy + alpha[(alpha.index(name[1]) + k) % 26]
copy = copy + alpha[(alpha.index(name[2]) + k) % 26]
print(copy)tlz| Letter | Index | + shift 1 | % 26 | New letter |
|---|---|---|---|---|
| s | 18 | 19 | 19 | t |
| k | 10 | 11 | 11 | l |
| y | 24 | 25 | 25 | z |
3.8Going deeper
- Wrap-around with y (extra). With shift 3,
y(index 24) goes to27 % 26 = 1, which isb. - Decoding (extra). Subtract the shift instead:
(index - k) % 26. Python's%never gives a negative result here, so(0 - 1) % 26is25. - Typing less (extra). The three repeated lines can be written as a loop over the letters (loops come later in the course).
alpha = "abcdefghijklmnopqrstuvwxyz"
name = "sky"
copy = ""
k = 3
for ch in name:
copy = copy + alpha[(alpha.index(ch) + k) % 26]
print(copy)
print((0 - 1) % 26)vnb
253.9find, split and join: the string tools that programs use most
Section 3.4 introduced index(), count() and replace(). Three more tools finish the toolkit: find() (a safer index()), split() and join(). The last two are how a program turns one line of typed input into several values, and back.
A. find, rfind, index and count in detail
s.find(v)returns the position of the first match, or-1if there is none.s.index(v)does the same but raisesValueErrorwhen there is none.s.rfind(v)searches from the right and gives the position of the last match.- All of them accept optional
startandendpositions:s.find(v, 3)starts looking at index 3. s.count(v)counts non-overlapping matches, scanning left to right.s.replace(old, new, k)replaces only the firstkmatches when you givek.v in sanswers only "is it there?" (True/False);findalso says where.
s = "banana bandana"
print(s.find("ana")) # first match
print(s.find("ana", 3)) # start looking at index 3
print(s.rfind("ana")) # last match
print(s.find("xyz")) # not found: -1, no error
print(s.count("ana")) # non-overlapping matches
print("aaaa".count("aa")) # 2, not 3: matches do not overlap
print(s.replace("ana", "ANA", 1)) # only the first match1
3
11
-1
2
2
bANAna bandanaprint("banana".index("xyz"))ValueError: substring not foundfind when "not present" is a normal outcome you will test for (if s.find(v) == -1). Use index when absence would be a bug. A classic slip: if s.find("a"): is wrong, because -1 is truthy and a match at position 0 is falsy. Write if s.find("a") != -1: or if "a" in s:.B. split and join
s.split()with no argument splits on any run of whitespace and drops empty pieces.s.split(sep)splits at everysepand keeps empty pieces.s.split(sep, 1)splits at most once. The result is always a list of strings.sep.join(list_of_strings)glues the pieces together withsepbetween them. The separator is the string you calljoinon; the list is the argument.- Reading numbers:
input()returns one string, soa, b = input().split()splits a line like"3 4"into two strings, and each still needsint().
print("a,b,,c".split(",")) # empty piece is kept
print(" a b ".split()) # whitespace: no empty pieces
print("a-b-c".split("-", 1)) # at most one split
print("-".join(["x", "y", "z"]))
print("".join(reversed("abc"))) # reverse a string
line = "3 4" # what input() would return
a, b = line.split()
print(a, b, "sum", int(a) + int(b))['a', 'b', '', 'c']
['a', 'b']
['a', 'b-c']
x-y-z
cba
3 4 sum 7"3 4".split() gives ["3", "4"], two strings. Adding them directly gives "34", not 7. Convert each piece with int() first.C. A few more checks and a palindrome test
startswithandendswithaccept a tuple of alternatives:name.endswith((".csv", ".txt")).isalnum()is True when every character is a letter or digit (and the string is non-empty);isspace()when every character is whitespace;isdigit()only for the digits0to9, so"-12"and"3.5"are False.- A word is a palindrome when it equals its reverse:
s == s[::-1]. For a test that ignores case, lower both sides first.
print("file.csv".endswith((".csv", ".txt")))
print("abc 123".isalnum())
print(" ".isspace())
print("-12".isdigit())
print("3.5".isdigit())
print("level" == "level"[::-1])
print("Level".lower() == "Level".lower()[::-1])True
False
True
False
False
True
True3.10Exam tips and common mistakes
- Label each method as a transform or a check before predicting output.
- For the cipher, write the index of every letter first, then add the shift, then
% 26.
- Expecting
x.upper()to changexwithout assigning the result. - Using
index()for a value that may be absent: it raisesValueError. - Forgetting
% 26, which fails for letters near the end such asz. - Confusing
strip("-")(removes dashes at the ends) withreplace("-", "")(removes all dashes).
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does this print?
print("i love python".title())
print("PyTHon".swapcase())I Love Python then pYthONI love python then pYthONI Love Python then PYTHONi love python then pythOntitle() capitalises every word; swapcase() flips every letter.
print("i love python".title())
print("PyTHon".swapcase())I Love Python
pYthON"i love python".title()isI Love Python."PyTHon".swapcase()ispYthON.- Answer: option 1.
Numerical Answer Type (NAT).
What does the program print?
x = "python string methods"
print(x.count("t") + x.count("s"))Add the two counts.
x = "python string methods"
print(x.count("t") + x.count("s"))5"t"occurs 3 times (python, string, methods) and"s"occurs 2 times (string, methods): 3 + 2 = 5.- Answer: 5
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
x = "---Python---"
print(x.rstrip("-"))Python------PythonPython---Python---rstrip trims the right end only.
x = "---Python---"
print(x.rstrip("-"))---Pythonrstrip("-")removes the three dashes at the right, leaving---Python.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What happens?
print("python".index("z"))-1None0index() raises an error when the value is absent.
print("python".index("z"))ValueError: substring not found"python"has noz, soindex("z")raisesValueError.- Answer: option 3.
Numerical Answer Type (NAT).
What does this print?
alpha = "abcdefghijklmnopqrstuvwxyz"
print(alpha[(alpha.index("s") + 3) % 26] + alpha[(alpha.index("k") + 3) % 26] + alpha[(alpha.index("y") + 3) % 26])Add 3 to each index and wrap with % 26.
alpha = "abcdefghijklmnopqrstuvwxyz"
print(alpha[(alpha.index("s") + 3) % 26] + alpha[(alpha.index("k") + 3) % 26] + alpha[(alpha.index("y") + 3) % 26])vnb- s(18)+3 = 21 → v; k(10)+3 = 13 → n; y(24)+3 = 27 → 27 % 26 = 1 → b.
- Answer: vnb
Multiple Select Question (MSQ): select all that apply.
Which of these return True/False (checks)?
isdigit()upper()startswith()replace()A check answers a yes/no question.
isdigit()andstartswith()return booleans.upper()andreplace()return new strings.- Answer: options 1 and 3.
Numerical Answer Type (NAT).
What does this print?
alpha = "abcdefghijklmnopqrstuvwxyz"
j = 28
print(alpha[j % 26])Compute 28 % 26 first.
alpha = "abcdefghijklmnopqrstuvwxyz"
j = 28
print(alpha[j % 26])c28 % 26 = 2, andalpha[2]isc.- Answer: c
Multiple Select Question (MSQ): select all that apply.
Consider s = "Mississippi". Select all the true statements.
s.find("ss") is 2s.find("ss", 3) is 5s.count("ss") is 2s.find("z") raises a ValueErrors.rfind("ss") is 5Index the letters: M0 i1 s2 s3 i4 s5 s6 i7 p8 p9 i10. Run each call.
s = "Mississippi"
print(s.find("ss"))
print(s.find("ss", 3))
print(s.count("ss"))
print(s.find("z"))
print(s.rfind("ss"))2
5
2
-1
5- 1 ✓ first
ssstarts at index 2. 2 ✓ searching from 3 skips the first and finds index 5. 3 ✓ two non-overlapping matches. - 4 ✗
findreturns-1; it isindexthat raisesValueError. 5 ✓ the last match starts at index 5. - Answer: options 1, 2, 3 and 5.
Numerical Answer Type (NAT).
What does the program print?
print("aaaaa".count("aa"))count scans left to right and never reuses characters.
print("aaaaa".count("aa"))2- Match at positions 0 to 1, then the scan resumes at 2 and matches 2 to 3; the final
ais left over. Two matches. - Counting overlapping matches (positions 0, 1, 2, 3) would give 4. That is not what
countdoes. - Answer: 2
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
line = "10 20 30"
parts = line.split()
print(parts[0] + parts[1])30102010 20split() returns a list of strings; + on strings joins them.
line = "10 20 30"
parts = line.split()
print(parts[0] + parts[1])1020partsis['10', '20', '30']."10" + "20"is"1020". To add the numbers writeint(parts[0]) + int(parts[1]), which is30.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What is printed by the program?
s = "banana"
print(s.replace("a", "o", 2))bononobononabononbbonanaThe third argument is the maximum number of replacements, counted from the left.
s = "banana"
print(s.replace("a", "o", 2))bonona- The first two
as (positions 1 and 3) becomeo; the last stays. Resultbonona. - Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Which of the following print yhp?
print("php"[::-1])print("".join(reversed("phy")))print("phy"[::-1])print("-".join("phy")[::-1])Reversing "phy" gives "yhp". Check each option.
print("php"[::-1])
print("".join(reversed("phy")))
print("phy"[::-1])
print("-".join("phy")[::-1])php
yhp
yhp
y-h-p- 1 ✗ reverses
php(a palindrome), givingphp. 2 ✓. 3 ✓. - 4 ✗
"-".join("phy")isp-h-y, and its reverse isy-h-pwith the hyphens. - Answer: options 2 and 3.
title swapcase
isdigit isalpha isalnum
→ True / False
count index replace
index raises ValueError
Conditional Statements
if, else, elif, logical operators, nested if and the conditional expression.
Decision-making lets a program run different statements depending on a condition. This part covers if, if...else, if...elif...else, logical operators in conditions, nested if and the conditional (ternary) expression.
4.1The if statement
if expression: followed by an indented block of statement(s).
The block runs only when the expression is True. Statements of the block must be indented consistently.
x = 10
y = 5
if x > y:
text = "Hello World"
print(text)Hello Worldx = 3
y = 5
if x > y:
text = "Hello World"
print(text)NameError: name 'text' is not definedThe second program shows what happens when the condition is false: the block is skipped, text is never created, and print(text) raises a NameError. (Extra.)
4.2if ... else
age = 15
if age >= 18:
print("User is old enough")
else:
print("User is not old enough")User is not old enoughelse has no condition; it runs when the if condition is false.
4.3if ... elif ... else
x = 5
if x > 10:
print("Yes")
elif x < 10:
print("No")
else:
print("x is 10")Nox = 10
if x > 10:
print("x is more than 10")
elif x < 10:
print("x is less than 10")
else:
print("x is 10 because it is neither more nor less")x is 10 because it is neither more nor lessOnce a branch runs, the remaining elif and else parts are skipped, even if they would also be true. So the order of branches matters.
x = 95
if x > 50:
print("above 50")
elif x > 90:
print("above 90")above 504.4Logical operators in conditions
Use and (both must be true) and or (at least one must be true) to combine tests.
x = 10
y = 5
if (x == 10) and (y == 5):
text = "Hello World"
print(text)
if (x == 10) or (y == 10):
print("At least one condition is true")Hello World
At least one condition is true| Expression | x = 10, y = 5 |
|---|---|
(x == 10) and (y == 5) | True |
(x == 10) and (y == 10) | False |
(x == 10) or (y == 10) | True |
(x == 0) or (y == 0) | False |
4.5Nested if
An if can sit inside another if (or else). The inner test runs only if the outer one let the program in.
x = 15
if x > 5:
print("x is more than 5")
if x > 10:
print("x is more than 10")
else:
print("x is between 5 and 10")
else:
print("x is 5 or below")x is more than 5
x is more than 10| x | Output |
|---|---|
| 15 | more than 10 |
| 8 | between 5 and 10 |
| 3 | 5 or below |
4.6Conditional (ternary) expression
value_if_true if condition else value_if_false
A one-line choice between two values, handy for simple assignments.
x = 10
text = "x is 10" if x == 10 else "x is not 10"
print(text)x is 10x = 7
print("even" if x % 2 == 0 else "odd")odd4.7Going deeper
- Indentation is the syntax. A body that is not indented is an
IndentationError(extra). - Use
==to compare. A single=assigns and is a syntax error inside anif(extra). - elif versus separate ifs (extra). Separate
ifstatements are all tested; anelifchain stops at the first true branch.
x = 95
if x > 50:
print("above 50")
if x > 90:
print("above 90")above 50
above 90x = 5
if x > 3:
print("big")IndentationError: expected an indented block after 'if' statement on line 24.8Exam tips and common mistakes
- Trace from the top: test the first condition, run its block if true and skip everything else in the chain.
- For nested ifs, indent level tells you which
elsebelongs to whichif.
- Writing
=instead of==in a condition. - Forgetting the colon after
if,eliforelse. - Putting a broader test before a narrower one in an
elifchain. - Mixing indentation levels.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
x = 5
if x > 10:
print("Yes")
elif x < 10:
print("No")
else:
print("x is 10")YesNox is 10Test the conditions top to bottom.
x = 5
if x > 10:
print("Yes")
elif x < 10:
print("No")
else:
print("x is 10")No5 > 10is false,5 < 10is true, soNois printed and the rest is skipped.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What is printed?
x = 95
if x > 50:
print("above 50")
elif x > 90:
print("above 90")above 90above 50The first true branch wins.
x = 95
if x > 50:
print("above 50")
elif x > 90:
print("above 90")above 5095 > 50is true, so the first block runs and theelifis never tested.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What is printed for x = 8?
x = 8
if x > 5:
if x > 10:
print("x is more than 10")
else:
print("x is between 5 and 10")
else:
print("x is 5 or below")x is more than 10x is between 5 and 10x is 5 or belowThe outer test passes; then decide the inner one.
x = 8
if x > 5:
if x > 10:
print("x is more than 10")
else:
print("x is between 5 and 10")
else:
print("x is 5 or below")x is between 5 and 108 > 5is true, so the outer block runs;8 > 10is false, so the innerelseprints.- Answer: option 2.
Numerical Answer Type (NAT).
What does the program print?
x = 11
text = "x is 10" if x == 10 else "x is not 10"
print(text)The condition decides which value is chosen.
x = 11
text = "x is 10" if x == 10 else "x is not 10"
print(text)x is not 10x == 10is false forx = 11, so the value afterelseis used.- Answer: x is not 10
Multiple Select Question (MSQ): select all that apply.
For x = 10, y = 5, which conditions are true?
x = 10
y = 5
print((x == 10) and (y == 5))
print((x == 10) and (y == 10))
print((x == 10) or (y == 10))
print((x == 0) or (y == 0))(x == 10) and (y == 5)(x == 10) and (y == 10)(x == 10) or (y == 10)(x == 0) or (y == 0)and needs both; or needs one.
x = 10
y = 5
print((x == 10) and (y == 5))
print((x == 10) and (y == 10))
print((x == 10) or (y == 10))
print((x == 0) or (y == 0))True
False
True
False- Options 1 and 3 are true.
- Option 2 fails on
y == 10; option 4 fails on both parts. - Answer: options 1 and 3.
Multiple Choice Question (MCQ): choose the one correct option.
What does this print?
x = 95
if x > 50:
print("above 50")
if x > 90:
print("above 90")above 50above 90above 50 then above 90Two separate if statements are both tested.
x = 95
if x > 50:
print("above 50")
if x > 90:
print("above 90")above 50
above 90- There is no
elif, so eachifis tested on its own and both are true. - Answer: option 3.
expression is True
elif: more conditions
first true wins
or: at least one
indent shows ownership
colon
branch order
Practice Zone
Four programs that turn decision rules into code, traced with real inputs.
Try each problem yourself before reading the solution. Every program below was run for real; the sample runs show what it prints.
5.1Problem 1: even or odd
Take an integer as input and decide whether it is even or odd. A number is even when dividing by 2 leaves remainder 0.
x = int(input("Enter a number: "))
if x % 2 == 0:
print("Even")
else:
print("Odd")Enter a number: 7
Odd| Input | Output |
|---|---|
| 7 | Odd |
| 10 | Even |
| 0 | Even |
| -3 | Odd |
-3 % 2 is 1 in Python, so negative odd numbers are still reported as Odd.5.2Problem 2: the last digit
Decide whether the last digit of a number is 0, 5 or something else. A last digit of 0 or 5 means the number is divisible by 5; among those, divisible by 10 means the last digit is 0. That is a nested if.
x = int(input("Enter a number: "))
if x % 5 == 0:
if x % 10 == 0:
print("0")
else:
print("5")
else:
print("Other")Enter a number: 25
5| Input | % 5 == 0 ? | % 10 == 0 ? | Output |
|---|---|---|---|
| 40 | yes | yes | 0 |
| 25 | yes | no | 5 |
| 7 | no | — | Other |
5.3Problem 3: student grade
| Grade | Marks (as given) |
|---|---|
| A | and |
| B | |
| C | |
| D | |
| E | and |
x = int(input("Enter your marks: "))
if x > 90 and x <= 100:
print("A")
elif x > 80:
print("B")
elif x >= 70:
print("C")
elif x >= 60:
print("D")
elif x <= 60 and x > 0:
print("E")
else:
print("Not Valid")Enter your marks: 72
C| Marks | Output | Why |
|---|---|---|
| 95 | A | first test: 95 > 90 and ≤ 100 |
| 85 | B | not A; 85 > 80 |
| 80 | C | 80 > 80 is false, so it falls to ≥ 70 |
| 72 | C | ≥ 70 |
| 60 | D | ≥ 60 is tested before the E branch |
| 30 | E | only the last branch fits |
| 0 | Not Valid | fails every test |
- Each
elifonly runs if every test above it was false, sox > 80really means "above 80 and not A". - The table says E is "≤ 60", but 60 is also "≥ 60" (D). The code resolves the overlap in favour of D, because D comes first.
B (the output for 105 above). A safer version checks the valid range first.x = int(input("Enter your marks: "))
if x <= 0 or x > 100:
print("Not Valid")
elif x > 90:
print("A")
elif x > 80:
print("B")
elif x >= 70:
print("C")
elif x >= 60:
print("D")
else:
print("E")Enter your marks: 105
Not Valid| Marks | Output (safer version) |
|---|---|
| 105 | Not Valid |
| 100 | A |
| 91 | A |
| 60 | D |
| 59 | E |
| 0 | Not Valid |
5.4Problem 4: travel decision
A flowchart problem: travel from City A to City B. First ask whether the trip time is longer or shorter than a threshold, then compare the price with a threshold to pick coach/train (long trip) or red-eye/daytime flight (short trip).
print("Travel from City A to City B")
time = int(input("Enter time: "))
longer = int(input("Define longer: "))
if time >= longer:
price = int(input("Enter price: "))
higher = int(input("Define higher: "))
if price >= higher:
print("Train")
else:
print("Coach")
else:
price = int(input("Enter price: "))
higher = int(input("Define higher: "))
if price >= higher:
print("Daytime Flight")
else:
print("Red Eye Flight")
print("Arrive City B")Travel from City A to City B
Enter time: 5
Define longer: 3
Enter price: 200
Define higher: 100
Train
Arrive City B| time | longer | price | higher | Result |
|---|---|---|---|---|
| 5 | 3 | 200 | 100 | Train |
| 5 | 3 | 50 | 100 | Coach |
| 1 | 3 | 200 | 100 | Daytime Flight |
| 1 | 3 | 50 | 100 | Red Eye Flight |
Notice that higher and longer are values you define, so the program is really two nested decisions. The last line, print("Arrive City B"), is outside both blocks and runs every time.
5.5Exam tips and common mistakes
- Make a small table of inputs and trace each one through the branches.
- Test boundary values (60, 70, 80, 90, 100) because that is where branch order matters.
- Using
>where the boundary should be included (>=). - Forgetting
int(...)aroundinput, which leaves a string and breaks the comparison. - Assuming the code rejects invalid marks without checking the range.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
For the input 80, what does the grade program print?
x = int(input("Enter your marks: "))
if x > 90 and x <= 100:
print("A")
elif x > 80:
print("B")
elif x >= 70:
print("C")
elif x >= 60:
print("D")
elif x <= 60 and x > 0:
print("E")
else:
print("Not Valid")ABCDIs 80 > 80 true?
x = int(input("Enter your marks: "))
if x > 90 and x <= 100:
print("A")
elif x > 80:
print("B")
elif x >= 70:
print("C")
elif x >= 60:
print("D")
elif x <= 60 and x > 0:
print("E")
else:
print("Not Valid")Enter your marks: 80
C80 > 90is false,80 > 80is false,80 >= 70is true:C.- Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
For the input 60, what is printed?
x = int(input("Enter your marks: "))
if x > 90 and x <= 100:
print("A")
elif x > 80:
print("B")
elif x >= 70:
print("C")
elif x >= 60:
print("D")
elif x <= 60 and x > 0:
print("E")
else:
print("Not Valid")CDENot ValidWhich of >= 60 and <= 60 is tested first?
x = int(input("Enter your marks: "))
if x > 90 and x <= 100:
print("A")
elif x > 80:
print("B")
elif x >= 70:
print("C")
elif x >= 60:
print("D")
elif x <= 60 and x > 0:
print("E")
else:
print("Not Valid")Enter your marks: 60
D>= 60comes before<= 60 and > 0, soDis printed.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
For the input 105, what does the original grade program print?
x = int(input("Enter your marks: "))
if x > 90 and x <= 100:
print("A")
elif x > 80:
print("B")
elif x >= 70:
print("C")
elif x >= 60:
print("D")
elif x <= 60 and x > 0:
print("E")
else:
print("Not Valid")ABNot ValidFollow the chain: the first test needs x <= 100.
x = int(input("Enter your marks: "))
if x > 90 and x <= 100:
print("A")
elif x > 80:
print("B")
elif x >= 70:
print("C")
elif x >= 60:
print("D")
elif x <= 60 and x > 0:
print("E")
else:
print("Not Valid")Enter your marks: 105
B- The first test fails (105 is above 100) but
105 > 80is true, soBis printed. - Answer: option 2.
Numerical Answer Type (NAT).
What does the program print for the input 25?
x = int(input("Enter a number: "))
if x % 5 == 0:
if x % 10 == 0:
print("0")
else:
print("5")
else:
print("Other")25 is divisible by 5 but not by 10.
x = int(input("Enter a number: "))
if x % 5 == 0:
if x % 10 == 0:
print("0")
else:
print("5")
else:
print("Other")Enter a number: 25
525 % 5 == 0is true;25 % 10 == 0is false, so the innerelseprints5.- Answer: 5
Multiple Choice Question (MCQ): choose the one correct option.
For the inputs 1, 3, 50, 100 (in that order), what is the result line before "Arrive City B"?
print("Travel from City A to City B")
time = int(input("Enter time: "))
longer = int(input("Define longer: "))
if time >= longer:
price = int(input("Enter price: "))
higher = int(input("Define higher: "))
if price >= higher:
print("Train")
else:
print("Coach")
else:
price = int(input("Enter price: "))
higher = int(input("Define higher: "))
if price >= higher:
print("Daytime Flight")
else:
print("Red Eye Flight")
print("Arrive City B")TrainCoachDaytime FlightRed Eye Flight1 >= 3 is false, so use the else branch.
print("Travel from City A to City B")
time = int(input("Enter time: "))
longer = int(input("Define longer: "))
if time >= longer:
price = int(input("Enter price: "))
higher = int(input("Define higher: "))
if price >= higher:
print("Train")
else:
print("Coach")
else:
price = int(input("Enter price: "))
higher = int(input("Define higher: "))
if price >= higher:
print("Daytime Flight")
else:
print("Red Eye Flight")
print("Arrive City B")Travel from City A to City B
Enter time: 1
Define longer: 3
Enter price: 50
Define higher: 100
Red Eye Flight
Arrive City Btime >= longeris false, so the program goes to theelseblock;50 >= 100is false, soRed Eye Flightis printed.- Answer: option 4.
Numerical Answer Type (NAT).
What does the even/odd program print for the input 10?
x = int(input("Enter a number: "))
if x % 2 == 0:
print("Even")
else:
print("Odd")Check the remainder on division by 2.
x = int(input("Enter a number: "))
if x % 2 == 0:
print("Even")
else:
print("Odd")Enter a number: 10
Even10 % 2is 0, soEven.- Answer: Even
Even else Odd
0, 5 or Other
60 → D, 105 → B (bug)
time then price
Importing Modules: math, random, calendar
Reusing code with import, and the four ways of importing.
A module is reusable code that you can bring into your program with import. It saves you from rewriting common tools.
6.1Importing modules
import math
print(math.pow(10, 3))1000.0Use from to import a particular part of a module; then you use the name directly, without the math. prefix.
from math import sqrt
print(sqrt(9))3.06.2The math module
| Name | What it gives | Sample |
|---|---|---|
math.sqrt(x) | square root of x | 3.0 |
math.pow(x, y) | x raised to the power y (float) | 8.0 |
math.ceil(x) | rounds up to an integer | 3 |
math.floor(x) | rounds down to an integer | 2 |
math.pi | the constant π | 3.141592653589793 |
math.e | the constant e | 2.718281828459045 |
math.cos(x) sin(x) tan(x) | trigonometric functions (x in radians) | 1.0 0.0 0.0 |
import math
print(math.sqrt(9))
print(math.pow(2, 3))
x = math.ceil(2.6)
y = math.floor(2.6)
print(x)
print(y)3.0
8.0
3
2import math
print(math.pi)
print(math.e)
print(math.cos(0))
print(math.sin(0))
print(math.tan(0))3.141592653589793
2.718281828459045
1.0
0.0
0.0sqrt and pow return floats (3.0, 8.0), while ceil and floor return integers.Extra: for a negative number, floor goes to the smaller integer, which is not the same as cutting off the decimal part.
import math
print(math.floor(-2.6))
print(math.ceil(-2.6))
print(int(-2.6))-3
-2
-26.3The random module
random.random()gives a random float from0.0up to (but not including)1.0.random.randint(x, y)gives a random integer in the rangextoy; both ends can occur.
import random
x = random.random()
print(x)
y = random.randint(1, 10)
print(y)The printed values change every run, so the exact output cannot be predicted. What you can predict are the ranges:
import random
x = random.random()
y = random.randint(1, 10)
print(0 <= x < 1)
print(1 <= y <= 10)
print(type(x), type(y))True
True
<class 'float'> <class 'int'>6.4The calendar module
import calendar
print(calendar.month(2020, 10)) October 2020
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31calendar.month(year, month) returns the text of one month; the week starts on Monday. calendar.calendar(year) returns the whole year. Here are the first lines of calendar.calendar(2018):
import calendar
lines = calendar.calendar(2018).splitlines()
print("\n".join(lines[:6])) 2018
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7 1 2 3 4 1 2 3 4
8 9 10 11 12 13 14 5 6 7 8 9 10 11 5 6 7 8 9 10 116.5Different ways of importing modules
# 1. Whole module
import math
print(math.sqrt(4))
# 2. Specific item
from math import sqrt
print(sqrt(4))
# 3. Alias
import math as m
print(m.sqrt(4))
# 4. Everything
from math import *
print(sqrt(4))2.0
2.0
2.0
2.0| Form | Use | Note |
|---|---|---|
import math | math.sqrt(4) | safest; the module name shows where a function comes from |
from math import sqrt | sqrt(4) | only the named item is brought in |
import math as m | m.sqrt(4) | short alias for a long name |
from math import * | sqrt(4) | brings in everything; can overwrite your own names |
import math
print(sqrt(4))NameError: name 'sqrt' is not definedfrom math import sqrt
print(math.sqrt(4))NameError: name 'math' is not definedA name only exists in the form you imported it. After import math you must write math.sqrt; after from math import sqrt the name math itself is not defined. Both mistakes give a NameError.
6.6Going deeper
- Imports usually go at the top (extra). It makes clear what a program depends on.
powversus**(extra).math.pow(2, 3)returns a float8.0, while2 ** 3returns the integer8.- Why avoid
import *(extra). If two modules define the same name, the later one silently wins.
import math
print(math.pow(2, 3))
print(2 ** 3)8.0
86.7Exam tips and common mistakes
- Match the way you call a function to the way you imported it.
- For random functions, reason about the range, never about the exact value.
- Calling
sqrt(4)after onlyimport math. - Calling
math.sqrtafterfrom math import sqrt. - Thinking
random.randint(1, 10)never returns 10. - Passing degrees to
sinandcos; they expect radians.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does the program print?
import math
print(math.pow(2, 3))math.pow returns a float.
import math
print(math.pow(2, 3))8.02raised to3is 8, andpowreturns the float8.0.- Answer: 8.0
Numerical Answer Type (NAT).
What does the program print?
import math
print(math.ceil(2.6) + math.floor(2.6))Round 2.6 up and down, then add.
import math
print(math.ceil(2.6) + math.floor(2.6))5ceil(2.6)is 3 andfloor(2.6)is 2: 3 + 2 = 5.- Answer: 5
Multiple Choice Question (MCQ): choose the one correct option.
What happens when this runs?
import math
print(sqrt(4))2.04Which name did the import create?
import math
print(sqrt(4))NameError: name 'sqrt' is not definedimport mathcreates the namemath, notsqrt, sosqrt(4)is aNameError.- Answer: option 3.
Multiple Select Question (MSQ): select all that apply.
For which setups does print(sqrt(4)) print 2.0?
import mathfrom math import sqrtimport math as mfrom math import *Which setups bring the bare name sqrt in?
from math import sqrtandfrom math import *bring insqrtitself.import mathneedsmath.sqrt, and the alias form needsm.sqrt.- Answer: options 2 and 4.
Multiple Choice Question (MCQ): choose the one correct option.
Which statement about the program is always true?
import random
x = random.random()
y = random.randint(1, 10)
print(0 <= x < 1)
print(1 <= y <= 10)0.5TrueFalse when the integer is 10Think about the ranges, not the values.
import random
x = random.random()
y = random.randint(1, 10)
print(0 <= x < 1)
print(1 <= y <= 10)True
Truerandom.random()is at least 0 and below 1;randint(1, 10)is between 1 and 10 including both ends.- Answer: option 2.
Numerical Answer Type (NAT).
How many lines does calendar.month(2020, 10) print?
import calendar
print(len(calendar.month(2020, 10).splitlines()))Title line, weekday line, then the weeks.
import calendar
print(len(calendar.month(2020, 10).splitlines()))7- One title line, one weekday-header line and five week lines make 7.
- Answer: 7
math.sqrt(...)
pi e cos sin tan
randint(x, y): x to y
calendar(y)
avoid import *
Week 2 Summary Sheet
One page to revise all of Week 2: topics, tools, the exam checklist and the mistakes to avoid.
The big picture
- Meaningful names;
#comments. - Dynamic typing; naming rules;
del; short-hand operators.
in/not in; chained comparisons.- Escapes
\n \t; single, double, triple quotes.
- Case, checks, trim, search, replace.
- Caesar cipher:
alpha[(index + k) % 26].
if,else,elif, nested, ternary.and/orcombine tests.
- Even/odd, last digit, grades, travel.
- Order of
elifdecides edge cases.
import,math,random,calendar.- Four import styles.
Revision sheet
| Topic | Key point |
|---|---|
| Meaningful variables | names should communicate purpose |
| Comments | # ; not executed |
| Dynamic typing | a variable can refer to different types |
| Variable rules | letter/underscore start; case-sensitive; no keywords |
| Multiple assignment | x, y = 1, 2 |
| Same-value assignment | x = y = z = 8 |
| Delete | del x |
| Short-hand | x += 3 etc. |
| Membership | in, not in |
| Chained comparisons | a < b < c |
| Escape characters | \n, \t, escaped quotes |
| Quotes | single, double, triple |
| String methods | case, checks, trimming, searching, replacing |
| Caesar Cipher | shift letters; % 26 wraps |
| if / else / elif | run a block / alternative / more conditions |
| Nested if | if inside if |
| Conditional expression | a if condition else b |
| import | bring a module into the program |
| math | mathematical functions/constants |
| random | random values |
| calendar | calendar output |
Which tool when?
| You want to… | Use |
|---|---|
| test if a word is inside a text | in |
| check a value lies between two numbers | a < x < b |
| print a quote or a tab inside a string | \" \' \t |
| make a string lowercase / title-case | lower() title() |
| test if a string is all digits | isdigit() |
| shift a letter and wrap past z | % 26 |
| choose between two values on one line | a if cond else b |
| use square root, ceiling, pi | math |
Exam checklist (from the source)
- Explain dynamic typing.
- Apply variable naming rules.
- Perform multiple assignment and unpacking.
- Delete a variable using
del. - Use short-hand assignment operators.
- Use
inandnot in. - Read chained comparisons.
- Use
\n,\tand escaped quotes. - Distinguish single, double and triple-quoted strings.
- Know the Week 2 string methods.
- Explain the Caesar Cipher formula.
- Write
if,if-elseandif-elif-else. - Combine conditions with
andandor. - Write a nested
ifand the conditional expression. - Import and use modules; know the different import styles.
- Use
math.sqrt(),pow(),ceil(),floor(),random.random(),random.randint()and thecalendarmodule.
Common mistakes
2nd_place,first-nameand keywords are not allowed.
- String methods return a new string; assign it back.
- A broad
elifbefore a narrow one hides the narrow one.
- Compare with
==;=assigns.
- Call a function the way you imported it.
- The grade program prints B for 105; check the range first.