Python,
Week 1
Concepts, runnable examples and practice: the fundamentals that everything else in Python builds on.
Chapters
- 01Python BasicsPart 1 · Getting started
- 02Output and VariablesPart 2 · print and variables
- 03Input and Data TypesPart 3 · input, types, casting
- 04OperatorsPart 4 · arithmetic, comparison, logic
- 05Precedence and AssociativityPart 5 · which operator runs first
- 06StringsPart 6 · indexing and slicing
- 07Try It YourselfPractice zone · 10 questions
- 08Week 1 Summary SheetAll parts
Python Basics
Python is a programming language used almost everywhere. In this part we meet the interpreter, the rules of Python syntax (especially indentation) and comments.
1.1What is Python?
Python is a programming language, used across areas such as:
- Web development
- Machine learning
- Data science
- Scripting
- And many more
1.2The interpreter and the console
A Python interpreter is a program that directly executes Python code.
The Python console (or shell) lets you execute code line by line and see the output immediately.
print("Hello, Python!")Hello, Python!1.3Syntax and indentation
Syntax is the set of rules followed when writing a Python program. Python uses indentation to mark a block of statements.
Important indentation rules
- Indentation marks a block of statements.
- Statements in the same block must share the same indentation level.
- Tabs or leading whitespace create the indentation.
- Incorrect indentation raises an
IndentationError.
A correct block: the indented lines form the body of the if.
x = 5
if x > 4:
print("Hello")
print(x)Hello
5Indentation errors
If the line after if x > 4: is not indented, Python does not know what the body is:
x = 5
if x > 4:
print("Hello")IndentationError: expected an indented block after 'if' statement on line 2Lines in one block must also line up with each other:
x = 5
if x > 4:
print("Hello")
print(x)IndentationError: unexpected indentTabError for inconsistent use). When the block ends, the next statement returns to the previous indentation level.x = 3
if x > 4:
print("Big")
print("Done")Done1.4Comments
Comments are used to clarify or explain code. Python does not execute comments.
Single-line comment
A single-line comment starts with #.
# This is a comment
print("Hello")HelloMultiple lines of comments
Each commented line starts with its own #:
# First comment
# Second comment
print("Hello")Hello# is ignored, e.g. print(x) # 25.Predict the output. Which statements are inside the if block, and does the comment run?
x = 8
if x > 4:
print("Big") # runs only when x > 4
print("End")x > 4 is True, so the indented print("Big") runs. print("End") is not indented, so it is outside the block and always runs. The comment is ignored.
x = 8
if x > 4:
print("Big") # runs only when x > 4
print("End")Big
End1.5Going deeper: how Python runs a file, and the two kinds of errors
A Python file is read from the top, one statement at a time. Two things follow: output appears only when you ask for it, and the kind of mistake decides how much of your program runs.
In a file, only print() shows output
In the console, typing 3 + 4 echoes 7 by itself. In a saved program nothing is shown unless you print it:
3 + 4
print(3 + 4)7Syntax errors and runtime errors
A syntax error means Python cannot even understand the file, so it refuses to run any of it. Look: "start" is on the first line but is never printed.
print("start")
print("oopsSyntaxError: unterminated string literal (detected at line 2)A runtime error happens only when the faulty line is reached. The lines before it have already run; the lines after it never do.
print("start")
print(1 / 0)
print("end")start
ZeroDivisionError: division by zeroThe error names you must recognise
| Error | Typical cause | Message Python prints |
|---|---|---|
SyntaxError | broken grammar, e.g. a quote never closed | unterminated string literal (detected at line 1) |
IndentationError | a block is not indented correctly | expected an indented block after 'if' statement on line 1 |
NameError | a name that was never created (or a typo) | name 'total' is not defined |
TypeError | an operation on the wrong types | can only concatenate str (not "int") to str |
ValueError | right type, impossible value | invalid literal for int() with base 10: 'abc' |
ZeroDivisionError | dividing by zero | division by zero |
IndexError | an index past the end | string index out of range |
Reading an error. The last line gives the error name and the reason; the line number above it tells you where to look.
A # inside quotes is not a comment
print("a # b") # a real commenta # bThe first # is part of the string; only the second one starts a comment.
1.6Exam tips and common mistakes
- For "what does this print?" questions first look for a syntax error: if there is one, nothing prints.
- If the error is a runtime error, write down the output of every line before it, then the error.
- Check the indentation of every block before tracing the logic.
- Learn the seven error names above; exams ask "which error is raised?".
- Thinking lines before a syntax error still run. They do not.
- Forgetting that a statement without
print()shows nothing in a file. - Counting a
#inside quotes as a comment. - Mixing up
NameError(name not created) andTypeError(wrong types).
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does this program print?
x = 3
if x > 5:
print("A")
print("B")
print("C")Only the indented lines depend on the if; the last line does not.
x = 3
if x > 5:
print("A")
print("B")
print("C")Cx > 5isFalseforx = 3, so both indented lines are skipped.print("C")is not indented, so it always runs.- Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Each snippet follows a line print("start"). For which snippets is start not printed?
print("hi) (the closing quote is missing)print(1 / 0)print(total) when total was never createdif line whose body is not indentedSyntax and indentation errors stop everything; runtime errors stop only at their own line.
- Option 1: SyntaxError, found before anything runs, so
startis not printed. - Option 2: ZeroDivisionError at run time, so
startwas already printed. - Option 3: NameError at run time, same reason.
- Option 4: IndentationError, found before anything runs.
- Answer: options 1 and 4.
Numerical Answer Type (NAT).
How many lines does this program print?
# a
print("x") # b
print("y # z")Comments never print; a # inside quotes is just text.
# a
print("x") # b
print("y # z")x
y # z- The first line is a comment and prints nothing.
- The second prints
x; the third printsy # z. - Answer: 2
Multiple Choice Question (MCQ): choose the one correct option.
Which error does print(10 + "5") raise?
print(10 + "5")The grammar is fine; the types are not.
print(10 + "5")TypeError: unsupported operand type(s) for +: 'int' and 'str'- The line is valid Python, so it is not a SyntaxError.
- An
intcannot be added to astr: TypeError. - Answer: option 2.
Web, ML, data science, scripting
Console runs one line at a time
Indentation marks a block
Wrong indent: IndentationError
Use 4 spaces
Not executed
One # per line
Output and Variables
Programs need to show results and to remember values. This part covers print(), variables, reassignment, and the rules for naming variables.
2.1Displaying output: print()
Use the print() function to display output. You can print strings, numbers, characters, and multiple objects separated by commas.
print("I am a boy")
print(3 + 1)
print("The sum is", 3 + 1)I am a boy
4
The sum is 4print() several objects separated by commas, it puts a space between them. Quotation marks must be matched for a valid string, e.g. print("Hello").print("Hello)SyntaxError: unterminated string literal (detected at line 1)2.2Variables
A variable is something that can vary or change, used to store a value. A simple assignment has three parts: a variable name, the assignment operator =, and a value (literal).
age = 20
print(age)20Reassigning a variable
A variable can be assigned different values multiple times. The latest value is retained.
age = 12
age = 18
age = 23
print(age)23=. = is not "equals" as in maths: it means "store the value on the right in the name on the left". That is why score = score + 5 makes sense in Python: it takes the old value, adds 5, and stores the result back.score = 10
score = score + 5
print(score)152.3Rules for naming variables
- A name should start with a letter or underscore (
_). - A name cannot start with a number.
- Names are case-sensitive.
- A name should contain only underscores and alphanumeric characters.
- For long names, underscores can separate words.
my_favourite_fruit = "mango"
myFavFruit = "mango"
print(my_favourite_fruit)
print(myFavFruit)mango
mangoage = 20
Age = 30
print(age, Age)20 30| Name | Valid? | Why |
|---|---|---|
age | Valid | letters only |
_count | Valid | starts with underscore |
fav2 | Valid | digits are fine after the first character |
my_name | Valid | underscore joins words |
2fav | Invalid | starts with a number |
my-name | Invalid | - is the minus operator |
my name | Invalid | spaces are not allowed |
class | Invalid | a reserved Python keyword |
if, class, True); those words are reserved for the language.What does this program print? Write the value of x after each line.
x = 4
x = x * 2
x = x + 1
print(x)| Line | x |
|---|---|
x = 4 | 4 |
x = x * 2 | 8 |
x = x + 1 | 9 |
x = 4
x = x * 2
x = x + 1
print(x)92.4Going deeper: print options and what a variable really holds
print() and its separators (extra)
Between objects print() puts a space (sep) and ends with a new line (end). You can change both:
print("a", "b", "c", sep="-")
print("x", end="")
print("y")a-b-c
xyA comma and a + are not the same. A comma lets print() show any types; + joins only two strings.
print("Total:", 5)
print("Total: " + str(5))Total: 5
Total: 5Copy, then change
b = a stores the current value of a in b. Later changes to a do not touch b.
a = 5
b = a
a = 9
print(a, b)9 5Updating a variable
x += 5 is a short way to write x = x + 5. The same works for -=, *= and so on (extra).
x = 10
x += 5
x -= 3
x *= 2
print(x)24Trace: 10 → 15 → 12 → 24.
Names and keywords
Keywords are case-sensitive too: class is reserved but Class is an ordinary name (not recommended).
import keyword
print(keyword.iskeyword("class"), keyword.iskeyword("Class"))True False2.5Exam tips and common mistakes
- For trace questions write a small table: one row per line, one column per variable.
- Read
=as "store into", never as "equals". - Check every variable name against the four rules: first character, allowed characters, case, keywords.
- Writing
"Total:" + 5: a TypeError. Use a comma, orstr(5). - Thinking
b = alinks the two variables so that they change together. - Using
my-nameor2ndas a name (the first is a minus, the second starts with a digit). - Mixing up
ageandAge: they are different variables.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does this program print?
x = 7
y = x
x = x + 3
print(x + y)y keeps the old value of x.
x = 7
y = x
x = x + 3
print(x + y)17x = 7, theny = 7(a copy).xbecomes 10, butystays 7.x + y = 10 + 7 = 17.- Answer: 17
Multiple Select Question (MSQ): select all that apply.
Choose the valid variable names.
_total2nd_placefirst-nameTotal2First character: letter or underscore. Later characters: letters, digits, underscore.
- Option 1 is valid (starts with an underscore).
- Option 2 starts with a digit: invalid.
- Option 3 contains
-, the minus operator: invalid. - Option 4 is valid (digits are fine after the first character).
- Answer: options 1 and 4.
Multiple Choice Question (MCQ): choose the one correct option.
What does print("a", "b", sep="") show?
print("a", "b", sep="")sep is what goes between the objects.
print("a", "b", sep="")ab- With
sep=""there is nothing betweenaandb. - Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does this program print?
count = 4
count += 2
count = count * 2
print(count)Go line by line: 4 → 6 → 12.
count = 4
count += 2
count = count * 2
print(count)12count += 2makes it 6.count = count * 2makes it 12.- Answer: option 3.
Many objects, separated by commas
Matched quotes
name = value
= is the assignment operator
Latest value is retained
Case-sensitive
Letters, digits, _ only
Input and Data Types
Programs take input and work with different kinds of values. This part covers input(), the data types str, int, float, bool and list, type(), and converting between types.
3.1User input: input()
Use input() to ask the user for information, with an optional prompt describing what to enter.
name = input("What is your name? ")
print("Name:", name)What is your name? Ayush
Name: AyushData type of input()
By default, user input is taken as a string. For a numeric value, convert the input with int() or float().
age = int(input("What is your age? "))
pi = float(input("Value of pi: "))
print(age)
print(pi)What is your age? 19
Value of pi: 3.14
19
3.14int() the input stays text, and adding a number to text is an error:age = "19"
print(age + 1)TypeError: can only concatenate str (not "int") to str3.2Data types
| Data type | Meaning | Example |
|---|---|---|
str | String / text | "Hello" |
int | Integer | 21 |
float | Floating-point number | 2.33 |
bool | Boolean | True / False |
list | Ordered collection | [2, 4, 6] |
String
A string contains text (one or more characters), written inside quotation marks.
name = "Ayush"
sports = "Basketball and Athletics"
print(name)
print(sports)Ayush
Basketball and AthleticsNumbers
Integer (int): no decimal part. Floating-point (float): has a decimal part.
x = 21
print(x)
y = 2.33
print(y)21
2.33Boolean
A Boolean value is either True or False. Boolean literals start with a capital letter.
isSecond = False
print(isSecond)
isFirst = True
print(isFirst)False
TrueisFirst = trueNameError: name 'true' is not definedLists
A list is an ordered collection of data (strings, numbers, and more), written with square brackets [], elements separated by commas.
myList = [2, 4, 6, 8, "yes", "no"]
print(myList)[2, 4, 6, 8, 'yes', 'no']3.3Getting the type: type()
Use type() to get the specific data type of a value or variable.
a = 3
b = "Hi"
c = True
d = [1, 3, 5]
print(type(a))
print(type(b))
print(type(c))
print(type(d))<class 'int'>
<class 'str'>
<class 'bool'>
<class 'list'>3.4Type conversion (type casting)
Type conversion changes a value from one data type to another:
str()→ convert to stringint()→ convert to integerfloat()→ convert to floatbool()→ convert to Boolean
Convert to string: str()
x = 21
x = str(x)
text = "My fav no. is " + x
print(text)My fav no. is 21Convert to integer: int()
x = 4.55
x = int(x)
print(x)4int() drops the decimal part (it truncates toward zero); it does not round. So int(4.55) is 4 and int(-4.55) is -4.Convert to float: float()
x = 4
x = float(x)
print(x)4.0Convert to Boolean: bool()
x = 10
y = "Hello"
z = ""
print(bool(x))
print(bool(y))
print(bool(z))True
True
False| Value | bool(value) |
|---|---|
0, 0.0, "" (empty string), [] (empty list) | False |
| any other number, any non-empty string or list | True |
bool("False") is True, because "False" is a non-empty string. Also, text that is not a number cannot be converted: int("abc") is an error.int("abc")ValueError: invalid literal for int() with base 10: 'abc'Give type() of each: 7, 7.0, "7", 7 > 3, [7], 3 + 2.0, str(7).
print(type(7))
print(type(7.0))
print(type("7"))
print(type(7 > 3))
print(type([7]))
print(type(3 + 2.0))
print(type(str(7)))<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'float'>
<class 'str'>Mixing an int and a float in arithmetic gives a float; a comparison gives a bool.
What do these print? int(7.9), float(3), str(5) + "1", bool(0), bool("0"), int("12") + 1.
print(int(7.9))
print(float(3))
print(str(5) + "1")
print(bool(0))
print(bool("0"))
print(int("12") + 1)7
3.0
51
False
True
13Note bool("0") is True: the string "0" is not empty.
Read the user's age and print their age next year.
age = int(input("Enter your age: "))
print("Next year:", age + 1)Enter your age: 20
Next year: 21Without int() the second line would raise a TypeError.
3.5Going deeper: strings versus numbers, and the conversion rules
Conversions are exam favourites. Learn the three groups in the chart, then check them in a program:
print(int(float("3.5")))
print(float("3"))
print(int(True))
print(str(3.0))3
3.0
1
3.0int("3.5")is an error: a string must look like a whole number. Go throughfloatfirst:int(float("3.5"))is3.int(True)is1andint(False)is0.
print(int("3.5"))ValueError: invalid literal for int() with base 10: '3.5'"3" and 3 are different
The same symbols behave differently as text and as numbers. + joins text, * repeats text; on numbers they add and multiply.
a = "3"
b = "4"
print(a + b)
print(int(a) + int(b))
print(a * 4)
print(int(a) * 4)34
7
3333
12The classic input() bug
Both inputs arrive as text, so a + b glues them together. Convert first.
a = input("First: ")
b = input("Second: ")
print(a + b)
print(int(a) + int(b))First: 3
Second: 4
34
7What type does an expression give?
print(type(10 / 2))
print(type(10 // 2))
print(type(2 ** 3))
print(type(3 + 2.0))<class 'float'>
<class 'int'>
<class 'int'>
<class 'float'>/ always gives a float; // and ** on ints give an int; mixing int and float gives a float.
3.6Exam tips and common mistakes
- First decide the type of every value in the expression, then apply the operator.
- Remember:
input()always returnsstr. - For
bool()questions, only 0, 0.0, an empty string and an empty list are False. A string like" "or"0"is True.
- Writing
int("3.5")and expecting 3. - Believing
bool("False")is False. - Adding the results of two
input()calls withoutint(). - Expecting
10 / 2to be the integer 5 (it is the float 5.0).
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does print(type(10 / 5)) show?
print(type(10 / 5))<class 'int'><class 'float'><class 'str'><class 'bool'>/ always gives a float.
print(type(10 / 5))<class 'float'>10 / 5is2.0, a float, even though it divides exactly.- Answer: option 2.
Numerical Answer Type (NAT).
What does this program print?
x = "5"
y = 3
print(int(x) * y)Convert the text before multiplying.
x = "5"
y = 3
print(int(x) * y)15int(x)is 5.5 * 3 = 15.- Answer: 15
Multiple Select Question (MSQ): select all that apply.
Which of these raise an error?
int("7.5")int(7.5)float("abc")bool("False")A string must look like a number of that type.
- Option 1: ValueError (a string "7.5" is not a whole number).
- Option 2 works and gives 7.
- Option 3: ValueError.
- Option 4 works and gives
True(non-empty string). - Answer: options 1 and 3.
Multiple Choice Question (MCQ): choose the one correct option.
What does print("3" + "4", 3 + 4) show?
print("3" + "4", 3 + 4)Strings are joined, numbers are added.
print("3" + "4", 3 + 4)34 7"3" + "4"joins the text:34.3 + 4adds the numbers:7.- Answer: option 2.
Numerical Answer Type (NAT).
How many of these values are True when passed to bool(): 0, "0", "", [], 0.0, " "?
print(bool(0), bool("0"), bool(""), bool([]), bool(0.0), bool(" "))Only zero, empty string and empty list are False.
print(bool(0), bool("0"), bool(""), bool([]), bool(0.0), bool(" "))False True False False False True"0"is a non-empty string: True." "contains a space: True.- The other four are False.
- Answer: 2
Always a string by default
int() / float() for numbers
True / False start with a capital
type(3) is int
int(4.55) is 4 (drops decimals)
Other values are True
"False" is True
Operators
Operators let us calculate, compare and combine conditions. This part covers arithmetic, operator order and grouping, comparison and logical operators.
4.1Arithmetic operators
An operator is a symbol that performs an operation on operands: variables, strings, numbers, Booleans and more. Week 1 covers arithmetic, comparison and logical operators.
| Operator | Operation | Example (x = 10, y = 5) | Result |
|---|---|---|---|
+ | Addition | x + y | 15 |
- | Subtraction | x - y | 5 |
* | Multiplication | x * y | 50 |
/ | Division | x / y | 2.0 |
** | Exponentiation | x ** 2 | 100 |
% | Remainder / modulus | x % y | 0 |
// | Floor division | x // 3 | 3 |
x = 10
y = 5
print("Addition:", x + y)
print("Subtraction:", x - y)
print("Multiplication:", x * y)
print("Division:", x / y)
print("Exponentiation:", x ** 2)
print("Remainder:", x % y)
print("Floor division:", x // 3)Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Exponentiation: 100
Remainder: 0
Floor division: 3Addition and string concatenation
+ also concatenates strings (joins them end to end).
x = "Hello"
y = "World"
print(x + y)HelloWorldDivision
The / operator returns the quotient as a floating-point result, even when it divides exactly.
x = 10
y = 5
print(x / y)2.0Exponentiation
** raises the left operand to the power of the right operand.
x = 2
print(x ** 3)8Remainder / modulus
% returns the remainder after division, e.g. 5 divided by 2 leaves a remainder of 1.
x = 5
print(x % 2)1Floor division
// gives the quotient rounded down to the nearest integer.
x = 5
print(x // 2)2a == (a // b) * b + a % b. For example 17 == 3 * 5 + 2, so 17 // 5 is 3 and 17 % 5 is 2. Rounded down matters for negatives: -5 // 2 is -3 (not -2) and -5 % 2 is 1.print(17 // 5, 17 % 5)
print(-5 // 2, -5 % 2)3 2
-3 14.2Operator sequence (precedence)
Operator sequence describes the order in which operations run in an expression. Use parentheses () to force a grouped expression to evaluate first.
x = 10 + 3 * 5
print(x) # 2525Grouping with parentheses
The expression inside parentheses evaluates first.
x = (10 + 3) * 5
print(x) # 6565The source notes summarise the order as "DMAS" (Division, Multiplication, Addition, Subtraction). That is a memory aid, not the full rule. In Python *, /, // and % share one level (they run left to right), and + and - share the next. ** runs before all of them, and parentheses beat everything.
print(10 * 3 // 4) # (10 * 3) // 4, left to right
print(8 / 2 * 4) # (8 / 2) * 4
print(2 ** 3 ** 2) # 2 ** (3 ** 2)
print(-2 ** 2, (-2) ** 2)7
16.0
512
-4 4If the rule were "division always before multiplication", the first line would be 0. It is 7, because Python goes left to right on the same level.
4.3Comparison operators
Comparison operators compare two operands and return a Boolean value (True or False).
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
print(5 == 5)
print(10 != 5)
print(8 > 4)
print(8 < 4)
print(8 >= 8)
print(8 <= 8)True
True
True
False
True
True= and ==. = assigns a value; == asks whether two values are equal.Comparing strings
print("python" == "python")
print("python" == "Python")True
False4.4Logical operators
Logical operators are commonly used with Boolean expressions. Python has three:
| Operator | Meaning |
|---|---|
and | Logical AND |
or | Logical OR |
not | Logical NOT |
and
Returns True when both operands are true.
print(True and True)
print(True and False)
print(False and False)True
False
FalseExample with expressions:
x = (5 == 5) and (4 == 4)
print(x)
expr = (2 > 3) and (8 > 2)
print(expr)True
Falseor
Returns True when at least one operand is true.
print(True or True)
print(True or False)
print(False or False)True
True
Falsenot
Reverses a Boolean value.
print(not False)
print(not True)
expr = not (10 > 20)
print(expr)True
False
True| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
| A | not A |
|---|---|
| True | False |
| False | True |
not runs first, then and, then or. So True or False and False is True.Evaluate each expression by hand, then check: 2 + 3 * 4, (2 + 3) * 4, 2 ** 3 * 2, 10 - 4 - 3, 20 / 4 / 5, 7 // 2 * 2, 17 % 5 + 1, -3 ** 2.
| Expression | Steps | Value |
|---|---|---|
2 + 3 * 4 | 2 + 12 | 14 |
(2 + 3) * 4 | 5 * 4 | 20 |
2 ** 3 * 2 | 8 * 2 | 16 |
10 - 4 - 3 | left to right: 6 - 3 | 3 |
20 / 4 / 5 | 5.0 / 5 | 1.0 |
7 // 2 * 2 | 3 * 2 | 6 |
17 % 5 + 1 | 2 + 1 | 3 |
-3 ** 2 | ** first: -(3 ** 2) | -9 |
Evaluate: (5 > 2) and (10 < 20), not (3 == 3), (1 > 2) or (2 > 1), 5 > 2 and not 3 > 4.
print((5 > 2) and (10 < 20))
print(not (3 == 3))
print((1 > 2) or (2 > 1))
print(5 > 2 and not 3 > 4)True
False
True
TrueLast one: 5 > 2 is True; 3 > 4 is False, so not makes it True; True and True is True.
47 sweets are packed in boxes of 6. How many full boxes, and how many sweets are left over? Use operators.
sweets = 47
box = 6
print("Full boxes:", sweets // box)
print("Left over:", sweets % box)Full boxes: 7
Left over: 5Check: 6 * 7 + 5 = 47.
4.5Going deeper: negative numbers, a test for leap years, and short-circuiting
// always rounds down (towards minus infinity), while int() cuts the decimals (towards zero). With negative numbers they differ, and % follows //:
print(-7 // 2, -7 % 2)
print(7 // -2, 7 % -2)
print(int(-3.5))-4 1
-4 -1
-3The identity a == (a // b) * b + a % b still holds:
a, b = -7, 2
print(a == (a // b) * b + a % b)TruePutting operators to work: leap years
A year is a leap year if it is divisible by 4 and not by 100, or if it is divisible by 400. One expression using %, ==, and, or:
for y in (2024, 1900, 2000):
print((y % 4 == 0 and y % 100 != 0) or y % 400 == 0)True
False
True(2024: yes. 1900: divisible by 100 but not by 400, so no. 2000: divisible by 400, so yes.) n % 2 == 0 is the standard test for an even number.
Short-circuiting: and / or stop early
A and B stops at the first False; A or B stops at the first True. The order can decide whether an error happens:
x = 0
print(x != 0 and 10 / x > 1)Falsex = 0
print(10 / x > 1 and x != 0)ZeroDivisionError: division by zeroComparing floats (extra)
Decimals are stored approximately, so avoid == on floats that come from arithmetic:
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)0.30000000000000004
False4.6Useful built-in functions: abs, round, pow, divmod, min, max, and float precision
Python ships with a few number functions that need no import. They appear in exam questions together with the operators above.
| Function | What it does | Example |
|---|---|---|
abs(x) | the size of without its sign | abs(-7) is 7 |
pow(a, b) | same as a ** b; pow(a, b, m) gives (a ** b) % m efficiently | pow(2, 10) is 1024 |
divmod(a, b) | the pair (a // b, a % b) | divmod(17, 5) is (3, 2) |
min(...), max(...) | smallest or largest of several values (or of one list or string) | max(4, 9, 2) is 9 |
round(x), round(x, n) | round to a whole number, or to n decimal places | round(3.14159, 2) is 3.14 |
print(abs(-7))
print(abs(3.5))
print(pow(2, 10))
print(divmod(17, 5))
print(divmod(-17, 5)) # floor division rounds down: -17 // 5 is -4
print(max(4, 9, 2))7
3.5
1024
(3, 2)
(-4, 3)
9round() does not always round half up
For a value exactly halfway between two integers, round() picks the even one ("banker's rounding"). It also works on negative numbers and with a negative number of digits:
print(round(2.5)) # tie: goes to the even neighbour, 2
print(round(3.5)) # tie: goes to the even neighbour, 4
print(round(-2.5))
print(round(7))
print(round(1234, -2)) # round to the nearest hundred
print(round(3.14159, 2))2
4
-2
7
1200
3.14int() drops the decimal part (rounds toward zero), round() goes to the nearest, math.floor() goes down and math.ceil() goes up. For they give , , and (and for , ceil gives ).import math
print(int(-3.7))
print(round(-3.7))
print(math.floor(-3.7))
print(math.ceil(-3.2))-3
-4
-4
-3Float precision
Python stores a decimal fraction like 0.1 in binary, and most such fractions cannot be stored exactly. Tiny errors appear, which is why 0.1 + 0.2 == 0.3 is False.
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(abs((0.1 + 0.2) - 0.3) < 1e-9) # compare with a tolerance
print(round(0.1 + 0.2, 2) == 0.3) # or round first0.30000000000000004
False
True
True- Never test two decimals with
==. Compare their difference to a small tolerance, or round both first. - Whole numbers are different:
inthas no limit on size (2 ** 100prints all 31 digits), and integer arithmetic is exact. - Division always gives a float:
10 / 5is2.0, while10 // 5is the int2. Floor division of floats stays a float:7.0 // 2is3.0.
print(10 / 5)
print(10 // 5)
print(7.0 // 2)
print(2 ** -1) # a negative power gives a float2.0
2
3.0
0.54.7Exam tips and common mistakes
- For negative numbers compute
//by rounding down, then get%froma - (a // b) * b. - Break a long condition into pieces and evaluate each comparison first; then apply
not,and,or. - Use
1 < x < 10for a range check; it works as two comparisons joined byand.
- Rounding
-7 // 2to-3(toward zero). It is-4. - Writing
x = 5where you meanx == 5. - Expecting
0.1 + 0.2 == 0.3to be True. - Forgetting that
andranks aboveor.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does print(-17 // 5) show?
print(-17 // 5)Floor division rounds down.
print(-17 // 5)-4-17 / 5 = -3.4.- Rounding down gives
-4. - Answer: -4
Numerical Answer Type (NAT).
What does print(-17 % 5) show?
print(-17 % 5)Use a == (a // b) * b + a % b.
print(-17 % 5)3-17 // 5 = -4.-17 = 5 * (-4) + r, sor = 3.- Answer: 3
Multiple Select Question (MSQ): select all that apply.
Which expressions have the value True?
print(17 % 5 == 2, -5 // 2 == -2, 1 < 5 < 10, "a" < "B")17 % 5 == 2-5 // 2 == -21 < 5 < 10"a" < "B"Evaluate each one separately.
print(17 % 5 == 2, -5 // 2 == -2, 1 < 5 < 10, "a" < "B")True False True False- Option 1: 17 = 5·3 + 2, so True.
- Option 2:
-5 // 2is-3, so False. - Option 3: both comparisons hold, True.
- Option 4:
"a"(code 97) is larger than"B"(code 66), so False. - Answer: options 1 and 3.
Multiple Choice Question (MCQ): choose the one correct option.
What does print(10 / 5, 10 // 5) show?
print(10 / 5, 10 // 5)/ always gives a float; // on ints gives an int.
print(10 / 5, 10 // 5)2.0 210 / 5is2.0.10 // 5is2.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does this program print?
x = 0
print(x == 0 or 10 / x > 1)or stops as soon as it sees True.
x = 0
print(x == 0 or 10 / x > 1)Truex == 0is True, soornever evaluates10 / x > 1: no error.- Answer: option 1.
Numerical Answer Type (NAT).
What does the following program print?
print(round(2.5) + round(3.5))For exact halves, round() goes to the even neighbour.
print(round(2.5) + round(3.5))6round(2.5)is2(even),round(3.5)is4(even). Sum6.- A student who expects "round half up" would say
3 + 4 = 7. That is the common wrong answer. - Answer: 6
Multiple Select Question (MSQ): select all that apply.
Which of these expressions evaluate to True?
round(2.5) == 20.1 + 0.2 == 0.3divmod(17, 5) == (3, 2)abs(-3.0) == 310 / 5 == 2int(-3.7) == -4Evaluate each one separately.
print(round(2.5) == 2)
print(0.1 + 0.2 == 0.3)
print(divmod(17, 5) == (3, 2))
print(abs(-3.0) == 3)
print(10 / 5 == 2)
print(int(-3.7) == -4)True
False
True
True
True
False- 1 True: a tie goes to the even number. 2 False: float error. 3 True. 4 True:
3.0 == 3is True. - 5 True:
2.0 == 2compares values, not types. 6 False:int()truncates toward zero, giving-3. - Answer: options 1, 3, 4 and 5.
Numerical Answer Type (NAT).
What does the program print?
q, r = divmod(-17, 5)
print(q, r)divmod(a, b) is (a // b, a % b), and // rounds down.
q, r = divmod(-17, 5)
print(q, r)-4 3-17 // 5 = -4(since rounds down), and , so-17 % 5 = 3.- Answer: -4 3 (the remainder is 3)
Numerical Answer Type (NAT).
What does print(round(1234, -2)) show?
A negative second argument rounds to tens (), hundreds (), and so on.
print(round(1234, -2))1200- is closer to than to .
- Answer: 1200
Multiple Choice Question (MCQ): choose the one correct option.
Which line correctly tests whether a = 0.1 + 0.2 is (practically) equal to 0.3?
a == 0.3abs(a - 0.3) < 1e-9a is 0.3a - 0.3 == 0Compare the size of the difference with a small tolerance.
a = 0.1 + 0.2
print(a == 0.3)
print(abs(a - 0.3) < 1e-9)
print(a - 0.3 == 0)False
True
False- Options 1 and 4 are the same exact comparison in disguise, and fail. Option 3 tests identity, not value.
- Answer: option 2.
/ always gives a float
+ joins strings
5 // 2 = 2
a = (a // b) * b + a % b
Same level: left to right
10 + 3 * 5 = 25, (10 + 3) * 5 = 65
Result is True or False
= assigns, == compares
or: at least one true
not: reverses
"python" == "Python" is False
Precedence and Associativity
Which operator runs first, and what happens when two operators are tied? This part explains it in short points, with traced examples and practice questions.
5.1Why precedence matters
An expression can contain many operators at once, and Python has to decide which one to apply first. Precedence is the rule that decides that order. Get the order wrong and you get a completely different answer, even though the code "looks" fine.
print(10 + 3 * 5) # 25, not 65
print((10 + 3) * 5) # 6525
65* has higher precedence than +, so multiplication runs first. Parentheses override everything.
5.2The precedence table
Listed in descending order: the upper group has higher precedence than the ones below it.
| Rank | Operators | Meaning |
|---|---|---|
| 1 | ( ) | Parentheses |
| 2 | ** | Exponent |
| 3 | * / // % | Multiplication, Division, Floor Division, Modulus |
| 4 | + - | Addition, Subtraction |
| 5 | == != > < >= <= | Comparisons |
| 6 | not | Logical NOT |
| 7 | and | Logical AND |
| 8 | or | Logical OR |
Brackets → Exponent → Multiply/Divide group → Add/Subtract → Comparisons → NOT → AND → OR. Arithmetic always finishes before comparisons, and comparisons always finish before logic.
-x ranks just below **, so -2 ** 2 is -(2 ** 2) = -4, while (-2) ** 2 is 4. And the comparison row has six operators: == != > < >= <=.print(-2 ** 2)
print((-2) ** 2)-4
45.3Reading the table correctly
- Higher in the table = evaluated first.
- Operators on the same row share the same precedence: they are tied.
- When operators are tied, precedence alone cannot decide the order: that is where associativity steps in (section 5.5).
( )sits at the top, so anything inside brackets is always computed first: the simplest way to force an order you want.
5.4Worked precedence examples
Example 1: arithmetic order
x = 10 + 3 * 5* is rank 3, + is rank 4: multiplication first.
10 + 3 * 5
10 + 15
25Example 2: parentheses override
x = (10 + 3) * 5( ) is rank 1: the addition inside runs first.
(10 + 3) * 5
13 * 5
65Example 3: exponent beats multiplication
x = 2 * 3 ** 2** is rank 2, higher than * at rank 3.
2 * 3 ** 2
2 * 9
18Example 4: arithmetic, then comparison, then logic
result = 5 + 3 > 6 and not FalseArithmetic (rank 4) → comparison (rank 5) → not (rank 6) → and (rank 7).
5 + 3 > 6 and not False
8 > 6 and not False
True and not False
True and True
TrueCheck all four by running them:
print(10 + 3 * 5)
print((10 + 3) * 5)
print(2 * 3 ** 2)
print(5 + 3 > 6 and not False)25
65
18
True5.5What associativity means
Looking at the table, more than one operator can exist in the same group: those operators have the same precedence. When two operators have the same precedence, associativity decides the order of operations.
Associativity is the order in which an expression is evaluated when it has multiple operators of the same precedence.
Almost all operators in Python have left-to-right associativity. The exceptions are ** and not, which go right to left.
| Operators | Associativity |
|---|---|
* / // % | Left → Right |
+ - | Left → Right |
| Comparisons | Left → Right |
and, or | Left → Right |
** | Right → Left |
not | Right → Left |
5 > 3 > 1 is not grouped as (5 > 3) > 1. Python reads it as 5 > 3 and 3 > 1, so each neighbouring pair is compared. Writing the brackets yourself gives a different answer:print(5 > 3 > 1)
print((5 > 3) > 1)True
False5.6Left-to-right associativity
* and // have the same precedence. If both appear in one expression, the left one is evaluated first.
Example: * and // tied
x = 100 * 10 // 3Both are rank 3, so left to right: * first, then //.
100 * 10 // 3
1000 // 3
333Reversing the order would give a different answer: 100 * (10 // 3) = 300.
Subtraction is also left to right
x = 20 - 5 - 320 - 5 - 3
15 - 3
12If it were right-to-left you would get 20 - 2 = 18, which is wrong.
print(100 * 10 // 3) # 333
print(100 * (10 // 3)) # 300
print(20 - 5 - 3) # 12333
300
125.7Right-to-left: the ** operator
For the exponential operator **, associativity is right to left. So in a chain of exponents, the rightmost pair is computed first.
Example: chained exponents
2 ** 3 ** 8 ** 4Python parenthesises this as (2 ** (3 ** (8 ** 4))). Innermost first: 8 ** 4, then 3 ** that, then 2 ** that. A left-to-right reading would have given ((2 ** 3) ** 8) ** 4, a totally different value.
8 ** 4 is 4096 and 3 ** 4096 already has 1955 digits, so 2 ** (3 ** 4096) is a number far too large for any computer to calculate. The point is only the grouping, which you can see without evaluating it.A smaller example you can verify
2 ** 3 ** 2
2 ** (3 ** 2)
2 ** 9
512Not 64: that would be (2 ** 3) ** 2.
print(2 ** 3 ** 2) # 512 (right to left)
print((2 ** 3) ** 2) # 64 (forced left)512
645.8Right-to-left: the not operator
The not operator also has right-to-left associativity. In a chain of nots, the one closest to the value is applied first, then the next one out.
not not True
not (not True)
not False
Trueprint(not not True) # True
print(not not False) # FalseTrue
False5.9Combining precedence and associativity
The full rule Python follows, in order:
- Precedence first: the higher-ranked operator runs before the lower-ranked one.
- Associativity second: only used to break a tie between equal-precedence operators.
Example: everything at once
x = 2 ** 2 ** 3 + 10 // 3 * 2- Step 1: exponent (rank 2), right to left:
2 ** 2 ** 3→2 ** 8→256. - Step 2:
//and*(rank 3), left to right:10 // 3→3, then3 * 2→6. - Step 3: addition (rank 4):
256 + 6.
2 ** 2 ** 3 + 10 // 3 * 2
256 + 10 // 3 * 2
256 + 3 * 2
256 + 6
262x = 2 ** 2 ** 3 + 10 // 3 * 2
print(x)2625.10Common mistakes
- Reading
2 ** 3 ** 2left to right and wrongly getting64instead of512. - Assuming
*beats/or//: they are tied, so it is left to right. - Forgetting that arithmetic finishes before comparison, and comparison before logic.
- Thinking
andandorare equal:andis higher thanor. - Forgetting
notbinds tighter thanand/or.
When an expression mixes three or more operator types, add parentheses. It costs nothing and removes all ambiguity for whoever reads the code next.
Practice questions with solutions
Predict the output before you open the solution.
What is the value of 6 + 4 * 2?
* (rank 3) beats + (rank 4): 4 * 2 = 8 first. Then 6 + 8.
print(6 + 4 * 2)14What is the value of (6 + 4) * 2?
Parentheses (rank 1) run first → 10, then 10 * 2.
print((6 + 4) * 2)20What is the value of 2 ** 3 ** 2?
** is right to left → 3 ** 2 = 9 first, then 2 ** 9 = 512. A left-to-right reading would wrongly give (2 ** 3) ** 2 = 64.
print(2 ** 3 ** 2)512What is the value of 50 // 7 * 2?
Both are rank 3 → left to right. 50 // 7 = 7, then 7 * 2.
print(50 // 7 * 2)14What is the value of 10 % 4 + 2 * 3?
Rank 3 first, left to right: 10 % 4 = 2, then 2 * 3 = 6. Then rank 4: 2 + 6.
print(10 % 4 + 2 * 3)8What is the value of not True and False?
not (rank 6) binds tighter than and (rank 7). not True → False, then False and False.
print(not True and False)FalseWhat is the value of True or False and False?
and (rank 7) beats or (rank 8) → False and False = False first. Then True or False.
print(True or False and False)TrueWhat is the value of 4 + 6 > 8?
Arithmetic (rank 4) before comparison (rank 5) → 10 > 8.
print(4 + 6 > 8)TrueHow does Python parenthesise 2 ** 3 ** 8 ** 4? Show the grouping (do not evaluate it).
** is right to left, so the rightmost pair binds first: (2 ** (3 ** (8 ** 4))).
What is the value of 2 ** 3 + 4 * 2 - 6 // 4?
Rank 2: 2 ** 3 = 8. Rank 3, left to right: 4 * 2 = 8, then 6 // 4 = 1. Rank 4, left to right: 8 + 8 = 16, then 16 - 1.
print(2 ** 3 + 4 * 2 - 6 // 4)155.11Going deeper: an evaluation tree and some tricky cases
The safest way to evaluate a mixed expression is to draw the tree: the highest-rank operators sit at the bottom and run first.
A routine that always works
- Put brackets around everything inside parentheses first.
- Mark the operators and note their ranks (Part 5.2).
- Evaluate rank by rank from the top. Ties go left to right, except
**andnot(right to left). - Write the new, shorter expression after every step, as the traced examples do.
Tricky cases, checked by running them
print(2 ** -1)
print(not 1 == 2)
print(7 + 8 % 3 * 2)
print(-2 ** 2, (-2) ** 2)0.5
True
11
-4 42 ** -1: a minus sign directly after**belongs to the exponent, so it is2 ** (-1)= 0.5.not 1 == 2: the comparison runs first, so it isnot (1 == 2), which is True.7 + 8 % 3 * 2:%and*tie, left to right:8 % 3 = 2, then2 * 2 = 4, then7 + 4 = 11.-2 ** 2is-(2 ** 2)=-4, unlike(-2) ** 2= 4.
5.12Exam tips and tricky cases
- Always rewrite the expression after each step; skipping steps causes most errors.
- Same rank means left to right, so
100 / 10 * 2is(100 / 10) * 2, not100 / (10 * 2). - When in doubt, add parentheses in your own answer sheet to show the order you used.
- Doing all the multiplications before all the divisions ("DMAS" is only a memory aid).
- Reading
2 ** 3 ** 2as(2 ** 3) ** 2. - Forgetting that
notcomes after the comparisons. - Giving an integer answer when
/was involved (the result is a float).
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does print(2 + 3 * 4 ** 2) show?
print(2 + 3 * 4 ** 2)** first, then *, then +.
print(2 + 3 * 4 ** 2)504 ** 2 = 16.3 * 16 = 48.2 + 48 = 50.- Answer: 50
Numerical Answer Type (NAT).
What does print(100 / 10 * 2 // 3) show?
print(100 / 10 * 2 // 3)/, * and // tie: left to right.
print(100 / 10 * 2 // 3)6.0100 / 10 = 10.0.10.0 * 2 = 20.0.20.0 // 3 = 6.0(a float because of the float operand).- Answer: 6.0
Multiple Choice Question (MCQ): choose the one correct option.
What does this program print?
print(not 5 > 3 or 2 ** 2 == 4)Comparisons first, then not, then or.
print(not 5 > 3 or 2 ** 2 == 4)True5 > 3is True, sonot 5 > 3is False.2 ** 2 == 4is True.False or Trueis True.- Answer: option 1.
Multiple Select Question (MSQ): select all that apply.
Which of these comparisons are True?
print(2 ** 3 ** 2 == 512, -3 ** 2 == 9, 10 - 4 - 3 == 3, 8 / 2 * 4 == 1)2 ** 3 ** 2 == 512-3 ** 2 == 910 - 4 - 3 == 38 / 2 * 4 == 1Check the associativity of each.
print(2 ** 3 ** 2 == 512, -3 ** 2 == 9, 10 - 4 - 3 == 3, 8 / 2 * 4 == 1)True False True False- Option 1:
**is right to left: 2 ** 9 = 512. - Option 2:
-3 ** 2is -9, not 9. - Option 3: (10 - 4) - 3 = 3.
- Option 4:
8 / 2 * 4is4.0 * 4 = 16.0. - Answer: options 1 and 3.
Numerical Answer Type (NAT).
What does print(7 + 8 % 3 * 2) show?
print(7 + 8 % 3 * 2)% and * tie, so left to right.
print(7 + 8 % 3 * 2)118 % 3 = 2.2 * 2 = 4.7 + 4 = 11.- Answer: 11
Higher in the table = first
( ) overrides everything
Associativity breaks the tie
20 - 5 - 3 = 12
100 * 10 // 3 = 333
2 ** 3 ** 2 = 512
not not True = True
not > and > or
Arithmetic → comparison → logic
Strings
A string is a sequence of characters: text. This part covers concatenation, indexing, slicing, len(), replication and comparison.
6.1String concatenation
Combining strings with the + operator.
a = "Hello"
b = "World"
text = a + b
print(text)HelloWorld+ adds nothing in between, so put a space in yourself. Also, you can only join a string to a string: turn a number into text with str() first.a = "Hello"
b = "World"
print(a + " " + b)
print("Age: " + str(21))Hello World
Age: 21print("Age: " + 21)TypeError: can only concatenate str (not "int") to str6.2String indexing
Indexing accesses a single character using square brackets []. Important: indexing starts at 0. Negative indices count from the end; -1 is the last character.
text = "Hi everyone"
print(text[0])
print(text[1])
print(text[-1])
print(text[-2])H
i
e
n0 … 4. Asking for index 5 is an error. Also, strings cannot be changed through an index.text = "Hello"
print(text[5])IndexError: string index out of rangetext = "Hello"
text[0] = "J"TypeError: 'str' object does not support item assignment6.3String slicing
Slicing accesses a range of characters: text[start:stop]. The stop index is exclusive.
text = "Python Lover"
print(text[2:5])thoSlicing from a position to the end
If the second index is omitted, the slice runs to the end of the string.
text = "Python Lover"
print(text[2:])thon Lovertext[start:stop] has stop - start characters, so text[2:5] has 3. Leaving out the first index starts at the beginning, and negative indices work too:text = "Python Lover"
print(text[:3])
print(text[-5:])Pyt
Lover6.4String length: len()
len() returns the number of characters in a string.
text = "Hello"
print(len(text))5len("Hi everyone") is 11: the space is a character too. The last valid index is always len(text) - 1.6.5String replication
The * operator can replicate a string.
text = "Gagan"
print(text * 2)
print(text * 4)GaganGagan
GaganGaganGaganGagan6.6String comparison
Strings can be compared using comparison operators. Python compares strings based on character ordering.
x = "India"
print(x == "India")
print(x == "india")True
FalseString comparisons can also use > and <:
print("apple" > "one")
print("abc" < "abcd")False
Trueprint("Zebra" < "apple")
print("10" < "9")
print(10 < 9)True
True
FalseFor text = "Programming" find: text[0], text[-1], text[3:7], text[:4], text[5:], len(text).
text = "Programming"
print(text[0])
print(text[-1])
print(text[3:7])
print(text[:4])
print(text[5:])
print(len(text))P
g
gram
Prog
amming
11| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| char | P | r | o | g | r | a | m | m | i | n | g |
What does print("Ha" * 3 + "!") print? And what does print("-" * 10) print?
print("Ha" * 3 + "!")
print("-" * 10)HaHaHa!
----------* runs before +: first "HaHaHa", then the "!" is joined.
True or False? "cat" < "dog", "cat" < "Cat", "cat" == "cat ", "10" < "9".
print("cat" < "dog")
print("cat" < "Cat")
print("cat" == "cat ")
print("10" < "9")True
False
False
True"c" < "d", so True.- A capital letter comes before a small one, so
"Cat"is smaller: False. - The trailing space makes them different: False.
"1"comes before"9"as characters: True (but10 < 9as numbers is False).
6.7Going deeper: slices never fail, strings never change
Slices are forgiving; single indexes are not
A single out-of-range index raises IndexError, but a slice simply stops at the end of the string. Negative stops cut from the right, and an optional third number is the step (extra).
text = "Hello"
print(text[2:100])
print(repr(text[10:]))
print(text[:-1])
print(text[::-1])
print(text[::2])llo
''
Hell
olleH
Hlotext[2:100]gives everything from index 2 to the end.text[10:]gives an empty string, with no error.text[:-1]drops the last character.text[::-1]reverses the string;text[::2]takes every second character.
Strings cannot be edited, only rebuilt
Assigning to an index is an error. To "change" a character, build a new string from slices. The original stays as it was.
text = "Hello"
new = "J" + text[1:]
print(new)
print(text)Jello
HelloBuilding strings: * runs before +
Is one string inside another? (extra)
print("th" in "python", "x" in "python")True False6.8Exam tips and common mistakes
- Count indices from 0; the last valid index is
len(text) - 1, andtext[a:b]hasb - acharacters. - Spaces and punctuation are characters too: include them when you count with
len(). - Before slicing, write the index above every character, like the "Programming" table.
- Using the stop index as if it were included:
text[2:5]has indices 2, 3, 4. - Trying
text[0] = "J". It is a TypeError. - Adding a number to a string without
str(). - Forgetting that
text[len(text)]is out of range.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does this program print?
s = "Programming"
print(s[2:6])Indices: P0 r1 o2 g3 r4 a5 m6. The stop index is excluded.
s = "Programming"
print(s[2:6])ogras[2:6]takes indices 2, 3, 4, 5:o g r a.- Answer: option 2.
Numerical Answer Type (NAT).
What does print(len("Hi, there!")) show?
print(len("Hi, there!"))Every character counts, including spaces and punctuation.
print(len("Hi, there!"))10- H, i, comma, space, t, h, e, r, e, exclamation mark: 10 characters.
- Answer: 10
Multiple Choice Question (MCQ): choose the one correct option.
What does print("Hello"[-3:]) show?
print("Hello"[-3:])Start 3 characters from the end and go to the end.
print("Hello"[-3:])llo-3is the third character from the end:l.- Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Which of these raise an error?
"Hello"[5]"Hello"[2:50]"Hello"[0] = "J""Hello" + 5Slices never raise IndexError; indexes can.
- Option 1: IndexError (valid indices are 0 to 4).
- Option 2 works: the slice stops at the end and gives
llo. - Option 3: TypeError (strings cannot be changed).
- Option 4: TypeError (str + int).
- Answer: options 1, 3 and 4.
Multiple Choice Question (MCQ): choose the one correct option.
What does print("ab" * 2 + "c" * 3) show?
print("ab" * 2 + "c" * 3)* runs before +.
print("ab" * 2 + "c" * 3)ababccc"ab" * 2isabab;"c" * 3isccc.- Then the two are joined.
- Answer: option 1.
Only string + string
str(21) to join a number
text[-1] is the last
Starts at 0
text[2:] runs to the end
text[:3] starts at the beginning
Spaces count
"Gagan" * 4
> < use character order
"apple" > "one" is False, "abc" < "abcd" is True
Try It Yourself
Ten short questions that cover the whole week: variables, input, casting, arithmetic, comparison, logic, indexing, slicing, len() and replication.
Work through these without looking back at the examples. Each solution is hidden behind a button, and its output comes from actually running the code.
Create a variable age, assign it a value, then print it.
# Q1
age = 20
print(age)20Take the user's name as input and print it.
# Q2
name = input("Enter your name: ")
print(name)Enter your name: Asha
AshaTake a number as input and convert it to an integer.
# Q3
number = int(input("Enter a number: "))
print(number)Enter a number: 42
42For x = 15 and y = 4, find the sum, difference, product, quotient, remainder, and floor quotient.
# Q4
x = 15
y = 4
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
print(x // y)19
11
60
3.75
3
315 / 4 is 3.75; 15 % 4 is the remainder 3; 15 // 4 is the floor quotient 3 (since 15 = 4 × 3 + 3).
Check whether 25 is greater than 20.
# Q5
print(25 > 20)TrueEvaluate (5 > 2) and (10 < 20).
# Q6
print((5 > 2) and (10 < 20))TrueFor text = "Python", print the first, last, and third character.
# Q7
text = "Python"
print(text[0])
print(text[-1])
print(text[2])P
n
tPrint "thon" from "Python" using slicing.
# Q8
text = "Python"
print(text[2:])thontext[2:] starts at index 2 ("t") and runs to the end.
Find the length of "Python".
# Q9
text = "Python"
print(len(text))6Print "Hi" five times using string replication.
# Q10
print("Hi" * 5)HiHiHiHiHiWeek 1 Summary Sheet
Everything from Week 1 on one sheet, for a last-minute revision.
Revision sheet
| Topic | Key point |
|---|---|
| Python | Programming language |
| Interpreter | Executes Python code |
| Indentation | Defines blocks |
| Comments | Start with #; not executed |
print() | Displays output |
| Variable | Stores a value |
input() | Takes user input; string by default |
type() | Returns the data type |
str() | Converts to string |
int() | Converts to integer |
float() | Converts to float |
bool() | Converts to Boolean |
+ - * / | Basic arithmetic |
** | Exponentiation |
% | Remainder |
// | Floor division |
== != > < >= <= | Comparison |
and or not | Logical operations |
| + on strings | Concatenation |
text[i] | Indexing |
text[a:b] | Slicing |
len(text) | String length |
text * n | String replication |
Operators at a glance
| Kind | Operators | Gives |
|---|---|---|
| Arithmetic | + - * / ** % // | number (/ always a float) |
| Comparison | == != > < >= <= | bool |
| Logical | and or not | bool |
| Strings | + * [ ] [a:b] | string |
Common mistakes
| Mistake | Fix |
|---|---|
if x = 5: (assignment instead of comparison) | if x == 5: |
age = input() then age + 1 | int(input()) |
"Age: " + 21 | "Age: " + str(21) |
5 / 2 when you want 2 | 5 // 2 |
text[len(text)] | last index is len(text) - 1 or text[-1] |
slice stop is included (text[2:5] has 5 characters) | stop is exclusive: 3 characters |
true / false | True / False |
10 < 9 vs "10" < "9" | numbers and strings compare differently |
Last-minute checklist
Make sure you can write and understand each of these:
print()andinput()- Variable assignment and reassignment
- Variable naming rules
str,int,float,bool,listtype()- Type casting with
str(),int(),float(),bool() - All seven arithmetic operators
- Operator precedence and parentheses
- Associativity: left to right, and
**/notright to left - All six comparison operators
and,or,not- String concatenation
- String indexing, including negative indexing
- String slicing and the exclusive stop index
len()- String replication with
* - String comparison
- Python indentation and comments
Exam tips: last-minute checklist
- Look for a syntax error first: if there is one, nothing prints
- Trace variables line by line in a small table
input()is always a string: convert withint()/float()/gives a float;//rounds down;%follows//- Rank first, then left to right (
**andnotgo right to left) - Count string indices from 0; the stop index is excluded
- Use
=where you mean== - Expect
int("3.5")to work - Think
bool("False")is False - Add a number to a string without
str() - Change a string through an index
- Compare floats from arithmetic with
==
Quick answers
| Question | Answer |
|---|---|
-7 // 2 and -7 % 2 | -4 and 1 |
2 ** 3 ** 2 | 512 |
print("a", "b", sep="") | ab |
"Hello"[-3:] | llo |
type(10 / 2) | float |
"3" + "4" | "34" |