←
Class 11 Computer Science
5. Getting Started with Python · 5 / 11
⌕
Chapter 5 of 11

5. Getting Started with Python

16 sections · 8,153 words

About this chapter

213 words · 1 min read

Big idea: Python lets you write clear steps. The interpreter runs those steps one line at a time.

This is an original lesson that follows the Class 11 Computer Science syllabus. Read the key words first. Cover a worked answer and try the steps yourself before you look. For a program, say what it will print before you read the real output.

  • Run Python at a prompt and from a saved .py file.
  • Apply identifier rules and keep keywords as reserved words.
  • Use variables as names that point to objects.
  • Name built-in types and say which ones can change.
  • Build expressions with operators and follow precedence.
  • Use print() and input(), then convert types when needed.
  • Tell syntax errors, runtime errors, and logical errors apart.

Guido van Rossum began Python in December 1989. He wanted a scripting language that was easy to read and still able to talk to the system. He named it after a comedy group so the work would stay light. Python 1.0 appeared in 1994. Python 2.0 arrived in 2000. Python 3.0 launched in 2008 with a cleaner design and Unicode strings. A global community still maintains it. Students use it because the first programs stay short and the errors are readable.

5.1 Introduction to Python

804 words · 4 min read

A program is a list of steps for a computer. Python makes those steps easy to read.

A computer needs instructions. An ordered list of instructions is a program.

The language of those instructions is a programming language.

The processor runs machine language. That is only 0 and 1.

People do not write bits by hand. A high-level language uses words close to English.

Python is a high-level language. The text you type is source code.

The machine cannot read source code as-is. A translator is needed.

Python uses an interpreter. It translates and runs one line at a time.

You write source codeThe interpreter reads one lineIt translates that lineThe machine runs the lineThe next line is read
An interpreter works one line at a time.

How to read the figure. Start at the top. You write a line. The interpreter reads it. Then it translates. Then the machine runs it. Then the next line starts. A syntax error stops this chain.

The interpreter does not wait for the whole file before the first line can fail.

Line-by-line running helps beginners. You see an error near the line that caused it.

  • Program: an ordered set of instructions for a computer.
  • Source code: the high-level text a person writes.
  • Interpreter: a translator that runs code line by line.
  • Python shell: the window that shows the >>> prompt.

  • High-level: It hides bit-level machine detail.
  • Interpreted: Each statement can run at once.
  • Free and open source: You may study and share it.
  • Portable: The same .py file can run on many systems.
  • Case-sensitive: Score and score are different names.
  • Indented blocks: Spaces at the left group code.
  • Standard library: Ready tools for maths, text, and files.

You can run Python in two modes.

Interactive mode uses the >>> prompt. You type one statement. You press Enter. The result appears at once. Closing the window drops that work.

Script mode uses a text file. You save it with a .py name. The interpreter reads the file from top to bottom. You can edit it and run it again.

Interactive Result at onceNot savedScript .py fileWhole file runsSaved on disk
Two ways to run Python. Prompt for tests. File for saved programs.

How to read the figure. The left column is the prompt. It is fast. It is not saved. The right column is a file. Use a file when the program must last.

FeatureInteractive modeScript mode
PromptShows >>>Runs the file
When it runsEach line at onceWhole file in order
Saved?NoYes, as .py
Best forQuick testsA full program

How to read the table. Match the job to a column. One formula: left. A quiz for later: right.

Student A wants to test one maths line. Student B needs a quiz program for tomorrow. Which mode should each use?

Goal. Pick a mode for each job.

Rule. Use interactive mode for a short test. Use script mode for saved, multi-step work.

Steps. Student A has one expression. Interactive mode fits.

Steps. Student B must save, edit, and rerun. Script mode fits.

Result: Student A: interactive mode. Student B: script mode.

Here is a tiny script. Read it before you look at the printout.

Python
print("Welcome to Python!")
print("Learning to code is fun.")
steps = 3 + 4
print("Steps completed:", steps)

Output
Welcome to Python!
Learning to code is fun.
Steps completed: 7

Trace that program line by line. What prints, and what is stored?

Goal. Predict each printed line and the value of steps.

Rule. A print call writes text. Assignment stores a value. + adds numbers.

Line 1. print shows Welcome to Python!

Line 2. print shows Learning to code is fun.

Line 3. 3 + 4 is computed. steps is bound to 7.

Line 4. print shows Steps completed: then 7.

Check. Four actions. Two greetings, one store, one report.

Result: Three lines of text. The last number is 7.

Cover the answers. Try each item on paper first.

Watch out: Do not type Python at a normal system prompt. Start the interpreter so you see >>>.

⚡ Quick Check Flashcards4 questions
Question 1
What is source code?
Try answering before revealing!
Question 2
How does an interpreter run a program?
Try answering before revealing!
Question 3
What file ending marks a Python program?
Try answering before revealing!
Question 4
When is interactive mode the better choice?
Try answering before revealing!

5.2 Python keywords

466 words · 2 min read

Keywords are reserved words. Python already gave them a job.

Every language has fixed words. In Python those words are keywords.

A keyword sets grammar. It starts a loop, a test, or a definition.

You cannot use a keyword as a variable name. Python stops with a syntax error.

  • Keyword: a reserved word with a fixed meaning in Python.
  • Reserved word: a word kept for the language, not for your names.

Python is case-sensitive. Most keywords are all lower-case. Examples: if, while, def, class, import.

Exactly three keywords start with a capital: True, False, and None.

Wrong capitals change the meaning. IF is not if. true is not True.

GroupKeywordsJob
Truth and emptyTrue, False, NoneYes, no, and no value
Decisionsif, elif, elsePick a branch
Loopsfor, while, break, continueRepeat or leave a loop
Functionsdef, return, lambdaMake and leave a function
Modulesimport, from, asLoad extra tools
Logic and testsand, or, not, is, inCombine tests

How to read the table. The middle column is the reserved spelling. Copy it exactly.

The keyword module can list them. keyword.iskeyword() tests one word.

Python
import keyword

test_words = ["for", "while", "count", "True", "true", "score"]
for word in test_words:
    print(word, "is a keyword:", keyword.iskeyword(word))

Output
for is a keyword: True
while is a keyword: True
count is a keyword: False
True is a keyword: True
true is a keyword: False
score is a keyword: False

How to read the output. for, while, and True print True. count, true, and score print False.

true with a small t is not a keyword.

A keyword check saves time. Test a name before you build a long program on it.

Student A wants three names: pass, Pass, and total_marks. Which names are legal?

Goal. Mark each name legal or illegal.

Rule. A keyword cannot be a variable. Keywords are case-sensitive.

Steps. pass in lower case is a keyword. Illegal.

Steps. Pass starts with a capital. It is not the keyword pass. Legal.

Steps. total_marks is not a keyword. Legal.

Result: Illegal: pass. Legal: Pass and total_marks.

Pause here. Answer before you scroll to the answers.

Watch out: Keywords need the exact letters. true or While will not work as keywords.

⚡ Quick Check Flashcards4 questions
Question 1
Can you name a variable while?
Try answering before revealing!
Question 2
Which three keywords start with a capital letter?
Try answering before revealing!
Question 3
What happens if you write true with a small t?
Try answering before revealing!
Question 4
Which module tests whether a word is a keyword?
Try answering before revealing!

5.3 Identifiers

440 words · 2 min read

An identifier is a name you choose. It labels a variable, a function, or another item.

You must name things in a program. Any name you create is an identifier.

Python has strict name rules. A broken name stops the program before it runs.

  • Identifier: a name you create for a variable, function, or similar item.
  • Underscore: the _ character. It may start a name or join words.
  • Snake case: lower-case words joined by underscores.

  • Allowed: letters a–z and A–Z, digits 0–9, and _.
  • First character: a letter or _. Never start with a digit.
  • No spaces or marks: no hyphen, hash, or percent.
  • No keywords: the name must not be a reserved word.
  • Case matters: score, Score, and SCORE are three names.
  • Length: any length is allowed. Short, clear names are better.
NameStatusWhy
student_scoreValidLetters and one underscore
_bonusValidMay start with _
item2ValidA digit after the first character
2nd_placeInvalidStarts with a digit
item-costInvalidA hyphen is subtraction
total scoreInvalidA space is not allowed
classInvalidclass is a keyword

How to read the table. Valid names sit in the first three rows. The rest fail one rule each.

Python style uses snake_case. Example: bus_speed or total_items.

Python
student_score = 95
total_items = 12
_bonus = 5
final_result = student_score + _bonus
print("Items:", total_items)
print("Final result:", final_result)

Output
Items: 12
Final result: 100

How to read the output. Items is 12. Final result is 100. The names follow the rules.

A clear name is part of the program. Future you must still understand it.

Classify each name: room#3, _speed, 4runners, student_name, def.

Goal. Mark valid or invalid.

Rule. Use the identifier rules. Check the first character, extra marks, and keywords.

Steps. room#3 has #. Invalid.

Steps. _speed starts with _ and uses letters. Valid.

Steps. 4runners starts with a digit. Invalid.

Steps. student_name uses letters and _. Valid.

Steps. def is a keyword. Invalid.

Result: Valid: _speed, student_name. Invalid: room#3, 4runners, def.

Write a short answer. Then check the notes below.

Watch out: Do not put a space or a hyphen in a name. Use an underscore, as in bus_stop.

⚡ Quick Check Flashcards4 questions
Question 1
Can an identifier start with a digit?
Try answering before revealing!
Question 2
Why is total-marks invalid?
Try answering before revealing!
Question 3
Are score and Score the same variable?
Try answering before revealing!
Question 4
Is _counter a legal name?
Try answering before revealing!

5.4 Variables

655 words · 3 min read

A variable is a name that points to an object in memory.

A program must remember data. In Python, data lives as an object.

A variable is a label. It is a name tag, not a fixed empty box.

You create the link with assignment. The operator is =.

Right side first. Python computes the right side. Then it binds the left-hand name.

The right side is computedAn object is stored in memoryThe name on the left is bound
Assignment binds a name to an object.

How to read the figure. The arrow goes down. Compute. Store. Name. Never think the name is filled before the right side exists.

name: countObject in memoryid: addresstype: intvalue: 25
A variable is a name tag. It points to an object in memory.

How to read the figure. The left box is only a name. The right box is the object. The arrow is the reference.

  • Variable: a name that references an object in memory.
  • Assignment: binding a name to an object with =.
  • Dynamic typing: the type comes from the object, not from a declared name.
  • Rebinding: pointing the same name at a different object.

Python uses dynamic typing. You do not declare “this name is an integer”.

The name takes the type of the current object. Later you may bind a string to that name.

a = b = c = 0 gives three names to integer 0.

x, y = 10, 20 pairs x with 10 and y with 20.

Swap is then short: x, y = y, x. Python packs the right side first. Then it unpacks.

Python
num_boxes = 5
print("Initial boxes:", num_boxes)
num_boxes = num_boxes + 3
print("After adding:", num_boxes)

x, y = 10, 20
print("Before swap: x =", x, "y =", y)
x, y = y, x
print("After swap:  x =", x, "y =", y)

Output
Initial boxes: 5
After adding: 8
Before swap: x = 10 y = 20
After swap:  x = 20 y = 10

Trace this program. Report each printed line.

Goal. Predict output in order.

Rule. Assignment binds. print shows the current object. Swap unpacks the right side first.

Line 1. num_boxes points to 5.

Line 2. Prints Initial boxes: 5.

Line 3. 5 + 3 is 8. The name is rebound.

Line 4. Prints After adding: 8.

Lines 6–7. x is 10, y is 20. Prints Before swap: x = 10 y = 20.

Line 8. Right side is (20, 10). Then x is 20 and y is 10.

Line 9. Prints After swap: x = 20 y = 10.

Result: 5, then 8, then 10 with 20, then 20 with 10.

Rebinding one name does not rewrite the old object for other names.

Think “this name now points here”. Do not think “the box was overwritten in place” for numbers.

A program runs p = 4, then q = p + 3, then p = 10. What are p and q at the end?

Goal. Find the final values of p and q.

Rule. Each assignment binds a name. q keeps its own object.

Steps. p points to 4.

Steps. q gets 4 + 3 = 7.

Steps. p is rebound to 10. q is unchanged.

Result: p is 10. q is 7.

Say the result out loud. Then read the answers.

Watch out: A single = stores. A double == compares. Do not mix them.

⚡ Quick Check Flashcards4 questions
Question 1
What does = do in Python?
Try answering before revealing!
Question 2
What is dynamic typing?
Try answering before revealing!
Question 3
How do you swap x and y in one statement?
Try answering before revealing!
Question 4
If a = 5 and b = a, does a = 99 change b?
Try answering before revealing!

5.5 Comments

429 words · 2 min read

A comment is a note for people. The computer skips it.

You will read code more often than you write it. A comment explains intent.

The interpreter ignores comments. They do not print. They do not slow the run.

  • Comment: text in the file that Python does not execute.
  • Inline comment: a short note on the same line as code.
  • Docstring: a triple-quoted string that documents a module or function.

  • Single line: starts with #. The rest of that line is skipped.
  • Inline: after a statement, such as tax = 0.05 # rate.
  • Several lines: many # lines, or a triple-quoted string at the top of a module or function.
StyleExampleUse
Single line# Convert hoursExplain the next block
Inlineradius = 7 # metresName a unit or constant
Docstring"""Hours to minutes."""Document a whole part

How to read the table. Pick a style by size. One fact: inline. A whole file: docstring.

Good comments say why. Bad comments repeat the code. # add 1 above count += 1 wastes space.

Python
# Program to convert hours into total minutes
hours = 3  # number of hours to convert
minutes_per_hour = 60  # conversion factor

# Multiply hours by minutes per hour
total_minutes = hours * minutes_per_hour

print("Hours:", hours)
print("Total minutes:", total_minutes)

Output
Hours: 3
Total minutes: 180

How to read the output. Hours is 3. Total minutes is 180. Every # line was ignored.

A hash inside quotes is not a comment. It is character data.

Comments help the next reader. That reader may be you next month.

Look at print("Code # 1") # print the item code. Which # starts a comment?

Goal. Split string text from comment text.

Rule. Inside quotes, # is data. Outside quotes, # starts a comment.

Steps. "Code # 1" is a string. That # is printed.

Steps. The later # starts the inline comment.

Steps. print the item code is skipped.

Result: Only # print the item code is a comment. Code # 1 is printed.

Cover the answers. Try each item on paper first.

Watch out: A hash inside quotation marks is part of a string. print("# Hello") prints # Hello.

⚡ Quick Check Flashcards4 questions
Question 1
Which symbol starts a single-line comment?
Try answering before revealing!
Question 2
Does Python run comments?
Try answering before revealing!
Question 3
What is an inline comment?
Try answering before revealing!
Question 4
Why explain why, not what?
Try answering before revealing!

5.6 Everything is an object

448 words · 2 min read

Every value in Python is an object. An object has identity, type, and value.

A whole number is an object. A word is an object. A list is an object. A function is an object too.

Each object has three properties.

  • Identity: a unique integer for that object. Read it with id().
  • Type: the kind of data, such as int or str. Read it with type().
  • Value: the content, such as 42 or "apple".
name: countObject in memoryid: addresstype: intvalue: 25
A variable is a name tag. It points to an object in memory.

How to read the figure again. Identity is the address. Type is the class. Value is 25. The name only points.

  • Object: a stored entity with data and operations.
  • Identity: the unique id() integer while the object lives.
  • Type: the class that decides allowed operations.
  • Value: the data stored in the object.

type(42) is <class 'int'>. type("cat") is <class 'str'>.

id() stays the same for that object while it lives. Two names for one object share the same id.

Python
num1 = 300
num2 = num1
print("num1 type:", type(num1))
print("Same object id:", id(num1) == id(num2))

num1 = num1 + 1
print("After changing num1:")
print("Same object id now:", id(num1) == id(num2))
print("num1 value:", num1)
print("num2 value:", num2)

Output
num1 type: <class 'int'>
Same object id: True
After changing num1:
Same object id now: False
num1 value: 301
num2 value: 300

How to read the output. At first both names share one object, so Same object id is True. After num1 = num1 + 1, a new int is made. num1 is 301. num2 is still 300.

Equal values are not always the same object.

Integers are immutable. “Change” means “bind a new integer”, not “edit the old one”.

list_a = [10, 20] and list_b = [10, 20]. Is list_a == list_b true? Is list_a is list_b true?

Goal. Separate value equality from identity.

Rule. == tests value. is tests the same object.

Steps. Both lists hold 10 then 20. == is True.

Steps. Python made two list objects. Each has its own id.

Steps. is is False.

Result: == is True. is is False.

Pause here. Answer before you scroll to the answers.

Watch out: Two names can hold equal values and still point to two objects. Use == for value. Use is for identity.

⚡ Quick Check Flashcards4 questions
Question 1
Name the three properties of every object.
Try answering before revealing!
Question 2
Which function returns the memory id?
Try answering before revealing!
Question 3
What does type(3.14) show?
Try answering before revealing!
Question 4
If a name is rebound, does its id stay the same?
Try answering before revealing!

5.7 Python data types

664 words · 3 min read

A data type names the kind of value. It also names the allowed operations.

Every value has a data type. The type decides what you may do.

You can multiply two numbers. You cannot divide a sentence by a number.

Python groups types into numbers, sequences, sets, mappings, and None.

  • Data type: the class of value an object holds.
  • Mutable: contents may change in place.
  • Immutable: contents cannot change after creation.
  • Sequence: an ordered collection with integer positions.
  • Mapping: a collection looked up by a key.

  • Numbers: int, float, complex, bool.
  • Sequences: str, list, tuple. Order matters.
  • Sets: set. Each value appears once.
  • None: only None, type NoneType. It means “no value”.
  • Mapping: dict. Look up a value by a key.
Immutableint, float, boolstr, tuple, NoneMutablelist, dict, setchange without new idPick the family before you write code.
Immutable objects keep their contents. Mutable objects can change in place.

How to read the figure. Left types stay as they are. Right types can grow, shrink, or replace an item and keep the same id.

Data typeExampleMutable?Use
int42, -15NoWhole numbers
float3.14, -0.5NoNumbers with a fraction
boolTrue, FalseNoYes or no
str"hello"NoText
list[10, 20, 30]YesAn ordered list that will change
tuple(10, 20, 30)NoA fixed ordered group
set{10, 20, 30}YesUnique values
dict{'a': 1}YesA key to a value
NoneNoneNoMissing data

How to read the table. Scan Mutable? first. Then pick a type that matches the job.

  • Use a list when the collection will change.
  • Use a tuple when the group must stay fixed, such as a point (x, y).
  • Use a set when duplicates must disappear.
  • Use a dict when you look up by a name or key.
Python
scores_list = [85, 90, 95]
print("Original list:", scores_list)
scores_list[1] = 92
print("Updated list: ", scores_list)

text_greeting = "Hello"
print("String greeting:", text_greeting)
print("New string formed:", "h" + text_greeting[1:])

point_tuple = (10, 20)
print("Tuple coordinate:", point_tuple)

student_record = {"id": "S101", "grade": 11}
student_record["grade"] = 12
print("Updated dictionary:", student_record)

colors = {"red", "green", "blue", "red"}
print("Unique set elements:", sorted(colors))

Output
Original list: [85, 90, 95]
Updated list:  [85, 92, 95]
String greeting: Hello
New string formed: hello
Tuple coordinate: (10, 20)
Updated dictionary: {'id': 'S101', 'grade': 12}
Unique set elements: ['blue', 'green', 'red']

How to read the output. The list index 1 changes 90 to 92. The string is not edited in place; a new string is built. The tuple stays (10, 20). The dict grade becomes 12. The set drops the extra red.

==s[0] = "b" on a string raises TypeError.== Strings are immutable.

Mutability is an exam favourite. Name the type, then say if it can change in place.

A record stores a name, a roll number, a list of sports, and a fixed admission year. Pick a type for each.

Goal. Match each field to a type.

Rule. Text is str. A changing list is list. A fixed whole number is int.

Steps. Name: str.

Steps. Roll number: int (or str if it must keep leading zeros).

Steps. Sports that come and go: list.

Steps. Admission year: int. It does not change.

Result: str, int, list, int.

Write a short answer. Then check the notes below.

Watch out: Strings and tuples cannot take item assignment. word[0] = "B" and tup[1] = 99 both fail.

⚡ Quick Check Flashcards5 questions
Question 1
Which built-in collections are mutable?
Try answering before revealing!
Question 2
Can a set hold the same value twice?
Try answering before revealing!
Question 3
What error comes from changing a tuple item?
Try answering before revealing!
Question 4
What is type(None)?
Try answering before revealing!
Question 5
When is a dict better than a list?
Try answering before revealing!

5.8 Operators

660 words · 3 min read

An operator is a symbol that computes or compares. The values it uses are operands.

In 17 + 5, + is the operator. 17 and 5 are operands.

Python has arithmetic, relational, assignment, logical, identity, and membership operators.

  • Operator: a symbol that computes or compares.
  • Operand: a value the operator uses.
  • Floor division: division that rounds down to the next lower integer.
  • Modulus: the remainder after integer division.
  • Short-circuit: stop a logical test as soon as the result is known.

OperatorNameExampleResult
+Addition17 + 522
-Subtraction17 - 512
*Multiplication17 * 585
/True division17 / 53.4 (always float)
//Floor division17 // 53 (rounds down)
%Modulus17 % 52
**Power5 ** 3125

How to read the table. / keeps a decimal. // drops toward minus infinity. % is the leftover.

  • True division / always returns a float. 8 / 2 prints 4.0.
  • Floor division rounds down. 17 // 5 is 3. -17 // 5 is -4.

Relational operators give True or False. They are ==, !=, >, <, >=, <=.

Augmented assignment folds maths into =. count += 4 means count = count + 4. Also -=, =, /=, //=, %=, *=.

Logical operators: and needs both True. or needs one True. not flips truth.

Python uses short-circuit evaluation. False and expr stops. True or expr stops.

  • is is True when both names point to the same object. is not is the reverse.
  • in is True when an item sits in a sequence. not in is the reverse.
Python
a, b = 17, 5
print("True division: ", a / b)
print("Floor division:", a // b)
print("Modulus:       ", a % b)
print("Power:         ", b ** 3)

count = 10
count += 4
print("After += 4:    ", count)
count //= 3
print("After //= 3:   ", count)

x, y = 15, 20
print("x < y and y > 10:", x < y and y > 10)
print("x == y or x < 20:", x == y or x < 20)
print("not (x > y):     ", not (x > y))

list1 = [1, 2]
list2 = [1, 2]
print("list1 == list2:  ", list1 == list2)
print("list1 is list2:  ", list1 is list2)

Output
True division:  3.4
Floor division: 3
Modulus:        2
Power:          125
After += 4:     14
After //= 3:    4
x < y and y > 10: True
x == y or x < 20: True
not (x > y):      True
list1 == list2:   True
list1 is list2:   False

How to read the output. Division lines match the table. count becomes 14, then 4. The and/or/not lines are True. The two lists are equal in value, not in identity.

Short-circuit is not a trick. It is a safety rule. A later divide-by-zero may never run.

Evaluate 25 // 4, 25 % 4, and -25 // 4.

Goal. Find three integer results.

Rule. // rounds down. % is the remainder. Remainder fits n = (n // d) * d + (n % d).

Steps. 25 / 4 is 6.25. Floor is 6.

Steps. Remainder: 25 − (6 × 4) = 1.

Steps. -25 / 4 is -6.25. The next lower integer is -7.

Result: 6, 1, and -7.

Say the result out loud. Then read the answers.

Watch out: 10 / 2 is 5.0, not 5. Use // when you need an integer quotient.

⚡ Quick Check Flashcards5 questions
Question 1
How do / and // differ?
Try answering before revealing!
Question 2
What is 14 % 4?
Try answering before revealing!
Question 3
If total = 12, what is total after total += 5?
Try answering before revealing!
Question 4
How does or short-circuit?
Try answering before revealing!
Question 5
How do == and is differ?
Try answering before revealing!

5.9 Expressions and operator precedence

608 words · 3 min read

An expression mixes values and operators. It computes one value. Precedence decides the order.

An expression is a legal mix of values, names, and operators. It has one result.

15 is an expression. 3 * 4 + 2 is an expression too.

Operator precedence says which operator runs first. Higher rank runs sooner.

  • Expression: operands and operators that compute one value.
  • Operator precedence: the rank that picks the first operator.
  • Associativity: left-to-right or right-to-left among equal ranks.

RankOperatorsAssociativity
1 (highest)Parentheses: ()Left to right
2Power: **Right to left
3Unary +x, -xRight to left
4*, /, //, %Left to right
5+ and -Left to right
6==, !=, <, <=, >, >=Left to right
7is, inLeft to right
8notRight to left
9andLeft to right
10orLeft to right
11 (lowest)= , +=, -=, …Right to left

How to read the table. Start at rank 1. Do those operators first. Then move down. Equal rank uses the last column.

Most binary operators go left to right. ** is the exception. It goes right to left.

So 2 3 2 is 2 (3 2) = 512. Grouped the other way, (2 3) 2 = 64.

When you are unsure, add parentheses. They show your plan. They also override rank.

Python
result = 8 + 6 * 2 ** 3 // 4 - 5
print("Computed result:", result)

chain1 = 20 // 4 // 2
print("Left-to-right //:", chain1)

power_chain = 2 ** 3 ** 2
print("Right-to-left **:", power_chain)

Output
Computed result: 15
Left-to-right //: 2
Right-to-left **: 512

How to read the output. First result is 15. Floor chain is 2. Power chain is 512.

Parentheses are the safest rank. Use them in exam work if the order is not obvious.

A wrong rank is a silent logic error. The program still runs. The number is wrong.

Evaluate 10 + 4 3 * 2 // 6 - 7 with every step.

Goal. Find the single integer result.

Rule. Use the rank table. Power first. Then * and // left to right. Then + and - left to right.

Step 1. Power: 3 ** 2 = 9. Now 10 + 4 * 9 // 6 - 7.

Step 2. Multiply: 4 * 9 = 36. Now 10 + 36 // 6 - 7.

Step 3. Floor divide: 36 // 6 = 6. Now 10 + 6 - 7.

Step 4. Add: 10 + 6 = 16. Now 16 - 7.

Step 5. Subtract: 16 - 7 = 9.

Result: The expression equals 9.

Predict the three printed numbers from the program above, without looking back.

Goal. Name the three print results.

Rule. Same rank table. // is left to right. ** is right to left.

First. 2 ** 3 = 8, then 6 * 8 = 48, then 48 // 4 = 12, then 8 + 12 - 5 = 15.

Second. (20 // 4) // 2 = 5 // 2 = 2.

Third. 3 2 = 9, then 2 9 = 512.

Result: 15, then 2, then 512.

Cover the answers. Try each item on paper first.

Watch out: 2 2 3 is 2 8 = 256, not (2 2) ** 3 = 64. Power groups from the right.

⚡ Quick Check Flashcards4 questions
Question 1
Which is higher, * or +?
Try answering before revealing!
Question 2
Which way does ** run?
Try answering before revealing!
Question 3
What is 16 // 4 // 2?
Try answering before revealing!
Question 4
How do you add before you multiply?
Try answering before revealing!

5.10 Statements

460 words · 2 min read

A statement is a full instruction. The interpreter can run it as an action.

An expression yields a value. A statement does a job.

x = 5 is an assignment statement. print("Hello") is a call statement.

You cannot assign an assignment. a = (b = 5) is invalid in Python.

  • Statement: a complete instruction Python can run.
  • Simple statement: one logical line.
  • Compound statement: a header with a colon, then an indented body.
  • Indentation: leading spaces that mark a block.

A simple statement fits on one line. Assignment, print(...), import, and pass are simple.

A compound statement has a header that ends with :. The next lines are indented. That group is a suite. if, for, and def are compound.

A header line ends with a colonIndented lines form the suiteA less-indented line ends the block
Python groups code by spaces, not by braces.

How to read the figure. Colon. Then spaces. Then a later line with fewer spaces ends the block. Braces are not used.

You may put simple statements on one line with ;. Example: x = 1; y = 2. Clear separate lines are better.

A long statement may wrap inside parentheses. A backslash at the line end also continues a line.

Python
score = 82
message = "Pass"

if score >= 50:
    status = "Qualified"
    print("Status:", status)

total_points = (
    10 + 20 +
    30 + 40
)
print("Total points:", total_points)

Output
Status: Qualified
Total points: 100

How to read the output. The if suite runs because 82 >= 50. Status is Qualified. Total points is 100. message is stored but never printed.

Spaces are grammar in Python, not decoration.

Mix tabs and spaces and you get errors that are hard to see. Pick spaces and stay with them.

Why is x = 5 a statement, while x + 5 is an expression?

Goal. Name each kind.

Rule. An expression computes a value. A statement performs an action.

Steps. x + 5 computes a number. Expression.

Steps. x = 5 binds a name. It is not a value you can print as the assignment itself. Statement.

Result: x + 5 is an expression. x = 5 is a statement.

Pause here. Answer before you scroll to the answers.

Watch out: Do not write print(x = 5). That assignment is not a value for print.

⚡ Quick Check Flashcards4 questions
Question 1
How does an expression differ from a statement?
Try answering before revealing!
Question 2
How does Python know which lines sit inside if?
Try answering before revealing!
Question 3
What character ends a compound header?
Try answering before revealing!
Question 4
What is pass for?
Try answering before revealing!

5.11 Input and output

444 words · 2 min read

input() reads from the user. print() writes to the screen.

A useful program talks to a person. Data in is standard input. Text out is standard output.

Input: input() reads a stringProcess: convert and computeOutput: print() shows the result
Most first programs follow input, process, output.

How to read the figure. Top is input. Middle is process. Bottom is output. Skip convert in the middle and the types clash.

  • Standard input: data typed in, usually from the keyboard.
  • Standard output: the text the program prints.
  • sep: the string print() puts between items.
  • end: the string print() puts after the last item.

print() turns values into text and shows them. Comma items get a space by default. A newline follows.

  • sep: the gap between items. sep="-" puts a hyphen between them.
  • end: the ending. end=" " keeps the next print on the same line.

input() waits. The user types. Enter ends the line. You may pass a prompt: name = input("Enter name: ").

input() always returns a string. Type 25 and you still get "25".

Need a number? Convert with int() or float() first.

Python
print("Shelfmark", "Learning", "Python", sep="-")
print("Line", 1, sep=" : ", end=" *** ")
print("Line", 2, sep=" : ")

# Simulating user input conversion
user_text = "15"  # simulated string from input()
quantity = int(user_text)
unit_cost = 4
total_cost = quantity * unit_cost
print("Quantity:", quantity)
print("Total cost:", total_cost)

Output
Shelfmark-Learning-Python
Line : 1 *** Line : 2
Quantity: 15
Total cost: 60

How to read the output. First line uses hyphens. Line 1 stays on the same row as Line 2 because end is not a plain newline. Quantity is 15. Total cost is 60.

"15" * 3 is 151515, not 45. Convert before you do arithmetic.

Always convert input before maths. That one habit removes a whole class of TypeError.

n = input("Enter number: ") gets 5. Then print(n * 3) runs. What prints, and why?

Goal. Predict the printed text.

Rule. input() returns str. str times int repeats the text.

Steps. n is the string "5", not the integer 5.

Steps. "5" * 3 is "555".

Check. int(n) * 3 would be 15.

Result: 555 prints. Use int(n) * 3 to get 15.

Write a short answer. Then check the notes below.

Watch out: Adding a number to input() without int() or float() raises TypeError.

⚡ Quick Check Flashcards4 questions
Question 1
What type does input() return?
Try answering before revealing!
Question 2
How do you print three values with comma gaps?
Try answering before revealing!
Question 3
How do you stop print() from starting a new line?
Try answering before revealing!
Question 4
How do you turn typed digits into an integer?
Try answering before revealing!

5.12 Type conversion

520 words · 2 min read

Type conversion changes a value from one type to another so an operation can run.

Data often arrives as text. Maths needs a number. Changing the type is type conversion.

  • Type conversion: changing a value from one type to another.
  • Implicit conversion: Python changes the type by itself.
  • Explicit conversion: you call a function such as int().
  • Type casting: another name for explicit conversion.
  • Truthy and falsy: values that count as True or False in a test.

Implicit conversion happens when number types mix. Python promotes to the wider type so data is not lost.

In 8 + 2.5, integer 8 becomes 8.0. The sum is 10.5, type float.

Python will not mix str and int with +. "Score: " + 95 is TypeError. Call str(95) first.

Explicit conversion is a function you call.

FunctionBecomesExampleResult
int(x)Integerint(7.9)7 (fraction dropped)
int(x)Integerint("45")45
float(x)Floatfloat(12)12.0
float(x)Floatfloat("3.14")3.14
str(x)Stringstr(250)"250"
bool(x)Booleanbool(0)False
bool(x)Booleanbool(15)True
list(x)Listlist("cat")['c', 'a', 't']
tuple(x)Tupletuple([1, 2])(1, 2)

How to read the table. int() on a float chops toward zero. int() on "3.14" is not in the table on purpose. That call fails.

Some values are falsy: 0, 0.0, "", [], (), {}, None. bool() is False. Other values are truthy.

Python
int_val = 8
float_val = 2.5
combined = int_val + float_val
print("Combined value:", combined)
print("Combined type: ", type(combined))

num_str = "120"
converted_int = int(num_str)
print("Converted int + 5:", converted_int + 5)

float_str = "14.75"
converted_float = float(float_str)
print("Float value:    ", converted_float)
print("Truncated int:  ", int(converted_float))

print("bool(0):   ", bool(0))
print("bool(''):  ", bool(""))
print("bool([]):  ", bool([]))
print("bool(42):  ", bool(42))
print("bool('cat'):", bool("cat"))

Output
Combined value: 10.5
Combined type:  <class 'float'>
Converted int + 5: 125
Float value:     14.75
Truncated int:   14
bool(0):    False
bool(''):   False
bool([]):   False
bool(42):   True
bool('cat'): True

How to read the output. Combined is 10.5 and class float. "120" becomes 120, then 125. 14.75 truncates to 14. Empty values are False. 42 and cat are True.

int("3.14") fails. Convert to float first, then to int, if that is the plan.

What happens with int("3.14")? How can you reach the integer 3 safely?

Goal. Name the error, then a safe path.

Rule. int() on a string needs a whole-number digit string. A point is not allowed.

Steps. int("3.14") raises ValueError.

Steps. float("3.14") gives 3.14.

Steps. int(3.14) truncates to 3.

Steps. Together: int(float("3.14")).

Result: ValueError from int("3.14"). Use int(float("3.14")) to get 3.

Say the result out loud. Then read the answers.

Watch out: int("4.5") raises ValueError. Convert a decimal string with float() first.

⚡ Quick Check Flashcards4 questions
Question 1
How do implicit and explicit conversion differ?
Try answering before revealing!
Question 2
What is int(9.99)?
Try answering before revealing!
Question 3
Which function makes an integer into text?
Try answering before revealing!
Question 4
Name two falsy values.
Try answering before revealing!

5.13 Debugging and types of errors

638 words · 3 min read

Debugging means find the fault, name it, and fix it.

A fault in a program is a bug. Finding and removing it is debugging.

Python faults fall into three groups.

Syntax: grammar break. No run.Runtime: crash on a running line.Logic: runs, but the answer is wrong.Name the type before you try to fix it.
Three error types. Syntax, runtime, and logic are not the same.

How to read the figure. Top: the file is not legal. Middle: a line crashes while running. Bottom: the program finishes, but the number is wrong.

  • Bug: a fault that crashes a program or gives a wrong answer.
  • Debugging: finding, naming, and fixing bugs.
  • Syntax error: broken Python grammar.
  • Runtime error: a crash on a legal line while it runs.
  • Logical error: wrong reasoning; the program still finishes.
  • Traceback: the report with file, line, and error name.

  • Syntax errors: missing colon, bad brackets, or a mistyped keyword. Python stops before any line runs.
  • Runtime errors: the grammar is fine. An impossible act happens, such as 10 / 0 (ZeroDivisionError) or a missing name (NameError).
  • Logical errors: no crash. The formula or the steps are wrong.
TypeWhenDoes it run?Example
SyntaxBefore runNoif x == 5 (no colon)
RuntimeOn a lineStops there10 / 0
LogicalNever by PythonYes, to the endavg = a + b / 2

How to read the table. Ask two questions. Did it start? Did it finish with the right answer? That pair names the type.

1 Write2 Run3 CheckFix?No error? Stop. Error? Fix and test again.
The debug cycle. Write, run, check, then fix if needed.

How to read the figure. After Check, either stop or loop back through Fix to Write.

  • Read the traceback from the bottom. The last line names the error.
  • Open the given line. If it looks fine, check the line above.
  • Print mid values. See what a name actually holds.
  • Trace a tiny example on paper. Use numbers you can check by hand.
Python
numerator = 50
denominator = 0

try:
    quotient = numerator / denominator
except ZeroDivisionError as err:
    print("Caught runtime error:", type(err).__name__)

num_a = 10
num_b = 20

# Buggy formula (logical error): division before addition
buggy_avg = num_a + num_b / 2
print("Buggy average:  ", buggy_avg)

# Corrected formula using parentheses
correct_avg = (num_a + num_b) / 2
print("Correct average:", correct_avg)

Output
Caught runtime error: ZeroDivisionError
Buggy average:   20.0
Correct average: 15.0

How to read the output. The try block catches ZeroDivisionError. That is runtime. Buggy average is 20 because / beats +. Correct average is 15. That gap is a logical error.

A quiet wrong answer is still a bug.

Name the error type in the exam sentence. “It is wrong” is not enough. Say syntax, runtime, or logic.

A student writes print("Total score =", score with no closing parenthesis. What error type is that?

Goal. Name the error type.

Rule. Broken grammar that Python sees before running is a syntax error.

Steps. The ( after print has no matching ).

Steps. That breaks the grammar.

Steps. No line runs.

Result: Syntax error. The parenthesis is not closed.

Cover the answers. Try each item on paper first.

Watch out: A program that finishes can still be wrong. A logical error prints a quiet bad answer.

⚡ Quick Check Flashcards4 questions
Question 1
How does a syntax error differ from a runtime error?
Try answering before revealing!
Question 2
Why are logical errors hard?
Try answering before revealing!
Question 3
What runtime error is 1 / 0?
Try answering before revealing!
Question 4
What does a traceback tell you?
Try answering before revealing!

Summary

178 words · 1 min read
  • Python is high-level and interpreted. Blocks are made with indentation.
  • Interactive mode uses >>>. Script mode runs a saved .py file.
  • Keywords are reserved. You cannot use them as names.
  • Identifiers start with a letter or _. They hold no spaces or extra marks.
  • A variable is a name that points to an object. = binds. Types can change.
  • Comments start with #. Python skips them.
  • Every object has id(), type(), and a value.
  • Types include numbers, str, list, tuple, set, dict, and None.
  • list, dict, and set can change in place. int, str, and tuple cannot.
  • Operators do arithmetic, tests, assignment, logic, identity, and membership.
  • An expression has one value. ** groups from the right.
  • A statement does an action. A compound header ends with a colon.
  • print() writes with sep and end. input() always returns a string.
  • Conversion may be implicit between numbers, or explicit with int() and friends.
  • Syntax stops before run. Runtime crashes on a line. Logic finishes with a wrong answer.
Explain each important word in your own words. Then say why the rule works.

Exercises

526 words · 2 min read

These questions are new. Show your thinking. For programs, write your answer before you run the code.

5.1 Which names are invalid, and why: total_cost, 2nd_score, class, item-count, _temp, score%?

5.2 What is the output of this Python program?

Python
x = 12
y = 25
x, y = y, x + 5
print(x, y)

5.3 Which type fits each item: a) days in a week, b) a student name, c) exam passed or not, d) a book price, e) a fixed (latitude, longitude) pair?

5.4 Evaluate 29 // 4, 29 % 4, -29 // 4, and -29 % 4.

5.5 Predict the output of this Python program.

Python
print(2 ** 2 ** 3)
print((2 ** 2) ** 3)

5.6 Trace the value of val after this program runs. What is printed?

Python
val = 20
val += 6
val //= 4
val **= 2
print(val)

5.7 What does (15 > 10) and not (7 == 8) evaluate to?

5.8 What happens with False and (100 / 0 > 1) and with True or (100 / 0 > 1)?

5.9 Why does nums = [1, 2, 3]; nums[0] = 9 work, while text = "cat"; text[0] = "r" raises TypeError?

5.10 What is printed by this program?

Python
a = [5, 10]
b = [5, 10]
print(a == b)
print(a is b)

5.11 What is the exact output of this print call?

Python
print("Bus", "Train", sep=" -> ", end=" ***\n")

5.12 Predict the output of this print call.

Python
print(int(7.85), int("50"), float("12.5"), bool([]), bool(10))

5.13 Name the error type: a) missing closing quote in "hello, b) divide by zero, c) rectangle area as length + width.

5.14 Write an expression that is True when t is between 20 and 30 inclusive.

5.15 What is the value of "py" * 3 + "3"?

5.16 Find simple interest for P = 2000, R = 5, T = 3 using SI = (P R T) / 100.

Answers

  1. 5.1: Invalid: 2nd_score (digit first), class (keyword), item-count (hyphen), score% (percent). Valid: total_cost, _temp.
  2. 5.2: prints 25 17. The right side is packed first as (25, 17), then unpacked into x and y.
  3. 5.3: a) int, b) str, c) bool, d) float, e) tuple.
  4. 5.4: 29 // 4 = 7, 29 % 4 = 1, -29 // 4 = -8, -29 % 4 = 3.
  5. 5.5: prints 256, then 64. Powers group from the right unless parentheses force the left group.
  6. 5.6: prints 36. val becomes 26, then 6, then 36.
  7. 5.7: True. 15 > 10 is True. 7 == 8 is False, so not False is True. True and True is True.
  8. 5.8: Both are safe. Short-circuit: False and stops at False. True or stops at True. The divide never runs.
  9. 5.9: A list is mutable, so an item can change in place. A string is immutable, so an item cannot change.
  10. 5.10: prints True, then False. The lists have the same values, but they are two objects.
  11. 5.11: prints Bus -> Train *** on one line.
  12. 5.12: prints 7 50 12.5 False True.
  13. 5.13: a) syntax, b) runtime (ZeroDivisionError), c) logic (wrong formula).
  14. 5.14: 20 <= t <= 30 (or t >= 20 and t <= 30).
  15. 5.15: pypypy3. "py" repeats three times, then "3" is joined.
  16. 5.16: 300. True division makes a float: (2000 5 3) / 100 = 30000 / 100 = 300.
Up next
Continue to the next chapter