Weeks
Intro to PythonWeek 1 · Variables, Operators and Strings
Intro to Python

Python,
Week 1

Concepts, runnable examples and practice: the fundamentals that everything else in Python builds on.

8 chapters64 worked examples~53 min read
VariablesData typesOperatorsStringsPractice

Chapters

  1. 01Python BasicsPart 1 · Getting started
  2. 02Output and VariablesPart 2 · print and variables
  3. 03Input and Data TypesPart 3 · input, types, casting
  4. 04OperatorsPart 4 · arithmetic, comparison, logic
  5. 05Precedence and AssociativityPart 5 · which operator runs first
  6. 06StringsPart 6 · indexing and slicing
  7. 07Try It YourselfPractice zone · 10 questions
  8. 08Week 1 Summary SheetAll parts
01
Part 1

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

Definition: interpreter

A Python interpreter is a program that directly executes Python code.

Definition: console (shell)

The Python console (or shell) lets you execute code line by line and see the output immediately.

Python codeyour programInterpreterruns it directlyOutputwhat you seePYTHON SHELL>>> print("Hello, Python!")Hello, Python!The shell runs one line at a time and shows the result at once
Figure 1. The interpreter runs your code and shows the output
Python
print("Hello, Python!")
Output
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.

Python
x = 5
if x > 4:
    print("Hello")
    print(x)
Output
Hello
5
1x = 52if x > 4:3print("Hello")4print(x)5print("done")body of the if blocksame indentation levelback to the previous levelIndentation is how Python knows which lines belong together
Figure 2. Indented lines form a block; the next unindented line is outside it

Indentation errors

If the line after if x > 4: is not indented, Python does not know what the body is:

Python
x = 5
if x > 4:
print("Hello")
Error
IndentationError: expected an indented block after 'if' statement on line 2

Lines in one block must also line up with each other:

Python
x = 5
if x > 4:
    print("Hello")
      print(x)
Error
IndentationError: unexpected indent
Good habit. Use 4 spaces per level and do not mix tabs and spaces in one file (Python raises a TabError for inconsistent use). When the block ends, the next statement returns to the previous indentation level.
Python
x = 3
if x > 4:
    print("Big")
print("Done")
Output
Done

1.4Comments

Comments are used to clarify or explain code. Python does not execute comments.

Single-line comment

A single-line comment starts with #.

Python
# This is a comment
print("Hello")
Output
Hello

Multiple lines of comments

Each commented line starts with its own #:

Python
# First comment
# Second comment
print("Hello")
Output
Hello
Also allowed. A comment can follow code on the same line: everything after # is ignored, e.g. print(x) # 25.
Example 1Which lines run?

Predict the output. Which statements are inside the if block, and does the comment run?

Python
x = 8
if x > 4:
    print("Big")  # runs only when x > 4
print("End")
Solution

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.

Python
x = 8
if x > 4:
    print("Big")  # runs only when x > 4
print("End")
Output
Big
End

1.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:

Python
3 + 4
print(3 + 4)
Output
7

Syntax errors and runtime errors

1. SyntaxError: the file breaks the grammarwhole file is checked ✗nothing runs at allnot even the lines before the mistake2. Runtime error: the grammar is fine, a line fails when it runsfile checked ✓print("start")prints: startprint(1 / 0)ZeroDivisionErrorprint("end")never reachedSyntax errors are caught before line 1 runs. Runtime errors stop the program at the failing line.
Syntax errors are caught before anything runs; runtime errors stop at the failing line

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.

Python
print("start")
print("oops
Error
SyntaxError: 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.

Python
print("start")
print(1 / 0)
print("end")
Error
start
ZeroDivisionError: division by zero

The error names you must recognise

ErrorTypical causeMessage Python prints
SyntaxErrorbroken grammar, e.g. a quote never closedunterminated string literal (detected at line 1)
IndentationErrora block is not indented correctlyexpected an indented block after 'if' statement on line 1
NameErrora name that was never created (or a typo)name 'total' is not defined
TypeErroran operation on the wrong typescan only concatenate str (not "int") to str
ValueErrorright type, impossible valueinvalid literal for int() with base 10: 'abc'
ZeroDivisionErrordividing by zerodivision by zero
IndexErroran index past the endstring 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

Python
print("a # b")  # a real comment
Output
a # b

The first # is part of the string; only the second one starts a comment.

1.6Exam tips and common mistakes

Exam tips
  • 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?".
Common mistakes
  • 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) and TypeError (wrong types).

Practice questions (graded-assignment style)

Q1Which lines run?

Multiple Choice Question (MCQ): choose the one correct option.

What does this program print?

Python
x = 3
if x > 5:
    print("A")
    print("B")
print("C")
1
A, B, C
2
C
3
A, C
4
B, C
Solution
Idea

Only the indented lines depend on the if; the last line does not.

Python
x = 3
if x > 5:
    print("A")
    print("B")
print("C")
Output
C
  • x > 5 is False for x = 3, so both indented lines are skipped.
  • print("C") is not indented, so it always runs.
  • Answer: option 2.
Q2Errors found before running

Multiple Select Question (MSQ): select all that apply.

Each snippet follows a line print("start"). For which snippets is start not printed?

1
print("hi) (the closing quote is missing)
2
print(1 / 0)
3
print(total) when total was never created
4
an if line whose body is not indented
Solution
Idea

Syntax and indentation errors stop everything; runtime errors stop only at their own line.

  • Option 1: SyntaxError, found before anything runs, so start is not printed.
  • Option 2: ZeroDivisionError at run time, so start was already printed.
  • Option 3: NameError at run time, same reason.
  • Option 4: IndentationError, found before anything runs.
  • Answer: options 1 and 4.
Q3Count the output lines

Numerical Answer Type (NAT).

How many lines does this program print?

Python
# a
print("x")  # b
print("y # z")
Solution
Idea

Comments never print; a # inside quotes is just text.

Python
# a
print("x")  # b
print("y # z")
Output
x
y # z
  • The first line is a comment and prints nothing.
  • The second prints x; the third prints y # z.
  • Answer: 2
Q4Which error?

Multiple Choice Question (MCQ): choose the one correct option.

Which error does print(10 + "5") raise?

Python
print(10 + "5")
1
SyntaxError
2
TypeError
3
ValueError
4
NameError
Solution
Idea

The grammar is fine; the types are not.

Python
print(10 + "5")
Error
TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • The line is valid Python, so it is not a SyntaxError.
  • An int cannot be added to a str: TypeError.
  • Answer: option 2.
Revision overview
PythonA programming language
Web, ML, data science, scripting
InterpreterExecutes Python code directly
Console runs one line at a time
SyntaxRules for writing a program
Indentation marks a block
Python BasicsPart 1 · Getting started
IndentationSame block = same level
Wrong indent: IndentationError
Use 4 spaces
CommentsStart with #
Not executed
One # per line
Revision: Python basics on one page
Next · Part 2Output and Variables
02
Part 2

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.

Python
print("I am a boy")
print(3 + 1)
print("The sum is", 3 + 1)
Output
I am a boy
4
The sum is 4
Good to know. When you give print() several objects separated by commas, it puts a space between them. Quotation marks must be matched for a valid string, e.g. print("Hello").
Python
print("Hello)
Error
SyntaxError: unterminated string literal (detected at line 1)

2.2Variables

Definition: variable

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=20variable nameassignment operatorvalue (literal)age is the name, = is the assignment operator, 20 is the value
Figure 3. A simple assignment: name = value
Python
age = 20
print(age)
Output
20

Reassigning a variable

A variable can be assigned different values multiple times. The latest value is retained.

Python
age = 12
age = 18
age = 23
print(age)
Output
23
age = 12age = 18age = 23replacedreplacedlatest value is keptprint(age) → 23
Figure 4. Each assignment replaces the previous value
Reading =. = 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.
Python
score = 10
score = score + 5
print(score)
Output
15

2.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.
Python
my_favourite_fruit = "mango"
myFavFruit = "mango"
print(my_favourite_fruit)
print(myFavFruit)
Output
mango
mango
Python
age = 20
Age = 30
print(age, Age)
Output
20 30
NameValid?Why
ageValidletters only
_countValidstarts with underscore
fav2Validdigits are fine after the first character
my_nameValidunderscore joins words
2favInvalidstarts with a number
my-nameInvalid- is the minus operator
my nameInvalidspaces are not allowed
classInvalida reserved Python keyword
One more rule. A variable name cannot be a Python keyword (such as if, class, True); those words are reserved for the language.
Example 2Trace the variable

What does this program print? Write the value of x after each line.

Python
x = 4
x = x * 2
x = x + 1
print(x)
Solution
Linex
x = 44
x = x * 28
x = x + 19
Python
x = 4
x = x * 2
x = x + 1
print(x)
Output
9

2.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:

Python
print("a", "b", "c", sep="-")
print("x", end="")
print("y")
Output
a-b-c
xy

A comma and a + are not the same. A comma lets print() show any types; + joins only two strings.

Python
print("Total:", 5)
print("Total: " + str(5))
Output
Total: 5
Total: 5

Copy, then change

b = a stores the current value of a in b. Later changes to a do not touch b.

a = 5a5b—b = aa5b5a = 9a9b5b = a copies the value of a at that momentchanging a later does not change b, so print(a, b) shows 9 5
b = a copies the value; changing a later does not change b
Python
a = 5
b = a
a = 9
print(a, b)
Output
9 5

Updating a variable

x += 5 is a short way to write x = x + 5. The same works for -=, *= and so on (extra).

Python
x = 10
x += 5
x -= 3
x *= 2
print(x)
Output
24

Trace: 10 → 15 → 12 → 24.

Names and keywords

Keywords are case-sensitive too: class is reserved but Class is an ordinary name (not recommended).

Python
import keyword
print(keyword.iskeyword("class"), keyword.iskeyword("Class"))
Output
True False

2.5Exam tips and common mistakes

Exam tips
  • 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.
Common mistakes
  • Writing "Total:" + 5: a TypeError. Use a comma, or str(5).
  • Thinking b = a links the two variables so that they change together.
  • Using my-name or 2nd as a name (the first is a minus, the second starts with a digit).
  • Mixing up age and Age: they are different variables.

Practice questions (graded-assignment style)

Q1Trace the copy

Numerical Answer Type (NAT).

What does this program print?

Python
x = 7
y = x
x = x + 3
print(x + y)
Solution
Idea

y keeps the old value of x.

Python
x = 7
y = x
x = x + 3
print(x + y)
Output
17
  • x = 7, then y = 7 (a copy).
  • x becomes 10, but y stays 7.
  • x + y = 10 + 7 = 17.
  • Answer: 17
Q2Valid variable names

Multiple Select Question (MSQ): select all that apply.

Choose the valid variable names.

1
_total
2
2nd_place
3
first-name
4
Total2
Solution
Idea

First 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.
Q3print with sep

Multiple Choice Question (MCQ): choose the one correct option.

What does print("a", "b", sep="") show?

Python
print("a", "b", sep="")
1
a b
2
ab
3
a,b
4
a-b
Solution
Idea

sep is what goes between the objects.

Python
print("a", "b", sep="")
Output
ab
  • With sep="" there is nothing between a and b.
  • Answer: option 2.
Q4Short-hand updates

Multiple Choice Question (MCQ): choose the one correct option.

What does this program print?

Python
count = 4
count += 2
count = count * 2
print(count)
1
6
2
8
3
12
4
10
Solution
Idea

Go line by line: 4 → 6 → 12.

Python
count = 4
count += 2
count = count * 2
print(count)
Output
12
  • count += 2 makes it 6.
  • count = count * 2 makes it 12.
  • Answer: option 3.
Revision overview
print()Strings, numbers, characters
Many objects, separated by commas
Matched quotes
VariableStores a value
name = value
= is the assignment operator
Output and VariablesPart 2
ReassigningSame name, new value
Latest value is retained
Naming rulesLetter or _ first, never a digit
Case-sensitive
Letters, digits, _ only
Revision: output and variables on one page
Next · Part 3Input and Data Types
03
Part 3

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.

Python
name = input("What is your name? ")
print("Name:", name)
Output
What is your name? Ayush
Name: Ayush

Data type of input()

By default, user input is taken as a string. For a numeric value, convert the input with int() or float().

Python
age = int(input("What is your age? "))
pi = float(input("Value of pi: "))
print(age)
print(pi)
Output
What is your age? 19
Value of pi: 3.14
19
3.14
user types21input()a string (text)"21"int()an integer21age = int(input("What is your age? "))input() always gives a string; convert it for numbers
Figure 5. input() gives a string; int() turns it into a number
Why convert? Without int() the input stays text, and adding a number to text is an error:
Python
age = "19"
print(age + 1)
Error
TypeError: can only concatenate str (not "int") to str

3.2Data types

Data typeMeaningExample
strString / text"Hello"
intInteger21
floatFloating-point number2.33
boolBooleanTrue / False
listOrdered collection[2, 4, 6]
str"Hello"textint21whole numberfloat2.33decimal numberboolTrueTrue / Falselist[2, 4, 6]ordered collectionThe five data types in Week 1
Figure 6. The five data types in Week 1

String

A string contains text (one or more characters), written inside quotation marks.

Python
name = "Ayush"
sports = "Basketball and Athletics"
print(name)
print(sports)
Output
Ayush
Basketball and Athletics

Numbers

Integer (int): no decimal part. Floating-point (float): has a decimal part.

Python
x = 21
print(x)
y = 2.33
print(y)
Output
21
2.33

Boolean

A Boolean value is either True or False. Boolean literals start with a capital letter.

Python
isSecond = False
print(isSecond)
isFirst = True
print(isFirst)
Output
False
True
Python
isFirst = true
Error
NameError: name 'true' is not defined

Lists

A list is an ordered collection of data (strings, numbers, and more), written with square brackets [], elements separated by commas.

Python
myList = [2, 4, 6, 8, "yes", "no"]
print(myList)
Output
[2, 4, 6, 8, 'yes', 'no']

3.3Getting the type: type()

Use type() to get the specific data type of a value or variable.

Python
a = 3
b = "Hi"
c = True
d = [1, 3, 5]
print(type(a))
print(type(b))
print(type(c))
print(type(d))
Output
<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 string
  • int() → convert to integer
  • float() → convert to float
  • bool() → convert to Boolean

Convert to string: str()

Python
x = 21
x = str(x)
text = "My fav no. is " + x
print(text)
Output
My fav no. is 21

Convert to integer: int()

Python
x = 4.55
x = int(x)
print(x)
Output
4
Careful. int() 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()

Python
x = 4
x = float(x)
print(x)
Output
4.0

Convert to Boolean: bool()

Python
x = 10
y = "Hello"
z = ""
print(bool(x))
print(bool(y))
print(bool(z))
Output
True
True
False
Valuebool(value)
0, 0.0, "" (empty string), [] (empty list)False
any other number, any non-empty string or listTrue
A common trap. 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.
Python
int("abc")
Error
ValueError: invalid literal for int() with base 10: 'abc'
21str()"21"4.55int()44float()4.010bool()True"Hello"bool()True""bool()FalseType casting changes a value from one data type to another
Figure 7. Type casting examples
Example 3Name the types

Give type() of each: 7, 7.0, "7", 7 > 3, [7], 3 + 2.0, str(7).

Solution
Python
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)))
Output
<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.

Example 4Predict the conversions

What do these print? int(7.9), float(3), str(5) + "1", bool(0), bool("0"), int("12") + 1.

Solution
Python
print(int(7.9))
print(float(3))
print(str(5) + "1")
print(bool(0))
print(bool("0"))
print(int("12") + 1)
Output
7
3.0
51
False
True
13

Note bool("0") is True: the string "0" is not empty.

Example 5Age next year

Read the user's age and print their age next year.

Solution
Python
age = int(input("Enter your age: "))
print("Next year:", age + 1)
Output
Enter your age: 20
Next year: 21

Without int() the second line would raise a TypeError.

3.5Going deeper: strings versus numbers, and the conversion rules

works as expectedint("12") → 12float("3") → 3.0float(4) → 4.0str(7) → "7"safe conversionsworks, but surprisesint(4.9) → 4int(-4.9) → -4bool("False") → Truebool(" ") → Truecheck these twiceraises an errorint("3.5")int("abc")float("")"5" + 1ValueError / TypeError
Which conversions work, which surprise, which fail

Conversions are exam favourites. Learn the three groups in the chart, then check them in a program:

Python
print(int(float("3.5")))
print(float("3"))
print(int(True))
print(str(3.0))
Output
3
3.0
1
3.0
  • int("3.5") is an error: a string must look like a whole number. Go through float first: int(float("3.5")) is 3.
  • int(True) is 1 and int(False) is 0.
Python
print(int("3.5"))
Error
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.

Python
a = "3"
b = "4"
print(a + b)
print(int(a) + int(b))
print(a * 4)
print(int(a) * 4)
Output
34
7
3333
12

The classic input() bug

Both inputs arrive as text, so a + b glues them together. Convert first.

Python
a = input("First: ")
b = input("Second: ")
print(a + b)
print(int(a) + int(b))
Output
First: 3
Second: 4
34
7

What type does an expression give?

Python
print(type(10 / 2))
print(type(10 // 2))
print(type(2 ** 3))
print(type(3 + 2.0))
Output
<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

Exam tips
  • First decide the type of every value in the expression, then apply the operator.
  • Remember: input() always returns str.
  • For bool() questions, only 0, 0.0, an empty string and an empty list are False. A string like " " or "0" is True.
Common mistakes
  • Writing int("3.5") and expecting 3.
  • Believing bool("False") is False.
  • Adding the results of two input() calls without int().
  • Expecting 10 / 2 to be the integer 5 (it is the float 5.0).

Practice questions (graded-assignment style)

Q1Type of a division

Multiple Choice Question (MCQ): choose the one correct option.

What does print(type(10 / 5)) show?

Python
print(type(10 / 5))
1
<class 'int'>
2
<class 'float'>
3
<class 'str'>
4
<class 'bool'>
Solution
Idea

/ always gives a float.

Python
print(type(10 / 5))
Output
<class 'float'>
  • 10 / 5 is 2.0, a float, even though it divides exactly.
  • Answer: option 2.
Q2Convert, then multiply

Numerical Answer Type (NAT).

What does this program print?

Python
x = "5"
y = 3
print(int(x) * y)
Solution
Idea

Convert the text before multiplying.

Python
x = "5"
y = 3
print(int(x) * y)
Output
15
  • int(x) is 5.
  • 5 * 3 = 15.
  • Answer: 15
Q3Which conversions fail?

Multiple Select Question (MSQ): select all that apply.

Which of these raise an error?

1
int("7.5")
2
int(7.5)
3
float("abc")
4
bool("False")
Solution
Idea

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.
Q4Text or numbers?

Multiple Choice Question (MCQ): choose the one correct option.

What does print("3" + "4", 3 + 4) show?

Python
print("3" + "4", 3 + 4)
1
7 7
2
34 7
3
34 34
4
7 34
Solution
Idea

Strings are joined, numbers are added.

Python
print("3" + "4", 3 + 4)
Output
34 7
  • "3" + "4" joins the text: 34.
  • 3 + 4 adds the numbers: 7.
  • Answer: option 2.
Q5Count the Trues

Numerical Answer Type (NAT).

How many of these values are True when passed to bool(): 0, "0", "", [], 0.0, " "?

Python
print(bool(0), bool("0"), bool(""), bool([]), bool(0.0), bool(" "))
Solution
Idea

Only zero, empty string and empty list are False.

Python
print(bool(0), bool("0"), bool(""), bool([]), bool(0.0), bool(" "))
Output
False True False False False True
  • "0" is a non-empty string: True.
  • " " contains a space: True.
  • The other four are False.
  • Answer: 2
Revision overview
input()Asks the user, optional prompt
Always a string by default
int() / float() for numbers
Data typesstr, int, float, bool, list
True / False start with a capital
type()Returns the data type
type(3) is int
Input and Data TypesPart 3
Castingstr(), int(), float(), bool()
int(4.55) is 4 (drops decimals)
bool()0, "", [] are False
Other values are True
"False" is True
Revision: input, data types and casting on one page
Next · Part 4Operators
04
Part 4

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.

OperatorOperationExample (x = 10, y = 5)Result
+Additionx + y15
-Subtractionx - y5
*Multiplicationx * y50
/Divisionx / y2.0
**Exponentiationx ** 2100
%Remainder / modulusx % y0
//Floor divisionx // 33
Python
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)
Output
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Exponentiation: 100
Remainder: 0
Floor division: 3

Addition and string concatenation

+ also concatenates strings (joins them end to end).

Python
x = "Hello"
y = "World"
print(x + y)
Output
HelloWorld

Division

The / operator returns the quotient as a floating-point result, even when it divides exactly.

Python
x = 10
y = 5
print(x / y)
Output
2.0

Exponentiation

** raises the left operand to the power of the right operand.

Python
x = 2
print(x ** 3)
Output
8

Remainder / modulus

% returns the remainder after division, e.g. 5 divided by 2 leaves a remainder of 1.

Python
x = 5
print(x % 2)
Output
1

Floor division

// gives the quotient rounded down to the nearest integer.

Python
x = 5
print(x // 2)
Output
2
5 divided by 2group of 2group of 2left over5 / 22.5exact, always a float5 // 22full groups (floor)5 % 21remainder
Figure 8. 5 / 2, 5 // 2 and 5 % 2
Together. For whole numbers, a == (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.
Python
print(17 // 5, 17 % 5)
print(-5 // 2, -5 % 2)
Output
3 2
-3 1

4.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.

Python
x = 10 + 3 * 5
print(x)  # 25
Output
25

Grouping with parentheses

The expression inside parentheses evaluates first.

Python
x = (10 + 3) * 5
print(x)  # 65
Output
65
10 + 3 * 5multiply first10 + 1525(10 + 3) * 5brackets first13 * 565
Figure 9. Multiplication runs before addition; parentheses change that
Python's actual order

The 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.

Python
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)
Output
7
16.0
512
-4 4

If 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.

Full details in Part 5. The next part gives the complete precedence table, the rule for tied operators (associativity), traced examples and practice questions.

4.3Comparison operators

Comparison operators compare two operands and return a Boolean value (True or False).

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
Python
print(5 == 5)
print(10 != 5)
print(8 > 4)
print(8 < 4)
print(8 >= 8)
print(8 <= 8)
Output
True
True
True
False
True
True
Do not mix up = and ==. = assigns a value; == asks whether two values are equal.

Comparing strings

Python
print("python" == "python")
print("python" == "Python")
Output
True
False

4.4Logical operators

Logical operators are commonly used with Boolean expressions. Python has three:

OperatorMeaning
andLogical AND
orLogical OR
notLogical NOT

and

Returns True when both operands are true.

Python
print(True and True)
print(True and False)
print(False and False)
Output
True
False
False

Example with expressions:

Python
x = (5 == 5) and (4 == 4)
print(x)
expr = (2 > 3) and (8 > 2)
print(expr)
Output
True
False

or

Returns True when at least one operand is true.

Python
print(True or True)
print(True or False)
print(False or False)
Output
True
True
False

not

Reverses a Boolean value.

Python
print(not False)
print(not True)
expr = not (10 > 20)
print(expr)
Output
True
False
True
and
ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
or
ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
not
Anot A
TrueFalse
FalseTrue
Order. Among logical operators not runs first, then and, then or. So True or False and False is True.
Example 6Evaluate with the right order

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.

Solution
ExpressionStepsValue
2 + 3 * 42 + 1214
(2 + 3) * 45 * 420
2 ** 3 * 28 * 216
10 - 4 - 3left to right: 6 - 33
20 / 4 / 55.0 / 51.0
7 // 2 * 23 * 26
17 % 5 + 12 + 13
-3 ** 2** first: -(3 ** 2)-9
Example 7Boolean expressions

Evaluate: (5 > 2) and (10 < 20), not (3 == 3), (1 > 2) or (2 > 1), 5 > 2 and not 3 > 4.

Solution
Python
print((5 > 2) and (10 < 20))
print(not (3 == 3))
print((1 > 2) or (2 > 1))
print(5 > 2 and not 3 > 4)
Output
True
False
True
True

Last one: 5 > 2 is True; 3 > 4 is False, so not makes it True; True and True is True.

Example 8Divide and share

47 sweets are packed in boxes of 6. How many full boxes, and how many sweets are left over? Use operators.

Solution
Python
sweets = 47
box = 6
print("Full boxes:", sweets // box)
print("Left over:", sweets % box)
Output
Full boxes: 7
Left over: 5

Check: 6 * 7 + 5 = 47.

4.5Going deeper: negative numbers, a test for leap years, and short-circuiting

-5-4-3-2-10-7 / 2 = -3.5// rounds DOWN → -4int(-3.5) → -3 (toward 0)-7 // 2 and -7 % 2-7 = 2 · (-4) + 1, so -7 // 2 = -4 and -7 % 2 = 1
// rounds down on the number line, so the remainder is never negative here

// always rounds down (towards minus infinity), while int() cuts the decimals (towards zero). With negative numbers they differ, and % follows //:

Python
print(-7 // 2, -7 % 2)
print(7 // -2, 7 % -2)
print(int(-3.5))
Output
-4 1
-4 -1
-3

The identity a == (a // b) * b + a % b still holds:

Python
a, b = -7, 2
print(a == (a // b) * b + a % b)
Output
True

Putting 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:

Python
for y in (2024, 1900, 2000):
    print((y % 4 == 0 and y % 100 != 0) or y % 400 == 0)
Output
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

x = 0Safe order: the left side decidesx != 0 → FalseFalse and ...10 / x > 1never evaluatedReversed order: the error is reached first10 / x > 1 → errorx != 0ZeroDivisionError"A and B": if A is False, B is never evaluated
"A and B": when A is False, B is never evaluated

A and B stops at the first False; A or B stops at the first True. The order can decide whether an error happens:

Python
x = 0
print(x != 0 and 10 / x > 1)
Output
False
Python
x = 0
print(10 / x > 1 and x != 0)
Error
ZeroDivisionError: division by zero

Comparing floats (extra)

Decimals are stored approximately, so avoid == on floats that come from arithmetic:

Python
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
Output
0.30000000000000004
False

4.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.

FunctionWhat it doesExample
abs(x)the size of xx without its signabs(-7) is 7
pow(a, b)same as a ** b; pow(a, b, m) gives (a ** b) % m efficientlypow(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 placesround(3.14159, 2) is 3.14
Python
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))
Output
7
3.5
1024
(3, 2)
(-4, 3)
9

round() 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:

Python
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))
Output
2
4
-2
7
1200
3.14
Do not confuse four ways to turn a decimal into a whole number. int() drops the decimal part (rounds toward zero), round() goes to the nearest, math.floor() goes down and math.ceil() goes up. For −3.7-3.7 they give −3-3, −4-4, −4-4 and −3-3 (and for −3.2-3.2, ceil gives −3-3).
Python
import math
print(int(-3.7))
print(round(-3.7))
print(math.floor(-3.7))
print(math.ceil(-3.2))
Output
-3
-4
-4
-3

Float 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.

Python
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 first
Output
0.30000000000000004
False
True
True
  • Never test two decimals with ==. Compare their difference to a small tolerance, or round both first.
  • Whole numbers are different: int has no limit on size (2 ** 100 prints all 31 digits), and integer arithmetic is exact.
  • Division always gives a float: 10 / 5 is 2.0, while 10 // 5 is the int 2. Floor division of floats stays a float: 7.0 // 2 is 3.0.
Python
print(10 / 5)
print(10 // 5)
print(7.0 // 2)
print(2 ** -1)             # a negative power gives a float
Output
2.0
2
3.0
0.5

4.7Exam tips and common mistakes

Exam tips
  • For negative numbers compute // by rounding down, then get % from a - (a // b) * b.
  • Break a long condition into pieces and evaluate each comparison first; then apply not, and, or.
  • Use 1 < x < 10 for a range check; it works as two comparisons joined by and.
Common mistakes
  • Rounding -7 // 2 to -3 (toward zero). It is -4.
  • Writing x = 5 where you mean x == 5.
  • Expecting 0.1 + 0.2 == 0.3 to be True.
  • Forgetting that and ranks above or.

Practice questions (graded-assignment style)

Q1Floor division of a negative

Numerical Answer Type (NAT).

What does print(-17 // 5) show?

Python
print(-17 // 5)
Solution
Idea

Floor division rounds down.

Python
print(-17 // 5)
Output
-4
  • -17 / 5 = -3.4.
  • Rounding down gives -4.
  • Answer: -4
Q2Remainder of a negative

Numerical Answer Type (NAT).

What does print(-17 % 5) show?

Python
print(-17 % 5)
Solution
Idea

Use a == (a // b) * b + a % b.

Python
print(-17 % 5)
Output
3
  • -17 // 5 = -4.
  • -17 = 5 * (-4) + r, so r = 3.
  • Answer: 3
Q3Which are True?

Multiple Select Question (MSQ): select all that apply.

Which expressions have the value True?

Python
print(17 % 5 == 2, -5 // 2 == -2, 1 < 5 < 10, "a" < "B")
1
17 % 5 == 2
2
-5 // 2 == -2
3
1 < 5 < 10
4
"a" < "B"
Solution
Idea

Evaluate each one separately.

Python
print(17 % 5 == 2, -5 // 2 == -2, 1 < 5 < 10, "a" < "B")
Output
True False True False
  • Option 1: 17 = 5·3 + 2, so True.
  • Option 2: -5 // 2 is -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.
Q4Two divisions

Multiple Choice Question (MCQ): choose the one correct option.

What does print(10 / 5, 10 // 5) show?

Python
print(10 / 5, 10 // 5)
1
2 2
2
2.0 2
3
2.0 2.0
4
2 2.0
Solution
Idea

/ always gives a float; // on ints gives an int.

Python
print(10 / 5, 10 // 5)
Output
2.0 2
  • 10 / 5 is 2.0.
  • 10 // 5 is 2.
  • Answer: option 2.
Q5Short-circuit

Multiple Choice Question (MCQ): choose the one correct option.

What does this program print?

Python
x = 0
print(x == 0 or 10 / x > 1)
1
True
2
False
3
ZeroDivisionError
4
Nothing
Solution
Idea

or stops as soon as it sees True.

Python
x = 0
print(x == 0 or 10 / x > 1)
Output
True
  • x == 0 is True, so or never evaluates 10 / x > 1: no error.
  • Answer: option 1.
Q1Rounding two halves

Numerical Answer Type (NAT).

What does the following program print?

Python
print(round(2.5) + round(3.5))
Solution
Idea

For exact halves, round() goes to the even neighbour.

Python
print(round(2.5) + round(3.5))
Output
6
  • round(2.5) is 2 (even), round(3.5) is 4 (even). Sum 6.
  • A student who expects "round half up" would say 3 + 4 = 7. That is the common wrong answer.
  • Answer: 6
Q2Which expressions are True?

Multiple Select Question (MSQ): select all that apply.

Which of these expressions evaluate to True?

1
round(2.5) == 2
2
0.1 + 0.2 == 0.3
3
divmod(17, 5) == (3, 2)
4
abs(-3.0) == 3
5
10 / 5 == 2
6
int(-3.7) == -4
Solution
Idea

Evaluate each one separately.

Python
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)
Output
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 == 3 is True.
  • 5 True: 2.0 == 2 compares values, not types. 6 False: int() truncates toward zero, giving -3.
  • Answer: options 1, 3, 4 and 5.
Q3The remainder from divmod

Numerical Answer Type (NAT).

What does the program print?

Python
q, r = divmod(-17, 5)
print(q, r)
Solution
Idea

divmod(a, b) is (a // b, a % b), and // rounds down.

Python
q, r = divmod(-17, 5)
print(q, r)
Output
-4 3
  • -17 // 5 = -4 (since −3.4-3.4 rounds down), and −17=5(−4)+3-17 = 5(-4) + 3, so -17 % 5 = 3.
  • Answer: -4 3 (the remainder is 3)
Q4Rounding to hundreds

Numerical Answer Type (NAT).

What does print(round(1234, -2)) show?

Solution
Idea

A negative second argument rounds to tens (−1-1), hundreds (−2-2), and so on.

Python
print(round(1234, -2))
Output
1200
  • 12341234 is closer to 12001200 than to 13001300.
  • Answer: 1200
Q5Comparing decimals safely

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?

1
a == 0.3
2
abs(a - 0.3) < 1e-9
3
a is 0.3
4
a - 0.3 == 0
Solution
Idea

Compare the size of the difference with a small tolerance.

Python
a = 0.1 + 0.2
print(a == 0.3)
print(abs(a - 0.3) < 1e-9)
print(a - 0.3 == 0)
Output
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.
Revision overview
Arithmetic+ - * / ** % //
/ always gives a float
+ joins strings
Remainder and floor5 % 2 = 1
5 // 2 = 2
a = (a // b) * b + a % b
Precedence( ) then ** then * / // % then + -
Same level: left to right
10 + 3 * 5 = 25, (10 + 3) * 5 = 65
OperatorsPart 4
Comparison== != > < >= <=
Result is True or False
= assigns, == compares
Logicaland: both true
or: at least one true
not: reverses
Strings"python" == "python" is True
"python" == "Python" is False
Revision: operators on one page
Next · Part 5Precedence and Associativity
05
Part 5

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.

Python
print(10 + 3 * 5)    # 25, not 65
print((10 + 3) * 5)  # 65
Output
25
65
Takeaway

* 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.

RankOperatorsMeaning
1( )Parentheses
2**Exponent
3* / // %Multiplication, Division, Floor Division, Modulus
4+ -Addition, Subtraction
5== != > < >= <=Comparisons
6notLogical NOT
7andLogical AND
8orLogical OR
Memory hook

Brackets → Exponent → Multiply/Divide group → Add/Subtract → Comparisons → NOT → AND → OR. Arithmetic always finishes before comparisons, and comparisons always finish before logic.

1( )parentheses2**exponent3+x -xunary plus / minus4* / // %multiply, divide, floor, remainder5+ -add, subtract6== != > < >= <=comparisons7notBoolean NOT8andBoolean AND9orBoolean ORruns firstSame row: left to right (except **, which goes right to left)
Figure 10. Operator precedence, highest first (unary +x and -x sit between ** and *)
Two details the table leaves out. The unary minus in -x ranks just below **, so -2 ** 2 is -(2 ** 2) = -4, while (-2) ** 2 is 4. And the comparison row has six operators: == != > < >= <=.
Python
print(-2 ** 2)
print((-2) ** 2)
Output
-4
4

5.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

Python
x = 10 + 3 * 5

* is rank 3, + is rank 4: multiplication first.

Steps
10 + 3 * 5
10 + 15
25

Example 2: parentheses override

Python
x = (10 + 3) * 5

( ) is rank 1: the addition inside runs first.

Steps
(10 + 3) * 5
13 * 5
65

Example 3: exponent beats multiplication

Python
x = 2 * 3 ** 2

** is rank 2, higher than * at rank 3.

Steps
2 * 3 ** 2
2 * 9
18

Example 4: arithmetic, then comparison, then logic

Python
result = 5 + 3 > 6 and not False

Arithmetic (rank 4) → comparison (rank 5) → not (rank 6) → and (rank 7).

Steps
5 + 3 > 6 and not False
8 > 6 and not False
True and not False
True and True
True

Check all four by running them:

Python
print(10 + 3 * 5)
print((10 + 3) * 5)
print(2 * 3 ** 2)
print(5 + 3 > 6 and not False)
Output
25
65
18
True

5.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.

Definition: associativity

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.

OperatorsAssociativity
* / // %Left → Right
+ -Left → Right
ComparisonsLeft → Right
and, orLeft → Right
**Right → Left
notRight → Left
Left → RightRight → Left20 - 5 - 32 ** 3 ** 220-5-32**3**2first: 20 - 5 = 15then: 15 - 3 = 12first: 3 ** 2 = 9then: 2 ** 9 = 512((20 - 5) - 3) = 12(2 ** (3 ** 2)) = 512
Figure 11. Left-to-right and right-to-left grouping
Comparisons are special. A chain such as 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:
Python
print(5 > 3 > 1)
print((5 > 3) > 1)
Output
True
False

5.6Left-to-right associativity

* and // have the same precedence. If both appear in one expression, the left one is evaluated first.

Example: * and // tied

Python
x = 100 * 10 // 3

Both are rank 3, so left to right: * first, then //.

Steps
100 * 10 // 3
1000 // 3
333

Reversing the order would give a different answer: 100 * (10 // 3) = 300.

Subtraction is also left to right

Python
x = 20 - 5 - 3
Steps
20 - 5 - 3
15 - 3
12

If it were right-to-left you would get 20 - 2 = 18, which is wrong.

Python
print(100 * 10 // 3)    # 333
print(100 * (10 // 3))  # 300
print(20 - 5 - 3)       # 12
Output
333
300
12

5.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

Python
2 ** 3 ** 8 ** 4

Python 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.

Do not run this one. 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

Steps
2 ** 3 ** 2
2 ** (3 ** 2)
2 ** 9
512

Not 64: that would be (2 ** 3) ** 2.

Python
print(2 ** 3 ** 2)     # 512  (right to left)
print((2 ** 3) ** 2)   # 64   (forced left)
Output
512
64

5.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.

Steps
not not True
not (not True)
not False
True
Python
print(not not True)   # True
print(not not False)  # False
Output
True
False

5.9Combining precedence and associativity

The full rule Python follows, in order:

  1. Precedence first: the higher-ranked operator runs before the lower-ranked one.
  2. Associativity second: only used to break a tie between equal-precedence operators.

Example: everything at once

Python
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, then 3 * 2 → 6.
  • Step 3: addition (rank 4): 256 + 6.
Steps
2 ** 2 ** 3 + 10 // 3 * 2
256 + 10 // 3 * 2
256 + 3 * 2
256 + 6
262
Python
x = 2 ** 2 ** 3 + 10 // 3 * 2
print(x)
Output
262

5.10Common mistakes

  • Reading 2 ** 3 ** 2 left to right and wrongly getting 64 instead of 512.
  • Assuming * beats / or //: they are tied, so it is left to right.
  • Forgetting that arithmetic finishes before comparison, and comparison before logic.
  • Thinking and and or are equal: and is higher than or.
  • Forgetting not binds tighter than and / or.
Safest habit

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.

P16 + 4 * 2

What is the value of 6 + 4 * 2?

Solution

* (rank 3) beats + (rank 4): 4 * 2 = 8 first. Then 6 + 8.

Python
print(6 + 4 * 2)
Output
14
P2(6 + 4) * 2

What is the value of (6 + 4) * 2?

Solution

Parentheses (rank 1) run first → 10, then 10 * 2.

Python
print((6 + 4) * 2)
Output
20
P32 ** 3 ** 2

What is the value of 2 ** 3 ** 2?

Solution

** is right to left → 3 ** 2 = 9 first, then 2 ** 9 = 512. A left-to-right reading would wrongly give (2 ** 3) ** 2 = 64.

Python
print(2 ** 3 ** 2)
Output
512
P450 // 7 * 2

What is the value of 50 // 7 * 2?

Solution

Both are rank 3 → left to right. 50 // 7 = 7, then 7 * 2.

Python
print(50 // 7 * 2)
Output
14
P510 % 4 + 2 * 3

What is the value of 10 % 4 + 2 * 3?

Solution

Rank 3 first, left to right: 10 % 4 = 2, then 2 * 3 = 6. Then rank 4: 2 + 6.

Python
print(10 % 4 + 2 * 3)
Output
8
P6not True and False

What is the value of not True and False?

Solution

not (rank 6) binds tighter than and (rank 7). not True → False, then False and False.

Python
print(not True and False)
Output
False
P7True or False and False

What is the value of True or False and False?

Solution

and (rank 7) beats or (rank 8) → False and False = False first. Then True or False.

Python
print(True or False and False)
Output
True
P84 + 6 > 8

What is the value of 4 + 6 > 8?

Solution

Arithmetic (rank 4) before comparison (rank 5) → 10 > 8.

Python
print(4 + 6 > 8)
Output
True
P92 ** 3 ** 8 ** 4

How does Python parenthesise 2 ** 3 ** 8 ** 4? Show the grouping (do not evaluate it).

Solution

** is right to left, so the rightmost pair binds first: (2 ** (3 ** (8 ** 4))).

P102 ** 3 + 4 * 2 - 6 // 4

What is the value of 2 ** 3 + 4 * 2 - 6 // 4?

Solution

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.

Python
print(2 ** 3 + 4 * 2 - 6 // 4)
Output
15

5.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.

+③2*②3**①42Order of evaluation① 4 ** 2 = 16② 3 * 16 = 48③ 2 + 48 = 50Highest rank first: ** then * then +Same rank: left to right (except ** and not)2 + 3 * 4 ** 2
Evaluation tree of 2 + 3 * 4 ** 2: **, then *, then +

A routine that always works

  1. Put brackets around everything inside parentheses first.
  2. Mark the operators and note their ranks (Part 5.2).
  3. Evaluate rank by rank from the top. Ties go left to right, except ** and not (right to left).
  4. Write the new, shorter expression after every step, as the traced examples do.

Tricky cases, checked by running them

Python
print(2 ** -1)
print(not 1 == 2)
print(7 + 8 % 3 * 2)
print(-2 ** 2, (-2) ** 2)
Output
0.5
True
11
-4 4
  • 2 ** -1: a minus sign directly after ** belongs to the exponent, so it is 2 ** (-1) = 0.5.
  • not 1 == 2: the comparison runs first, so it is not (1 == 2), which is True.
  • 7 + 8 % 3 * 2: % and * tie, left to right: 8 % 3 = 2, then 2 * 2 = 4, then 7 + 4 = 11.
  • -2 ** 2 is -(2 ** 2) = -4, unlike (-2) ** 2 = 4.

5.12Exam tips and tricky cases

Exam tips
  • Always rewrite the expression after each step; skipping steps causes most errors.
  • Same rank means left to right, so 100 / 10 * 2 is (100 / 10) * 2, not 100 / (10 * 2).
  • When in doubt, add parentheses in your own answer sheet to show the order you used.
Common mistakes
  • Doing all the multiplications before all the divisions ("DMAS" is only a memory aid).
  • Reading 2 ** 3 ** 2 as (2 ** 3) ** 2.
  • Forgetting that not comes after the comparisons.
  • Giving an integer answer when / was involved (the result is a float).

Practice questions (graded-assignment style)

Q1Evaluate with the right order

Numerical Answer Type (NAT).

What does print(2 + 3 * 4 ** 2) show?

Python
print(2 + 3 * 4 ** 2)
Solution
Idea

** first, then *, then +.

Python
print(2 + 3 * 4 ** 2)
Output
50
  • 4 ** 2 = 16.
  • 3 * 16 = 48.
  • 2 + 48 = 50.
  • Answer: 50
Q2Ties and floats

Numerical Answer Type (NAT).

What does print(100 / 10 * 2 // 3) show?

Python
print(100 / 10 * 2 // 3)
Solution
Idea

/, * and // tie: left to right.

Python
print(100 / 10 * 2 // 3)
Output
6.0
  • 100 / 10 = 10.0.
  • 10.0 * 2 = 20.0.
  • 20.0 // 3 = 6.0 (a float because of the float operand).
  • Answer: 6.0
Q3Mixed operators

Multiple Choice Question (MCQ): choose the one correct option.

What does this program print?

Python
print(not 5 > 3 or 2 ** 2 == 4)
1
True
2
False
3
4
4
Error
Solution
Idea

Comparisons first, then not, then or.

Python
print(not 5 > 3 or 2 ** 2 == 4)
Output
True
  • 5 > 3 is True, so not 5 > 3 is False.
  • 2 ** 2 == 4 is True.
  • False or True is True.
  • Answer: option 1.
Q4Which statements hold?

Multiple Select Question (MSQ): select all that apply.

Which of these comparisons are True?

Python
print(2 ** 3 ** 2 == 512, -3 ** 2 == 9, 10 - 4 - 3 == 3, 8 / 2 * 4 == 1)
1
2 ** 3 ** 2 == 512
2
-3 ** 2 == 9
3
10 - 4 - 3 == 3
4
8 / 2 * 4 == 1
Solution
Idea

Check the associativity of each.

Python
print(2 ** 3 ** 2 == 512, -3 ** 2 == 9, 10 - 4 - 3 == 3, 8 / 2 * 4 == 1)
Output
True False True False
  • Option 1: ** is right to left: 2 ** 9 = 512.
  • Option 2: -3 ** 2 is -9, not 9.
  • Option 3: (10 - 4) - 3 = 3.
  • Option 4: 8 / 2 * 4 is 4.0 * 4 = 16.0.
  • Answer: options 1 and 3.
Q5Remainder in a sum

Numerical Answer Type (NAT).

What does print(7 + 8 % 3 * 2) show?

Python
print(7 + 8 % 3 * 2)
Solution
Idea

% and * tie, so left to right.

Python
print(7 + 8 % 3 * 2)
Output
11
  • 8 % 3 = 2.
  • 2 * 2 = 4.
  • 7 + 4 = 11.
  • Answer: 11
Revision overview
PrecedenceDecides which operator runs first
Higher in the table = first
( ) overrides everything
The table( ) → ** → * / // % → + - → comparisons → not → and → or
Tied operatorsSame row = same precedence
Associativity breaks the tie
Precedence & AssociativityPart 5
Left → Right* / // % · + - · comparisons · and, or
20 - 5 - 3 = 12
100 * 10 // 3 = 333
Right → Left** and not
2 ** 3 ** 2 = 512
not not True = True
HabitsMixed operators: add parentheses
not > and > or
Arithmetic → comparison → logic
Revision: precedence and associativity on one page
Next · Part 6Strings
06
Part 6

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.

Python
a = "Hello"
b = "World"
text = a + b
print(text)
Output
HelloWorld
Spaces and numbers. + 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.
Python
a = "Hello"
b = "World"
print(a + " " + b)
print("Age: " + str(21))
Output
Hello World
Age: 21
Python
print("Age: " + 21)
Error
TypeError: can only concatenate str (not "int") to str

6.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.

P0−6y1−5t2−4h3−3o4−2n5−1indexnegativeIndexing starts at 0. Negative indices count from the end: −1 is the last character.
Figure 12. Positive and negative indices of "Python"
Python
text = "Hi everyone"
print(text[0])
print(text[1])
print(text[-1])
print(text[-2])
Output
H
i
e
n
Out of range. A string with 5 characters has indices 0 … 4. Asking for index 5 is an error. Also, strings cannot be changed through an index.
Python
text = "Hello"
print(text[5])
Error
IndexError: string index out of range
Python
text = "Hello"
text[0] = "J"
Error
TypeError: 'str' object does not support item assignment

6.3String slicing

Slicing accesses a range of characters: text[start:stop]. The stop index is exclusive.

Python
text = "Python Lover"
print(text[2:5])
Output
tho

Slicing from a position to the end

If the second index is omitted, the slice runs to the end of the string.

Python
text = "Python Lover"
print(text[2:])
Output
thon Lover
01234567891011Python␣Lovertext[2:5]→ "tho"start 2 is included, stop 5 is notPython␣Lovertext[2:]→ "thon Lover"no stop: runs to the end
Figure 13. text[2:5] and text[2:]
Counting the slice. text[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:
Python
text = "Python Lover"
print(text[:3])
print(text[-5:])
Output
Pyt
Lover

6.4String length: len()

len() returns the number of characters in a string.

Python
text = "Hello"
print(len(text))
Output
5
Spaces count. len("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.

Python
text = "Gagan"
print(text * 2)
print(text * 4)
Output
GaganGagan
GaganGaganGaganGagan

6.6String comparison

Strings can be compared using comparison operators. Python compares strings based on character ordering.

Python
x = "India"
print(x == "India")
print(x == "india")
Output
True
False

String comparisons can also use > and <:

Python
print("apple" > "one")
print("abc" < "abcd")
Output
False
True
"apple"apple"one"onefirst characters differ:'a' < 'o'so "apple" < "one""abc"abc"abcd"abcdsame start "abc"; the shorterstring is smallerso "abc" < "abcd"
Figure 14. Strings are compared character by character
How the order works. Python compares the first characters that differ; if one string is a prefix of the other, the shorter is smaller. Characters are ordered by their code, so every capital letter comes before every small letter, and digits compare as characters, not numbers.
Python
print("Zebra" < "apple")
print("10" < "9")
print(10 < 9)
Output
True
True
False
Example 9Index and slice

For text = "Programming" find: text[0], text[-1], text[3:7], text[:4], text[5:], len(text).

Solution
Python
text = "Programming"
print(text[0])
print(text[-1])
print(text[3:7])
print(text[:4])
print(text[5:])
print(len(text))
Output
P
g
gram
Prog
amming
11
Index012345678910
charProgramming
Example 10Build a string

What does print("Ha" * 3 + "!") print? And what does print("-" * 10) print?

Solution
Python
print("Ha" * 3 + "!")
print("-" * 10)
Output
HaHaHa!
----------

* runs before +: first "HaHaHa", then the "!" is joined.

Example 11Compare the strings

True or False? "cat" < "dog", "cat" < "Cat", "cat" == "cat ", "10" < "9".

Solution
Python
print("cat" < "dog")
print("cat" < "Cat")
print("cat" == "cat ")
print("10" < "9")
Output
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 (but 10 < 9 as 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).

Python
text = "Hello"
print(text[2:100])
print(repr(text[10:]))
print(text[:-1])
print(text[::-1])
print(text[::2])
Output
llo
''
Hell
olleH
Hlo
  • text[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.

Python
text = "Hello"
new = "J" + text[1:]
print(new)
print(text)
Output
Jello
Hello

Building strings: * runs before +

"Ha" * 3higher rank: runs first"HaHaHa"intermediate value+ "!"then the join"HaHaHa!"final string
print("Ha" * 3 + "!") builds the string in two steps

Is one string inside another? (extra)

Python
print("th" in "python", "x" in "python")
Output
True False

6.8Exam tips and common mistakes

Exam tips
  • Count indices from 0; the last valid index is len(text) - 1, and text[a:b] has b - a characters.
  • 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.
Common mistakes
  • 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)

Q1A slice

Multiple Choice Question (MCQ): choose the one correct option.

What does this program print?

Python
s = "Programming"
print(s[2:6])
1
gram
2
ogra
3
ogram
4
rogra
Solution
Idea

Indices: P0 r1 o2 g3 r4 a5 m6. The stop index is excluded.

Python
s = "Programming"
print(s[2:6])
Output
ogra
  • s[2:6] takes indices 2, 3, 4, 5: o g r a.
  • Answer: option 2.
Q2Length with punctuation

Numerical Answer Type (NAT).

What does print(len("Hi, there!")) show?

Python
print(len("Hi, there!"))
Solution
Idea

Every character counts, including spaces and punctuation.

Python
print(len("Hi, there!"))
Output
10
  • H, i, comma, space, t, h, e, r, e, exclamation mark: 10 characters.
  • Answer: 10
Q3Negative start

Multiple Choice Question (MCQ): choose the one correct option.

What does print("Hello"[-3:]) show?

Python
print("Hello"[-3:])
1
Hel
2
llo
3
lo
4
ell
Solution
Idea

Start 3 characters from the end and go to the end.

Python
print("Hello"[-3:])
Output
llo
  • -3 is the third character from the end: l.
  • Answer: option 2.
Q4Which lines raise errors?

Multiple Select Question (MSQ): select all that apply.

Which of these raise an error?

1
"Hello"[5]
2
"Hello"[2:50]
3
"Hello"[0] = "J"
4
"Hello" + 5
Solution
Idea

Slices 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.
Q5Build a string

Multiple Choice Question (MCQ): choose the one correct option.

What does print("ab" * 2 + "c" * 3) show?

Python
print("ab" * 2 + "c" * 3)
1
ababccc
2
abababccc
3
abcabcabc
4
ababcccc
Solution
Idea

* runs before +.

Python
print("ab" * 2 + "c" * 3)
Output
ababccc
  • "ab" * 2 is abab; "c" * 3 is ccc.
  • Then the two are joined.
  • Answer: option 1.
Revision overview
Concatenation"Hello" + "World" = "HelloWorld"
Only string + string
str(21) to join a number
Indexingtext[0] is the first character
text[-1] is the last
Starts at 0
Slicingtext[a:b], stop is exclusive
text[2:] runs to the end
text[:3] starts at the beginning
StringsPart 6
len()Number of characters
Spaces count
Replication"Gagan" * 2 = "GaganGagan"
"Gagan" * 4
Comparison== is case-sensitive
> < use character order
"apple" > "one" is False, "abc" < "abcd" is True
Revision: strings on one page
Next · Practice zoneTry It Yourself
07
Practice zone

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.

Q1Variables

Create a variable age, assign it a value, then print it.

Solution
Python
# Q1
age = 20
print(age)
Output
20
Q2Input

Take the user's name as input and print it.

Solution
Python
# Q2
name = input("Enter your name: ")
print(name)
Output
Enter your name: Asha
Asha
Q3Type conversion

Take a number as input and convert it to an integer.

Solution
Python
# Q3
number = int(input("Enter a number: "))
print(number)
Output
Enter a number: 42
42
Q4Arithmetic

For x = 15 and y = 4, find the sum, difference, product, quotient, remainder, and floor quotient.

Solution
Python
# Q4
x = 15
y = 4
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
print(x // y)
Output
19
11
60
3.75
3
3

15 / 4 is 3.75; 15 % 4 is the remainder 3; 15 // 4 is the floor quotient 3 (since 15 = 4 × 3 + 3).

Q5Comparison

Check whether 25 is greater than 20.

Solution
Python
# Q5
print(25 > 20)
Output
True
Q6Logical operators

Evaluate (5 > 2) and (10 < 20).

Solution
Python
# Q6
print((5 > 2) and (10 < 20))
Output
True
Q7Indexing

For text = "Python", print the first, last, and third character.

Solution
Python
# Q7
text = "Python"
print(text[0])
print(text[-1])
print(text[2])
Output
P
n
t
Q8Slicing

Print "thon" from "Python" using slicing.

Solution
Python
# Q8
text = "Python"
print(text[2:])
Output
thon

text[2:] starts at index 2 ("t") and runs to the end.

Q9Length

Find the length of "Python".

Solution
Python
# Q9
text = "Python"
print(len(text))
Output
6
Q10Replication

Print "Hi" five times using string replication.

Solution
Python
# Q10
print("Hi" * 5)
Output
HiHiHiHiHi
Next · All partsWeek 1 Summary Sheet
08
All parts

Week 1 Summary Sheet

Everything from Week 1 on one sheet, for a last-minute revision.

Revision sheet

TopicKey point
PythonProgramming language
InterpreterExecutes Python code
IndentationDefines blocks
CommentsStart with #; not executed
print()Displays output
VariableStores 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 notLogical operations
+ on stringsConcatenation
text[i]Indexing
text[a:b]Slicing
len(text)String length
text * nString replication

Operators at a glance

KindOperatorsGives
Arithmetic+ - * / ** % //number (/ always a float)
Comparison== != > < >= <=bool
Logicaland or notbool
Strings+ * [ ] [a:b]string

Common mistakes

MistakeFix
if x = 5: (assignment instead of comparison)if x == 5:
age = input() then age + 1int(input())
"Age: " + 21"Age: " + str(21)
5 / 2 when you want 25 // 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 / falseTrue / False
10 < 9 vs "10" < "9"numbers and strings compare differently

Last-minute checklist

Make sure you can write and understand each of these:

  1. print() and input()
  2. Variable assignment and reassignment
  3. Variable naming rules
  4. str, int, float, bool, list
  5. type()
  6. Type casting with str(), int(), float(), bool()
  7. All seven arithmetic operators
  8. Operator precedence and parentheses
  9. Associativity: left to right, and ** / not right to left
  10. All six comparison operators
  11. and, or, not
  12. String concatenation
  13. String indexing, including negative indexing
  14. String slicing and the exclusive stop index
  15. len()
  16. String replication with *
  17. String comparison
  18. Python indentation and comments

Exam tips: last-minute checklist

Do
  • 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 with int() / float()
  • / gives a float; // rounds down; % follows //
  • Rank first, then left to right (** and not go right to left)
  • Count string indices from 0; the stop index is excluded
Do not
  • 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

QuestionAnswer
-7 // 2 and -7 % 2-4 and 1
2 ** 3 ** 2512
print("a", "b", sep="")ab
"Hello"[-3:]llo
type(10 / 2)float
"3" + "4""34"
Back to top