Install Python and run programs from the terminal and from VS Code
Store and combine data using numbers, strings, booleans and None
Make programs decide with if, elif and else
Repeat work with for and while loops without creating infinite loops
Organise data in lists, tuples, dictionaries and sets and pick the right one
Write reusable functions with parameters, defaults and return values
Read and write text files and handle errors with try and except
Use the standard library, install packages with pip and isolate projects with virtual environments
Before you start
A laptop or desktop with Windows, macOS or Linux
About 30 to 45 minutes a day
No prior programming, and no maths beyond school arithmetic
Anyone who has never programmed, or who has tried before and got stuck on the basics.
This level assumes you have never written code. You will start by installing Python and printing your first line, then build up one idea at a time: values, text, decisions, repetition, collections, functions, files and errors. Every idea is explained in plain language, shown with code you can run, and checked with a short exercise and quiz.
Read each module in order. Type the examples yourself instead of pasting them. Typing slowly is how your fingers and eyes learn Python's shape, and the mistakes you make are where most of the learning happens.
Module 1
Setup and your first program
Install Python, run code two different ways, and learn to read an error message without panic.
About 45 minutes
Python is a programming language: a way of writing instructions that a computer can follow. It is popular because it reads almost like English, it has a huge collection of ready-made tools, and it is used for websites, data analysis, automation and AI. When you write Python you are writing plain text in a file. A program called the interpreter reads that text from top to bottom and does what each line says.
Installing Python
Download the latest Python 3 from python.org/downloads. Avoid Python 2; it is retired and many tutorials that use it will not run on a modern machine. The steps differ slightly by system.
System
How to install
Command to use
Windows
Run the installer from python.org. Tick 'Add python.exe to PATH' on the first screen, then choose Install Now.
python or py
macOS
Use the installer from python.org, or run brew install python if you use Homebrew.
python3
Linux
Most distributions include it. If not: sudo apt install python3 python3-pip python3-venv on Ubuntu or Debian.
python3
Open a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux) and check that the install worked. The exact version number on your machine will be different from the example below, and that is fine as long as it starts with 3.
terminal
python --version
# macOS and Linux users type: python3 --version
$ python terminal
Your number will differ. Any 3.10 or newer is fine for this course.
Two ways to run Python
The REPL (read, evaluate, print, loop) is an interactive prompt. Type python in the terminal and you will see >>>. Each line you type runs immediately. It is perfect for experiments and quick maths. Leave it with exit().
A script is a file that ends in .py. You save your instructions there and run the whole file with python filename.py. Scripts are how you build real programs because you can save, edit, share and rerun them.
You can write Python in Notepad, but a code editor makes life much easier. Visual Studio Code (VS Code) is free and a good choice. Install it, then add the Python extension by Microsoft from the Extensions panel. Create a folder called ciphercode-python, open it in VS Code with File, Open Folder, and create a new file named hello.py. Press the play button at the top right to run it, or use the terminal inside VS Code with python hello.py.
Your first program
The traditional first program shows a message. In Python that is one line. Read it piece by piece: print is a function, a named action that Python already knows. The round brackets hold what you hand to the function, called the argument. The text in quotes is a string, which is how Python represents words and sentences.
hello.py
print("Hello, CipherCode!")
$ python hello.py
Line by line: Python reads print(...), evaluates the string inside, and the print function writes it to the screen followed by a new line.
print can take several values separated by commas. It puts a space between them. You can also change what goes between values with sep and what goes at the end with end.
print_tricks.py
print("Chai", "costs", 15, "rupees") # values joined by a space
print("Chai", "Coffee", "Tea", sep=" | ") # custom separator
print("Loading", end="...") # no new line afterwards
print("done") # continues on the same line
print() # an empty line
print("Single quotes work too: 'yes'")
print('And "double" quotes inside single ones')
$ python print_tricks.py
Comments
A line that starts with # is a comment. Python ignores it completely. Comments are notes to humans: why the code exists, what a tricky part does, or what you plan to do next. Good comments explain why, not just what. Write comments for the person who will read your code in six months, which is usually you.
comments.py
# This whole line is a comment and does nothing.
print("Step 1") # a comment can also sit at the end of a line
# print("This line is switched off, so it never runs")
print("Step 2")
$ python comments.py
Commenting out a line is a handy way to switch code off temporarily while you debug.
Reading error messages
You will see errors every day as a programmer, so learn to read them calmly. An error is Python telling you exactly what it could not understand. Read it from the bottom up: the last line names the kind of error and gives a reason, and the lines above show where it happened.
broken.py
print("Hello"
print("World")
$ python broken.py
The first line was never closed with a bracket. The message says so directly. Python 3.10 and newer give this friendly wording.
Error
What it means
Typical cause
SyntaxError
Python cannot understand how the line is written
Missing bracket or quote, a missing colon
NameError
You used a name Python does not know
A typo in a name, or using a variable before creating it
IndentationError
Spaces at the start of a line are wrong
Mixed tabs and spaces, or an unexpected indent
TypeError
A value is the wrong kind for the action
Adding a number to text
name_error.py
print(mesage) # typo: the name 'message' was never created
$ python name_error.py
Fix: spell the name the way you created it. Python is case-sensitive, so Name and name are different.
You now have everything needed to move forward: Python installed, an editor, two ways to run code, and a method for reading errors. The next module introduces variables, which let your programs remember things.
Remember this
Python is run by an interpreter that reads your .py file from top to bottom.
Use the REPL for quick experiments and scripts for real programs.
print() shows values; sep and end change how it formats them.
Comments start with # and are ignored by Python.
Read errors from the bottom line up: it names the problem.
Your turn
Write a program that prints three lines: your name, your city, and your favourite programming goal. Then print all three on one line separated by ' - ' using a single print call. Add a comment above each print.
Use three print calls first. For the single line, give print three values and set sep=' - '.
solution.py
# Three separate lines
print("Bilwanth")
print("Vijayawada")
print("Build my own app")
# The same three values on one line
print("Bilwanth", "Vijayawada", "Build my own app", sep=" - ")
$ python solution.py
Check yourself
Which command checks the installed Python version?
The --version flag prints the version and exits. On macOS and Linux you usually type python3 --version.
What does Python do with a line starting with #?
A # starts a comment. Python skips everything after it on that line.
You see 'NameError: name total is not defined'. What is the most likely cause?
NameError means Python does not know that name. Check spelling and make sure the variable is created before it is used.
Ask the CipherCode AI tutor
I am a complete beginner learning Python. Explain how the interpreter runs a .py file, then give me five tiny exercises using print, sep, end and comments. After I answer, review my code and explain any errors in plain language.
Give values names, understand the basic data types, do arithmetic, and read input from a user.
About 55 minutes
A program is mostly about handling data: prices, names, marks, scores. To work with data you need a way to remember it. A variable is a name that points to a value stored in the computer's memory. You create one with the = sign, which in Python means assign, not 'equals'. Read price = 15 as 'let the name price refer to the value 15'.
variables.py
price = 15 # create the name 'price' and attach it to 15
quantity = 4
total = price * quantity # the right side is worked out first, then labelled 'total'
print(total)
price = 20 # move the label to a new value
print(price)
print(total) # total is still 60: it was calculated earlier
count = 1
count = count + 1 # read as: take count, add 1, store the result back
print(count)
$ python variables.py
Line by line: Python evaluates whatever is on the right of =, then attaches the name on the left to the result. That is why count = count + 1 makes sense in code even though it is nonsense in algebra.
Naming rules and style
Names can contain letters, digits and underscores, but cannot start with a digit: score1 is fine, 1score is a SyntaxError.
Names are case-sensitive: Marks and marks are two different names.
You cannot use Python's reserved words such as if, for, class, True or None.
The Python style is snake_case: lowercase words joined by underscores, like total_price.
Choose names that say what the value is: cups_sold beats x.
The basic types
Every value has a type that decides what you can do with it. You can ask Python with the built-in type() function. These five are the foundation.
Type
Meaning
Examples
int
Whole numbers, any size
7, -3, 1_000_000
float
Numbers with a decimal point
3.14, -0.5, 2.0
str
Text, in quotes
"chai", '42'
bool
Truth values, exactly two
True, False
NoneType
'Nothing here yet', the single value None
None
types.py
age = 19
height = 1.72
name = "Asha"
is_student = True
nickname = None # we do not know it yet
print(type(age))
print(type(height))
print(type(name))
print(type(is_student))
print(type(nickname))
print(type("42")) # quotes make it text, even though it looks like a number
$ python types.py
Arithmetic operators
Operators are symbols that combine values. Besides the usual + - * /, Python has three that beginners should learn early: // (floor division, which drops the fraction), % (remainder, also called modulo) and ** (power). Note that / always returns a float, even when the answer is whole.
operators.py
print(7 + 2) # 9
print(7 - 2) # 5
print(7 * 2) # 14
print(7 / 2) # 3.5 true division always gives a float
print(8 / 2) # 4.0 still a float
print(7 // 2) # 3 floor division: how many whole times 2 fits in 7
print(7 % 2) # 1 remainder after dividing
print(2 ** 10) # 1024 two to the power ten
# Brackets change the order, just like in maths
print(2 + 3 * 4) # 14: multiplication first
print((2 + 3) * 4) # 20
# Handy shortcut forms
score = 10
score += 5 # same as score = score + 5
score *= 2 # same as score = score * 2
print(score)
$ python operators.py
The remainder operator is surprisingly useful. n % 2 == 0 tests whether n is even, and minutes % 60 gives the minutes left after counting whole hours.
float_surprise.py
print(0.1 + 0.2) # not exactly 0.3
print(round(0.1 + 0.2, 2)) # round to 2 decimal places
print(round(3.14159, 3))
$ python float_surprise.py
Computers store decimals in binary, and some fractions such as 0.1 cannot be stored exactly. This is normal in every language. Use round() when you display money or measurements.
Converting between types
Python will not guess what you mean when types are mixed. Adding a number to text is an error, because it is unclear whether you want addition or joining. You convert explicitly with int(), float(), str() and bool().
casting.py
print(int("25") + 5) # text '25' becomes the number 25
print(float("2.5") * 2)
print(str(100) + " rupees") # number becomes text so it can be joined
print(int(9.99)) # cuts off the decimals: 9, it does not round
print(int("hello")) # cannot be converted
$ python casting.py
A ValueError means the type is right (text) but the content is not usable as a number. In module 9 you will learn to catch this and ask again.
type_error.py
age = 19
print("I am " + age + " years old")
$ python type_error.py
Fix it by converting, str(age), or better, by using an f-string as shown next.
f-strings: text with values inside
An f-string is a string that starts with f before the opening quote. Anything inside curly braces { } is evaluated as Python and placed into the text. No conversions needed. After a colon inside the braces you can control formatting, such as :.2f for two decimal places or :, for thousands separators.
fstrings.py
name = "Asha"
cups = 3
price = 12.5
total = cups * price
print(f"{name} bought {cups} cups.")
print(f"Total: ₹{total}")
print(f"Total with 2 decimals: ₹{total:.2f}")
print(f"Big number: {1234567:,}")
print(f"{cups} x {price} = {cups * price}") # expressions are allowed
print(f"{name=}") # handy for debugging
$ python fstrings.py
{name=} prints both the name and its value, which is a quick way to inspect a variable.
Reading input
input() pauses the program, shows a prompt, waits for the user to type and press Enter, and hands back what they typed. The key rule: input() always returns a str, even if the user types digits. If you want to do arithmetic, convert the result.
input_demo.py
name = input("What is your name? ")
age_text = input("How old are you? ") # this is text, e.g. '19'
age = int(age_text) # now it is a number
print(f"Hi {name}! Next year you will be {age + 1}.")
$ python input_demo.py
The words after the prompts are what the user typed. If you forget int(), then age + 1 fails with TypeError: can only concatenate str (not "int") to str.
Remember this
A variable is a name attached to a value; assignment evaluates the right side first.
The core types are int, float, str, bool and None; type() tells you which one you have.
/ always gives a float, // drops the fraction, % gives the remainder, ** is power.
Convert explicitly with int(), float() and str(); Python will not mix types for you.
f-strings place values inside text, and input() always returns a string.
Your turn
A cricket team scored 186 runs in 20 overs. Store these in variables, calculate the run rate (runs per over) and print it to 2 decimal places in a sentence. Also print how many complete 10-over blocks fit in 20 overs using floor division.
run_rate = runs / overs. Use {run_rate:.2f} inside an f-string. For blocks use overs // 10.
17 divided by 5 is 3 with a remainder of 2. The % operator returns that remainder.
What type does input() always return?
input() gives back text every time. Convert with int() or float() if you need a number.
Which is a valid variable name?
Names cannot start with a digit, cannot contain hyphens, and cannot be reserved words like class.
Ask the CipherCode AI tutor
Act as my Python tutor. Quiz me with ten short questions about variables, int/float/str/bool, //, % and f-strings. Ask one question at a time, wait for my answer, and explain every mistake with a tiny code example.
Index, slice, search and clean text, and understand why strings can never be changed in place.
About 55 minutes
A string is a sequence of characters: letters, digits, spaces, symbols, emoji. Names, messages, passwords, file paths and web addresses are all strings. Text handling is a huge part of real programs, so Python gives strings a rich set of tools. You write a string with single quotes, double quotes, or triple quotes for text that spans several lines.
string_basics.py
a = "Hello"
b = 'World'
print(a + " " + b) # + joins strings (concatenation)
print(a * 3) # * repeats a string
print(len(a)) # len() counts characters: 5
# Triple quotes keep line breaks
poem = """Roses are red,
Python is neat,
Practise each day,
And you can't be beat."""
print(poem)
# Escape characters start with a backslash
print("Line one\nLine two") # \n is a new line
print("Name:\tAsha") # \t is a tab
print("She said \"hi\"") # \" puts a quote inside the text
print("C:\\Users\\Asha") # \\ gives one backslash
print(r"C:\Users\Asha") # a raw string keeps backslashes as they are
$ python string_basics.py
Indexing: picking one character
Every character in a string has a position called an index. Python counts from zero, so the first character is at index 0. Negative indexes count from the end: -1 is the last character. Think of the index as 'how many steps from the start', and then zero makes sense, because the first character is zero steps away.
Character
C
I
P
H
E
R
Index
0
1
2
3
4
5
Negative index
-6
-5
-4
-3
-2
-1
indexing.py
word = "CIPHER"
print(word[0]) # C first character
print(word[3]) # H
print(word[-1]) # R last character
print(word[-2]) # E
print(word[6]) # there is no index 6
$ python indexing.py
A string with 6 characters has indexes 0 to 5. Asking for index 6 raises IndexError. This 'off by one' mistake is extremely common, so remember: the last valid index is len(s) - 1.
Slicing: picking a piece
A slice takes a range of characters using [start:stop]. It includes start and stops beforestop. Leave out start to begin at the front, leave out stop to go to the end. A third number is the step: [start:stop:step].
slicing.py
word = "CIPHERCODE"
print(word[0:6]) # CIPHER indexes 0 to 5
print(word[:6]) # CIPHER start defaults to 0
print(word[6:]) # CODE stop defaults to the end
print(word[-4:]) # CODE the last four characters
print(word[::2]) # CPECD every second character
print(word[::-1]) # EDOCREHPIC a neat way to reverse
print(word[2:100]) # slices are forgiving: no error when stop is too big
$ python slicing.py
Strings are immutable
Immutable means you cannot change a string after it is created. You can read any character, but you cannot assign to one. To 'change' text you build a new string and, if you want, point the variable at it.
immutable.py
word = "Python"
word[0] = "J" # try to change one character
$ python immutable.py
Fix: build a new string, for example word = "J" + word[1:], which gives Jython.
Methods: built-in tools for strings
A method is a function attached to a value, called with a dot: text.upper(). String methods never change the original (it is immutable). They return a new string, so remember to store or print the result. Here are the ones you will use constantly.
Method
What it does
Example result
upper() / lower()
Change case
'chai'.upper() gives 'CHAI'
title() / capitalize()
Capitalise words / first letter
'masala chai'.title() gives 'Masala Chai'
strip()
Remove spaces from both ends
' hi '.strip() gives 'hi'
replace(old, new)
Swap text
'a-b'.replace('-', '+') gives 'a+b'
split(sep)
Break into a list
'a,b,c'.split(',') gives ['a', 'b', 'c']
sep.join(list)
Join a list into a string
'-'.join(['a','b']) gives 'a-b'
find(x)
Index of x, or -1 if absent
'hello'.find('l') gives 2
count(x)
How many times x appears
'banana'.count('a') gives 3
startswith(x) / endswith(x)
Test the beginning / end
'a.py'.endswith('.py') gives True
isdigit() / isalpha()
Check what it contains
'123'.isdigit() gives True
methods.py
text = " Welcome to CipherCode AI "
print(text.strip()) # remove surrounding spaces
clean = text.strip()
print(clean.upper())
print(clean.lower())
print(clean.replace("AI", "Academy"))
print(text) # the original is unchanged!
words = clean.split() # no argument: split on any whitespace
print(words)
print(len(words), "words")
print("_".join(words)) # join them back with underscores
print("banana".count("a"))
print("banana".find("n"))
print("banana".find("z")) # -1 means not found
print("42".isdigit(), "4.2".isdigit(), "abc".isalpha())
print("report.pdf".endswith(".pdf"))
$ python methods.py
Searching with in
The in operator asks 'is this piece of text inside that one?' and answers True or False. It is case-sensitive, so lower-case both sides when you want a relaxed match.
in_operator.py
email = "asha@example.com"
print("@" in email) # True
print("gmail" in email) # False
print("Chai" in "I love chai") # False: capital C does not match
print("chai" in "I love Chai".lower()) # True after lower-casing
print("x" not in "python") # True
$ python in_operator.py
Formatting recap and a worked example
You met f-strings last module. They also align text, which is useful for tables: {name:<10} left-aligns in 10 spaces, {value:>8.2f} right-aligns a float. Let us combine slicing, methods and formatting in a small program that tidies a messy name and builds a username.
username.py
raw_name = " aRIGELA bilwanth "
# Step 1: remove the outer spaces and fix the capitals
name = raw_name.strip().title()
print(repr(name)) # repr shows the quotes so spaces are visible
# Step 2: split into words, which also removes the doubled gap
parts = name.split()
first, last = parts[0], parts[1]
print(first, last)
# Step 3: username = first 3 letters of first name + last name, lowercase
username = (first[:3] + last).lower()
print(f"Username: {username}")
# Step 4: a small aligned table
print(f"{'Field':<10}{'Value':>14}")
print(f"{'First':<10}{first:>14}")
print(f"{'Last':<10}{last:>14}")
$ python username.py
Walkthrough: strip() trims the ends, title() fixes capitals, split() with no argument treats any run of spaces as one separator, so the double gap vanishes. first[:3] slices the first three letters.
Remember this
Strings are sequences of characters with indexes starting at 0; negatives count from the end.
Slices [start:stop:step] include start and exclude stop, and never raise errors for out-of-range stops.
Strings are immutable: methods return new strings and leave the original unchanged.
split() and join() convert between a string and a list of words.
Use in to test whether text contains other text; remember it is case-sensitive.
Your turn
Given the sentence sentence = ' learn python the CipherCode way ', clean it so each word starts with a capital letter and there are no outer spaces. Then print the number of words, the first word, the last word, and the sentence joined with hyphens.
Use strip() and title(), then split() to get the list of words. words[0] and words[-1] give first and last.
solution.py
sentence = " learn python the CipherCode way "
clean = sentence.strip().title()
words = clean.split()
print(clean)
print("Words:", len(words))
print("First:", words[0])
print("Last:", words[-1])
print("-".join(words))
$ python solution.py
Check yourself
What does 'CIPHERCODE'[2:5] give?
Indexes 2, 3, 4 are P, H, E. The slice stops before index 5.
After text = 'hello'; text.upper(), what is text?
Strings are immutable. upper() returns a new string; the original stays 'hello' unless you store the result.
Which expression reverses a string s?
A step of -1 walks backwards through the whole string. Strings have no reverse() method.
Ask the CipherCode AI tutor
I am learning Python strings. Give me a messy real-world text (like a pasted address or a student list) and ask me to clean it using strip, split, replace, slicing and f-strings. Check my solution and show a shorter alternative.
Compare values, combine tests with and/or/not, and make programs choose a path with if, elif and else.
About 50 minutes
So far your programs run every line, top to bottom, every time. Real programs need to decide: if the password is right, let the user in; if the marks are above 90, give an A grade. Decisions are built from two ingredients: a condition, which is an expression that is either True or False, and an if statement that runs code only when the condition is true.
Comparison operators
Comparisons produce a bool. The most important thing to remember: = assigns, == compares.
An if line ends with a colon :. The lines that belong to it are indented (moved right) by the same amount, conventionally 4 spaces. That indented group is called a block. Python uses indentation, not brackets, to know where a block starts and ends. When the indentation goes back to the left, the block is finished.
if_basic.py
temperature = 34
if temperature > 30:
print("It is hot today.") # runs only when the condition is True
print("Drink some water.") # same block: same indentation
print("This line always runs.") # back at the left edge: outside the if
$ python if_basic.py
Line by line: Python evaluates temperature > 30, gets True, and so runs the two indented lines. The last print is not indented, so it runs whatever the answer was.
if, elif and else
else handles 'everything otherwise'. elif (short for 'else if') adds extra questions in between. Python checks them from the top and runs the first block whose condition is true, then skips the rest. Order therefore matters: put the most specific or highest tests first.
grades.py
marks = 76
if marks >= 90:
grade = "A+"
elif marks >= 75:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "Fail"
print(f"Marks: {marks}, Grade: {grade}")
$ python grades.py
With 76: the first test (90) fails, the second (75) passes, so grade becomes 'A' and the remaining tests are never checked. If you wrote the 40 test first, everyone above 40 would get a C. That is why order matters.
Combining conditions: and, or, not
Operator
True when
Example
and
both sides are true
age >= 18 and has_id
or
at least one side is true
day == 'Sat' or day == 'Sun'
not
flips True and False
not is_raining
logic.py
age = 20
has_ticket = True
is_weekend = False
if age >= 18 and has_ticket:
print("You may enter.")
if is_weekend or age < 12:
print("Discount applies.")
else:
print("Full price.")
if not is_weekend:
print("It's a working day.")
# Membership test works nicely in conditions
day = "Sun"
if day in ("Sat", "Sun"):
print("Weekend!")
$ python logic.py
and and or are 'short-circuit': Python stops as soon as the answer is known. In False and anything, the second part is never evaluated.
Truthiness
An if does not strictly need a bool. Python treats some values as falsy: False, None, 0, 0.0, the empty string '', and empty collections like []. Almost everything else is truthy. This gives a tidy way to test for 'is there anything here?'. You can check with bool(value).
truthiness.py
print(bool(0), bool(1), bool(-5))
print(bool(""), bool("hi"), bool(" ")) # a single space is not empty
print(bool([]), bool([0]))
print(bool(None))
name = input("Name: ").strip()
if name: # same as: if name != ""
print(f"Hello, {name}")
else:
print("You did not type anything.")
$ python truthiness.py
The last part needs keyboard input, so the sample shows a run where the user typed Asha.
Nested conditions and the one-line form
You can put an if inside another if. Indent one more level for each. Nesting is fine for two levels, but more than that is a signal to combine conditions with and or to restructure. Python also offers a conditional expression, a one-line choice between two values: value_if_true if condition else value_if_false.
nested_and_ternary.py
age = 17
has_parent_note = True
if age >= 18:
print("Adult entry")
else:
if has_parent_note: # nested: only checked when age < 18
print("Minor entry with note")
else:
print("Entry denied")
# One-line choice
number = 7
kind = "even" if number % 2 == 0 else "odd"
print(f"{number} is {kind}")
# Leap year: divisible by 4, except centuries unless divisible by 400
year = 2100
is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
print(year, "leap year?", is_leap)
$ python nested_and_ternary.py
The leap-year line shows brackets making the order of and / or clear. and is evaluated before or, but brackets help readers.
Remember this
Comparisons (==, !=, <, >, <=, >=) give True or False; = assigns and == compares.
A colon plus an indented block defines what an if, elif or else controls.
Python runs only the first matching branch in an if/elif/else chain, so order matters.
Combine tests with and, or and not; use in for membership checks.
Empty values and zero are falsy; everything else is truthy.
Your turn
Write a ticket-price program. Set age and is_student variables. Children under 5 are free, ages 5 to 17 pay 50, adults pay 120, but any student (of any age 5 or above) gets 20 off the price. Print the final price in a sentence.
Use if/elif/else to choose the base price first. Then use a second if: if is_student and price > 0 subtract 20. Test with several ages.
solution.py
age = 21
is_student = True
if age < 5:
price = 0
elif age < 18:
price = 50
else:
price = 120
if is_student and price > 0:
price = price - 20
print(f"Age {age}, student: {is_student} -> price is ₹{price}")
$ python solution.py
Check yourself
What will this print? x = 5; if x > 3: print('A') elif x > 1: print('B') else: print('C')
The first condition is true, so its block runs and the elif and else are skipped.
Which value is falsy?
The number 0 is falsy. The text '0', a list with one item and a single space are all non-empty and therefore truthy.
What does 'not (True and False)' evaluate to?
True and False is False, and not False is True.
Ask the CipherCode AI tutor
Give me five small real-life decision problems (like a canteen discount or a login check) and ask me to write the if/elif/else code for each. After each answer, point out any ordering mistakes and show how to simplify the conditions.
Use for and while loops to repeat actions, control them with break and continue, and build totals with the accumulator pattern.
About 55 minutes
Computers are good at doing the same thing a million times without getting bored. A loop repeats a block of code. Python has two kinds. A for loop goes through a known collection of things, one at a time. A while loop keeps going for as long as a condition stays true. Choose for when you know what you are looping over, and while when you do not know in advance how many repeats you need.
The for loop
Read for letter in word: as 'for each letter in word, do the following'. On each round, the loop variable (letter) is attached to the next item. The indented block is the body; it runs once per item.
for_basic.py
for letter in "CODE":
print("letter:", letter)
for drink in ["chai", "coffee", "lassi"]:
print("We serve", drink)
$ python for_basic.py
Strings and lists are both iterable, which means Python knows how to hand over their items one by one.
range(): counting loops
To repeat something a number of times, loop over range(). It produces numbers on demand. range(5) gives 0, 1, 2, 3, 4, which is five numbers starting at zero and stopping before 5, exactly like slicing. range(start, stop) sets the first number, and range(start, stop, step) sets the jump size.
range_demo.py
for i in range(5):
print(i, end=" ")
print() # new line after the loop
for i in range(1, 6): # 1 to 5
print(i, end=" ")
print()
for i in range(10, 0, -2): # counting down by 2
print(i, end=" ")
print()
# Multiplication table with an f-string
number = 7
for i in range(1, 6):
print(f"{number} x {i} = {number * i}")
$ python range_demo.py
The accumulator pattern
One pattern appears in almost every program: start with an initial value, then update it on each pass. That gives you totals, counts, maximums, or a built-up string. Always create the accumulator before the loop. If you create it inside, it resets to the starting value on every round.
accumulator.py
# Sum of the numbers 1 to 100
total = 0 # 1. start before the loop
for n in range(1, 101):
total += n # 2. update on every round
print("Sum 1..100 =", total) # 3. use the result after the loop
# Count how many even numbers are in a list
scores = [12, 7, 30, 45, 8, 22]
even_count = 0
for s in scores:
if s % 2 == 0:
even_count += 1
print("Even scores:", even_count)
# Find the largest value
highest = scores[0]
for s in scores:
if s > highest:
highest = s
print("Highest:", highest)
# Build a string
stars = ""
for _ in range(5): # _ means 'I do not need the variable'
stars += "*"
print(stars)
$ python accumulator.py
Walkthrough of the sum: total starts at 0. When n is 1, total becomes 1. When n is 2, it becomes 3. When n is 3, it becomes 6. By n = 100, the loop has added every number.
The while loop
A while loop checks its condition before every round. If it is true, the body runs, then Python goes back and checks again. When the condition becomes false, the loop ends. Something inside the body must eventually make the condition false, otherwise you have an infinite loop.
while_basic.py
# Countdown
count = 5
while count > 0:
print(count)
count -= 1 # this change is what ends the loop
print("Lift off!")
# Savings: how many months to reach 10000 saving 1500 a month?
saved = 0
months = 0
while saved < 10000:
saved += 1500
months += 1
print(f"{months} months to save ₹{saved}")
$ python while_basic.py
break, continue and loop else
break ends the loop immediately.
continue skips the rest of the current round and jumps to the next one.
else on a loop runs only if the loop finished normally, without hitting break. It is handy for 'search and report not found'.
break_continue.py
# break: stop at the first match
for n in [3, 8, 11, 14, 17]:
if n % 2 == 0:
print("First even number:", n)
break
# continue: skip some items
for n in range(1, 11):
if n % 3 == 0:
continue # skip multiples of 3
print(n, end=" ")
print()
# loop else: runs only when break did NOT happen
for n in [3, 5, 7]:
if n % 2 == 0:
print("found an even number")
break
else:
print("no even numbers in the list")
# while True with break: a common way to repeat until valid
attempts = 0
while True:
attempts += 1
if attempts == 3:
break
print("Stopped after", attempts, "attempts")
$ python break_continue.py
while True: looks scary but is a standard, readable pattern. The loop runs 'forever' until a break inside it decides enough is enough.
Nested loops
A loop inside a loop runs the inner loop completely for each round of the outer loop. Picture a clock: the minute hand goes all the way round for every single step of the hour hand. If the outer loop runs 3 times and the inner runs 4 times, the inner body runs 12 times in total.
nested_loops.py
# A triangle of stars
for row in range(1, 5):
print("*" * row)
print()
# A grid of coordinates
for r in range(1, 4):
for c in range(1, 4):
print(f"({r},{c})", end=" ")
print() # new line after each row
$ python nested_loops.py
enumerate_demo.py
menu = ["Chai", "Coffee", "Lassi"]
for number, item in enumerate(menu, start=1):
print(f"{number}. {item}")
$ python enumerate_demo.py
Remember this
Use for to walk through items and while to repeat until a condition changes.
range(start, stop, step) stops before stop, just like slicing.
The accumulator pattern: create the variable before the loop, update it inside, use it after.
break exits a loop, continue skips to the next round, and a loop else runs only when no break happened.
Every while loop needs something inside that eventually makes its condition false.
Your turn
Print the multiplication table of 9 from 1 to 10. Then, using a loop and an accumulator, calculate the total of only the odd numbers from 1 to 50 and print it. Finally, write a while loop that doubles a starting amount of 100 until it is over 1000 and prints how many doublings it took.
Use range(1, 11) for the table. For odds use range(1, 51, 2) or an if with %. For doubling, keep a counter that you increase each time inside the while.
solution.py
# 1. Table of 9
for i in range(1, 11):
print(f"9 x {i:>2} = {9 * i}")
# 2. Sum of odd numbers 1..50
odd_total = 0
for n in range(1, 51, 2):
odd_total += n
print("Sum of odd numbers:", odd_total)
# 3. Doubling
amount = 100
doublings = 0
while amount <= 1000:
amount *= 2
doublings += 1
print(f"Passed 1000 after {doublings} doublings (amount = {amount})")
$ python solution.py
Check yourself
How many times does the body of 'for i in range(2, 8):' run?
range(2, 8) produces 2, 3, 4, 5, 6, 7. That is six numbers because 8 is excluded.
What does continue do inside a loop?
continue skips the rest of the current round and moves on to the next item or condition check.
Your program seems stuck forever in a while loop. What do you press in the terminal?
Ctrl + C sends a KeyboardInterrupt that stops the running program.
Ask the CipherCode AI tutor
Give me a set of increasingly hard loop exercises: start with printing patterns, then totals and counts, then a guessing game with while True and break. After I submit each solution, explain how many times each loop body runs and where I could simplify.
Store many values in order, change them with list methods, avoid the copying trap, and know when a tuple is the better choice.
About 60 minutes
Until now each variable held one value. Real data comes in groups: the marks of 40 students, the items in a cart, the days of a week. A list holds an ordered collection of values in one variable. You write it with square brackets and commas. Items can be of any type, and you can mix types, though most lists hold one kind of thing.
list_basics.py
marks = [72, 85, 91, 64, 58]
names = ["Asha", "Ravi", "Meena"]
mixed = ["chai", 15, True, 2.5]
empty = []
print(marks)
print(len(marks)) # number of items
print(marks[0], marks[-1]) # indexing works just like strings
print(marks[1:4]) # slicing too: [85, 91, 64]
print(91 in marks) # membership test
print(max(marks), min(marks), sum(marks))
print(sorted(marks)) # a new sorted list; marks itself is unchanged
print(marks)
$ python list_basics.py
Indexing and slicing follow exactly the same rules as strings: start at 0, the stop is excluded, negative numbers count from the end.
Lists are mutable
Unlike strings, lists are mutable: you can change them in place. Assign to an index to replace an item. The list object stays the same one in memory; only its contents change.
mutable.py
cart = ["milk", "bread", "eggs"]
cart[1] = "butter" # replace the item at index 1
print(cart)
cart[0:2] = ["tea", "sugar", "biscuits"] # replace a slice with 3 items
print(cart)
del cart[0] # delete by index
print(cart)
$ python mutable.py
List methods you will use daily
Method
What it does
Returns
append(x)
Add x to the end
None (changes the list)
insert(i, x)
Put x at position i
None
extend(other)
Add all items of another list
None
remove(x)
Delete the first item equal to x
None; ValueError if missing
pop() / pop(i)
Remove and give back the last / i-th item
the removed item
index(x)
Position of the first x
an int; ValueError if missing
count(x)
How many times x appears
an int
sort()
Sort the list in place
None
reverse()
Reverse the list in place
None
list_methods.py
todo = ["wake up", "study"]
todo.append("exercise") # end
todo.insert(1, "tea") # at position 1
todo.extend(["sleep", "dream"])
print(todo)
last = todo.pop() # removes 'dream' and gives it back
print("popped:", last)
todo.remove("tea") # removes by value
print(todo)
numbers = [5, 2, 9, 1, 7]
numbers.sort() # in place
print(numbers)
numbers.sort(reverse=True)
print(numbers)
words = ["banana", "kiwi", "apple"]
words.sort(key=len) # sort by length instead of alphabetically
print(words)
result = numbers.sort() # sort() returns None, a classic mistake
print(result)
$ python list_methods.py
Methods that change a list in place return None. Writing numbers = numbers.sort() wipes your list and leaves None. Use sorted(numbers) if you want a new list back.
Looping over lists
list_loops.py
prices = [15, 20, 12, 30]
total = 0
for p in prices:
total += p
print("Total:", total, "| Average:", total / len(prices))
# Build a new list from an old one
with_gst = []
for p in prices:
with_gst.append(round(p * 1.05, 2))
print(with_gst)
# The same thing in one line: a list comprehension
with_gst2 = [round(p * 1.05, 2) for p in prices]
print(with_gst2 == with_gst)
# Filtering
expensive = [p for p in prices if p > 15]
print(expensive)
$ python list_loops.py
A list comprehension is a compact way to build a list: [expression for item in items if condition]. Read it as 'give me this expression for each item that passes the test'. Use it when it stays readable on one line.
The copying trap
This is the most important idea in the module. Remember the 'sticky label' model of variables. When you write b = a with a list, you do not copy the list. You attach a second label to the same list. Change it through either name and both names see the change.
copy_trap.py
a = [1, 2, 3]
b = a # NOT a copy: two labels, one list
b.append(4)
print("a:", a) # a changed too!
print(a is b) # True: they are the same object
c = a.copy() # a real (shallow) copy
d = a[:] # another way: slice everything
c.append(99)
print("a:", a) # unaffected this time
print("c:", c)
print(a is c) # False
$ python copy_trap.py
Use .copy() or [:] whenever you need an independent list. The same rule applies when you pass a list into a function: the function can change your original.
Tuples: lists that cannot change
A tuple is like a list but immutable. You write it with round brackets. Use a tuple for a fixed group of related values where the order has meaning, such as a coordinate (12.9, 77.6) or an RGB colour. Tuples are safe against accidental change, and they can be used as dictionary keys (lists cannot). A tuple with one item needs a trailing comma: (5,).
tuples.py
point = (3, 4)
print(point[0], point[1])
print(len(point))
single = (5,) # the comma makes it a tuple
not_tuple = (5) # this is just the number 5 in brackets
print(type(single), type(not_tuple))
point[0] = 10 # tuples cannot be changed
$ python tuples.py
This example ends in an error on purpose, so the output is shown as a recorded sample.
Unpacking
Unpacking spreads the items of a list or tuple into separate variables in one line. The number of names must match the number of items, unless you use * to collect the extras into a list. It also gives a classic Python trick: swapping two variables without a temporary one.
unpacking.py
point = (3, 4)
x, y = point
print(x, y)
name, age, city = ["Asha", 19, "Pune"]
print(name, age, city)
first, *middle, last = [10, 20, 30, 40, 50]
print(first, middle, last)
a, b = 1, 2
a, b = b, a # swap
print(a, b)
# Functions that 'return two things' really return a tuple
def min_and_max(values):
return min(values), max(values)
low, high = min_and_max([4, 9, 1, 7])
print(low, high)
$ python unpacking.py
Lists of lists (2D data)
A list can contain other lists. This is how you store a table: each inner list is a row. To reach one cell you use two indexes, row first and then column: grid[1][2] means 'row 1, then item 2 in that row'. Loop over it with a nested loop.
grid.py
marks = [
["Asha", 72, 85, 91],
["Ravi", 64, 58, 77],
["Meena", 90, 95, 88],
]
print(marks[1][0]) # Ravi
print(marks[2][3]) # 88
for row in marks:
name = row[0]
scores = row[1:]
average = sum(scores) / len(scores)
print(f"{name:<6} average {average:.1f}")
# Careful: this builds 3 references to ONE inner list
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # both rows changed!
good = [[0] * 3 for _ in range(2)]
good[0][0] = 1
print(good) # only the first row changed
$ python grid.py
Multiplying a list of lists copies the reference, not the inner list, so the rows share one object. Build rows with a comprehension to get independent lists.
Remember this
Lists hold ordered, changeable collections; indexing and slicing work like strings.
Methods like append, sort and reverse change the list in place and return None.
b = a shares one list; use a.copy() or a[:] for an independent copy.
Tuples are immutable lists, good for fixed groups and for dictionary keys.
Unpacking assigns several variables at once, and tables are lists of lists accessed as grid[row][col].
Your turn
You have scores = [45, 78, 92, 66, 81, 39, 74]. Print the highest, lowest and average (1 decimal). Create a new list passed that holds only scores of 40 or more. Add 55 to passed, sort it from highest to lowest and print it. Print how many students failed.
Use max, min, sum and len. Build passed with a list comprehension and an if. Use passed.append(55) then passed.sort(reverse=True). Failed count is len(scores) - len(passed) before you add 55.
solution.py
scores = [45, 78, 92, 66, 81, 39, 74]
print("Highest:", max(scores))
print("Lowest:", min(scores))
print(f"Average: {sum(scores) / len(scores):.1f}")
passed = [s for s in scores if s >= 40]
failed_count = len(scores) - len(passed)
passed.append(55)
passed.sort(reverse=True)
print("Passed:", passed)
print("Failed:", failed_count)
$ python solution.py
Check yourself
After a = [1, 2]; b = a; b.append(3), what is a?
b = a attaches a second name to the same list, so appending through b changes what a sees.
What does nums = [3, 1, 2]; x = nums.sort() make x?
sort() sorts in place and returns None. Use sorted(nums) to get a new sorted list.
Which creates a tuple with exactly one item?
The trailing comma makes it a tuple. (7) is just the number 7 inside brackets.
Ask the CipherCode AI tutor
Explain Python list aliasing and copying with three small diagrams drawn in text. Then give me five practice problems about lists, tuples and unpacking, and review my solutions, pointing out any aliasing bugs.
Look things up by key with dictionaries, remove duplicates and compare groups with sets, and know which collection to pick.
About 60 minutes
A list finds things by position: 'give me item 3'. Often you want to find things by meaning: 'what is the price of chai?'. A dictionary (dict) stores key: value pairs and looks values up by key, like a real dictionary looks up a meaning by a word. Write it with curly braces. Keys must be immutable (strings, numbers and tuples work) and unique. Values can be anything.
dict_basics.py
prices = {"chai": 15, "coffee": 25, "lassi": 30}
print(prices["chai"]) # look up by key
print(len(prices)) # number of pairs
print("coffee" in prices) # membership checks KEYS
print("tea" in prices)
prices["samosa"] = 12 # add a new pair
prices["chai"] = 18 # update an existing one
print(prices)
del prices["lassi"] # delete a pair
print(prices)
print(prices["tea"]) # missing key
$ python dict_basics.py
Reading a key that does not exist raises KeyError. The sample output is recorded because the last line fails on purpose. Dictionaries keep the order in which you inserted the keys.
Safe lookups with get()
d.get(key) returns the value, or None if the key is missing, with no error. You can supply your own default as the second argument: d.get(key, 0). Use it whenever a key might not exist.
dict_get.py
prices = {"chai": 15, "coffee": 25}
print(prices.get("chai"))
print(prices.get("tea")) # None, no error
print(prices.get("tea", "not on menu")) # custom default
item = "coffee"
if item in prices:
print(f"{item} costs ₹{prices[item]}")
$ python dict_get.py
Looping over dictionaries
Looping directly over a dict gives its keys. Use .values() for values and .items() for both at once, as pairs you can unpack in the loop header.
dict_loops.py
prices = {"chai": 15, "coffee": 25, "lassi": 30}
for key in prices: # keys
print(key)
for value in prices.values(): # values
print(value, end=" ")
print()
for item, price in prices.items(): # both, unpacked
print(f"{item:<8} ₹{price}")
total = sum(prices.values())
print("Menu total:", total)
# Dictionary comprehension: apply 10% discount
discounted = {item: round(price * 0.9, 1) for item, price in prices.items()}
print(discounted)
$ python dict_loops.py
Nested dictionaries
A value can itself be a dictionary or a list. This is how you model records, and it is also exactly the shape of JSON data you will meet on the web. Chain the keys to dig in: students['asha']['marks'].
nested.py
students = {
"asha": {"age": 19, "marks": [72, 85, 91]},
"ravi": {"age": 20, "marks": [64, 58, 77]},
}
print(students["asha"]["age"])
print(students["ravi"]["marks"][1]) # dict, key, then list index
students["ravi"]["marks"].append(81) # change nested data in place
students["meena"] = {"age": 18, "marks": [90, 95]}
for name, info in students.items():
avg = sum(info["marks"]) / len(info["marks"])
print(f"{name.title():<6} age {info['age']} average {avg:.1f}")
$ python nested.py
Notice the quotes inside the f-string: info['age'] uses single quotes because the f-string itself uses double quotes.
The counting pattern
One of the most useful dictionary jobs is counting how often things occur: letters in a word, votes, words in a document. The idea: use the item as the key and the count as the value. get(item, 0) + 1 reads 'the current count, or zero if we have not seen it, plus one'.
counting.py
text = "banana"
counts = {}
for ch in text:
counts[ch] = counts.get(ch, 0) + 1
print(counts)
votes = ["chai", "coffee", "chai", "lassi", "chai", "coffee"]
tally = {}
for v in votes:
tally[v] = tally.get(v, 0) + 1
print(tally)
# Find the winner
winner = max(tally, key=tally.get)
print("Winner:", winner, "with", tally[winner], "votes")
$ python counting.py
Walkthrough for 'banana': first b is not in the dict, so get returns 0 and we store 1. The second a finds 1 and stores 2, and so on. The standard library also has collections.Counter that does this in one line, which you will meet later.
Sets: unique items
A set is an unordered collection of unique items. Duplicates disappear automatically, and checking whether something is in a set is as fast as a dictionary lookup. Write it with curly braces and no colons. An empty set must be written set(), because {} is an empty dict. Sets have no order, so you cannot index them.
sets.py
numbers = [3, 1, 3, 2, 1, 5]
unique = set(numbers)
print(unique) # duplicates gone
print(len(unique))
print(sorted(unique)) # sorted() gives an ordered list
tags = set()
tags.add("python")
tags.add("coding")
tags.add("python") # adding a duplicate does nothing
print(tags)
tags.discard("coding") # remove without error if missing
print(tags)
print(type({}), type(set()))
$ python sets.py
The order in which a set prints is not something to depend on.
Sets shine when comparing groups. Imagine two classes and the students who joined each club. | is union (everyone), & is intersection (in both), - is difference (in the first but not the second) and ^ is symmetric difference (in exactly one).
set_ops.py
coding_club = {"Asha", "Ravi", "Meena", "Karan"}
music_club = {"Meena", "Karan", "Divya"}
print(sorted(coding_club | music_club)) # in either club
print(sorted(coding_club & music_club)) # in both
print(sorted(coding_club - music_club)) # coding only
print(sorted(coding_club ^ music_club)) # in exactly one
print("Asha" in coding_club)
print({"Meena"} <= coding_club) # is it a subset?
$ python set_ops.py
Which collection should I use?
Type
Ordered
Changeable
Duplicates
Best for
list
Yes
Yes
Allowed
A sequence of things you will add to, loop over and sort
tuple
Yes
No
Allowed
A fixed group such as a coordinate; dictionary keys
dict
Yes (insertion order)
Yes
Keys unique
Looking up values by a name or id
set
No
Yes
Not allowed
Removing duplicates, fast membership tests, group comparisons
Remember this
A dict maps unique, immutable keys to values and finds them quickly.
Use get(key, default) to avoid KeyError; loop with items() for pairs.
The counting pattern is counts[x] = counts.get(x, 0) + 1.
Sets hold unique items and support union (|), intersection (&) and difference (-).
Pick list for sequences, tuple for fixed groups, dict for lookups and set for uniqueness.
Your turn
Given the sentence 'the cat and the dog and the bird', count how many times each word appears using a dictionary and print the words from most to least frequent. Also print how many unique words there are using a set.
Use split() to get the words. Count with get(word, 0) + 1. To sort by count use sorted(counts.items(), key=lambda pair: pair[1], reverse=True), or loop and use max repeatedly. A set of the words gives the unique count.
solution.py
sentence = "the cat and the dog and the bird"
words = sentence.split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
ranked = sorted(counts.items(), key=lambda pair: pair[1], reverse=True)
for word, n in ranked:
print(f"{word:<5} {n}")
print("Unique words:", len(set(words)))
$ python solution.py
Check yourself
What does {'a': 1}.get('b', 0) return?
The key 'b' does not exist, so get returns the default value you supplied, which is 0.
What is type({})?
Empty curly braces make a dictionary. Use set() for an empty set.
Which expression gives items in set A but not in set B?
A - B is the difference. | is union, & is intersection, and ^ is items in exactly one of the sets.
Ask the CipherCode AI tutor
Give me a small dataset of products and orders as Python dictionaries and ask me ten questions about it (totals, counts, who ordered what, which customers overlap). Review each of my answers and show a cleaner version if mine is long.
Package code into reusable, named tools with parameters and return values, and understand scope.
About 60 minutes
You have already used functions: print(), len(), range(). A function is a named block of code that you can run whenever you want, as many times as you want. Writing your own functions gives you three big wins. You stop repeating yourself, you give a chunk of logic a clear name, and you can test and fix it in one place.
Defining and calling
You define a function with def, a name, brackets and a colon. The indented lines below are its body. Defining does not run it; it only saves the instructions under that name. You run it by calling it: write its name followed by brackets.
def_basic.py
def greet():
print("Welcome to CipherCode AI!")
print("Let's write some Python.")
greet() # call it
greet() # call it again: no need to retype the body
$ python def_basic.py
Parameters and arguments
A function becomes far more useful when you can hand it information. Parameters are the names listed in the definition; arguments are the actual values you pass in when calling. Think of parameters as empty slots, and arguments as what you put in the slots on each call.
parameters.py
def greet(name, city): # name and city are parameters
print(f"Hello {name} from {city}!")
greet("Asha", "Pune") # arguments, matched by position
greet("Ravi", "Delhi")
greet(city="Chennai", name="Meena") # keyword arguments: any order
$ python parameters.py
return: getting a value back
print shows something on screen, but the program cannot use it afterwards. return hands a value back to the caller so it can be stored, printed, or used in further calculations. The moment Python reaches return, the function ends. A function with no return gives back None.
return_demo.py
def add(a, b):
return a + b
def with_gst(price, rate=5):
return round(price * (1 + rate / 100), 2)
total = add(3, 4)
print(total)
print(add(10, 20) * 2) # the result can be used in an expression
print(with_gst(200))
print(with_gst(200, 18))
def only_prints(x):
print("value is", x)
result = only_prints(5)
print(result) # None: it never returned anything
$ python return_demo.py
Beginners often confuse printing with returning. If you want to use the answer later, return it, and print it at the place where you call the function.
Default values and keyword arguments
A parameter with = in the definition has a default, used when the caller leaves that argument out. Parameters with defaults must come after the ones without. Keyword arguments make calls self-documenting, as in send(to='Asha', urgent=True).
defaults.py
def bill(amount, tip_percent=10, people=1):
total = amount * (1 + tip_percent / 100)
return round(total / people, 2)
print(bill(500)) # uses both defaults
print(bill(500, 15)) # custom tip
print(bill(500, people=4)) # skip tip, set people by keyword
print(bill(amount=1200, tip_percent=0, people=3))
$ python defaults.py
mutable_default.py
def add_item(item, bag=None):
if bag is None:
bag = [] # a fresh list on every call
bag.append(item)
return bag
print(add_item("pen"))
print(add_item("book")) # separate list: no leftovers
$ python mutable_default.py
Returning several values
A function can return several values separated by commas. Python packs them into a tuple, and the caller can unpack them straight into variables, which you saw in the previous module.
A variable created inside a function is local: it exists only while the function runs, and it cannot be seen from outside. Variables created at the top of the file are global and can be read from inside functions. If you assign to a name inside a function, Python creates a new local one rather than changing the global. Treat the function as a sealed room: pass things in with parameters, get things out with return.
scope.py
rate = 5 # global
def price_with_tax(price):
tax = price * rate / 100 # reading a global is fine
return price + tax # tax is local to this function
print(price_with_tax(200))
print(tax) # tax does not exist out here
$ python scope.py
The error is deliberate. Functions that depend on parameters rather than hidden globals are easier to understand and test.
Docstrings and design rules
The first line inside a function can be a string describing it, called a docstring. Tools and the built-in help() show it. Good functions follow a few simple rules: do one job, choose a verb-based name like calculate_total, keep it short enough to fit on a screen, and prefer returning values over printing or changing globals.
docstring.py
def is_even(n):
"""Return True if n is an even whole number, otherwise False."""
return n % 2 == 0
def average(numbers):
"""Return the average of a list of numbers, or 0 for an empty list."""
if not numbers:
return 0
return sum(numbers) / len(numbers)
print(is_even(10), is_even(7))
print(average([4, 6, 8]), average([]))
print(is_even.__doc__)
$ python docstring.py
A first look at recursion
A function can call itself. This is called recursion, and it fits problems that break into smaller copies of themselves. Every recursive function needs a base case that stops the chain, and a step that moves toward it. The factorial of 4 is 4 * 3 * 2 * 1, which is also 4 * factorial(3).
recursion.py
def factorial(n):
if n <= 1: # base case: stop here
return 1
return n * factorial(n - 1) # smaller problem
print(factorial(5)) # 120
# How it unfolds: 5 * (4 * (3 * (2 * 1)))
def countdown(n):
if n == 0:
print("Go!")
return
print(n)
countdown(n - 1)
countdown(3)
$ python recursion.py
Without a base case Python raises RecursionError: maximum recursion depth exceeded. Loops are often simpler for beginners; you will see where recursion truly shines later in the course.
Remember this
def defines a function; calling it with brackets runs it.
Parameters are the slots in the definition; arguments are the values you pass in.
return sends a value back and ends the function; no return means None.
Defaults and keyword arguments make calls flexible; never use a list or dict as a default.
Variables made inside a function are local; pass data in with parameters and out with return.
Your turn
Write a function grade(marks) that returns 'A' for 75 and above, 'B' for 60 to 74, 'C' for 40 to 59 and 'Fail' below 40. Write a second function class_report(marks_list) that returns the average, the highest mark and the number of students who passed (40 or more) as three values. Call both with a list of five marks and print the results.
grade() is an if/elif/else chain that returns. For class_report use sum/len, max and a counting loop or a list comprehension, and return all three values separated by commas.
solution.py
def grade(marks):
"""Return the grade letter for a mark out of 100."""
if marks >= 75:
return "A"
elif marks >= 60:
return "B"
elif marks >= 40:
return "C"
return "Fail"
def class_report(marks_list):
"""Return (average, highest, number_passed)."""
average = sum(marks_list) / len(marks_list)
highest = max(marks_list)
passed = len([m for m in marks_list if m >= 40])
return average, highest, passed
marks_list = [82, 67, 35, 74, 91]
for m in marks_list:
print(m, grade(m))
avg, top, passed = class_report(marks_list)
print(f"Average {avg:.1f}, highest {top}, passed {passed}")
$ python solution.py
Check yourself
What does a function return if it has no return statement?
A function without a return gives back None.
Why is def add(x, bag=[]) risky?
The default list is created once when the function is defined and is reused on every call that omits the argument, so items accumulate.
A variable created inside a function can be used...
It is local to the function. When the function finishes, the name disappears.
Ask the CipherCode AI tutor
Explain the difference between parameters and arguments, print and return, and local and global variables using small examples. Then give me six small functions to write (with tests I can run) and review my code for naming, single responsibility and edge cases.
Read and write text files safely with 'with', and stop programs from crashing by handling exceptions.
About 60 minutes
Variables vanish when your program ends. To keep data, such as marks, a to-do list or settings, you save it in a file. And whenever a program touches the outside world (files, user input, networks) things can go wrong: the file may not exist, the user may type letters where you wanted a number. This module teaches both skills together because they depend on each other: files fail often, so file code needs error handling.
Opening a file
open(path, mode) connects your program to a file and returns a file object. The mode says what you want to do.
Mode
Meaning
If the file exists
If it does not exist
'r'
Read (the default)
Reads it
FileNotFoundError
'w'
Write
Erases it and starts fresh
Creates it
'a'
Append
Adds to the end
Creates it
The with statement
An open file must be closed so the data is saved properly and the operating system can release it. If your code crashes between opening and closing, the file stays open. The with statement solves this: it opens the file, runs your indented block, and always closes the file at the end, even if an error happens. Always use with for files.
write_file.py
# Work inside a temporary folder so the example is safe to run anywhere
import os, tempfile
folder = tempfile.mkdtemp()
path = os.path.join(folder, "students.txt")
with open(path, "w", encoding="utf-8") as f: # w: create or overwrite
f.write("Asha,72\n") # you add the new line yourself
f.write("Ravi,64\n")
with open(path, "a", encoding="utf-8") as f: # a: add to the end
f.write("Meena,90\n")
print("Saved to a file called", os.path.basename(path))
$ python write_file.py
write() does not add a line break for you; include \n. We pass encoding='utf-8' so that text such as ₹ and other languages saves correctly on every system.
Reading a file
There are three common ways to read: read() gives the entire contents as one string, readline() gives one line, and readlines() gives a list of lines. The most idiomatic way for text files is to loop over the file object, which hands you one line at a time and works even for huge files. Each line keeps its trailing \n, so call .strip().
read_file.py
import os, tempfile
path = os.path.join(tempfile.mkdtemp(), "students.txt")
with open(path, "w", encoding="utf-8") as f:
f.write("Asha,72\nRavi,64\nMeena,90\n")
# 1. Whole file at once
with open(path, encoding="utf-8") as f:
content = f.read()
print(repr(content))
# 2. Line by line (recommended)
marks = {}
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip() # remove the \n
if not line: # skip blank lines
continue
name, score = line.split(",")
marks[name] = int(score)
print(marks)
print("Average:", sum(marks.values()) / len(marks))
$ python read_file.py
repr() in the first print shows the hidden \n characters. In the loop, line.split(',') turns 'Asha,72' into ['Asha', '72'], which is unpacked into two names. The score is still text, so we convert it with int().
Exceptions: when something goes wrong
When Python hits a problem it cannot continue past, it raises an exception. If nothing handles it, the program stops and prints a traceback. You can handle exceptions yourself with try and except. Python runs the try block; if an exception of the named type occurs, it jumps straight into the matching except block instead of crashing.
Exception
Typical cause
ValueError
int('abc'): right type, unusable content
TypeError
'5' + 3: wrong kind of value for the operation
ZeroDivisionError
10 / 0
IndexError
[1, 2][5]: position does not exist
KeyError
{'a': 1}['b']: key does not exist
FileNotFoundError
open('missing.txt'): the file is not there
try_except.py
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero.")
return None
return result
print(safe_divide(10, 2))
print(safe_divide(10, 0))
# Reading a file that may not exist
try:
with open("no_such_file.txt", encoding="utf-8") as f:
data = f.read()
except FileNotFoundError:
print("File not found, starting with empty data.")
data = ""
print(repr(data))
$ python try_except.py
The full try statement
try: the risky code.
except SomeError: runs if that error happens. You can have several, and you can name the error object with as e to print its message.
else: runs only if the try block had no error. Put code that depends on success here.
finally: runs always, error or not. It is for cleanup.
full_try.py
def parse_marks(text):
try:
marks = int(text)
except ValueError as e:
print("Problem:", e)
return None
else:
print("Parsed OK")
return marks
finally:
print("Finished parsing", repr(text))
print(parse_marks("85"))
print(parse_marks("eighty"))
$ python full_try.py
Notice that finally runs in both cases, even though the function has already hit a return.
Validating input with a loop
Combining a while True loop, try/except and break gives the standard 'ask until valid' pattern. The loop only ends when the conversion succeeds and the value is acceptable.
ask_number.py
def ask_marks():
while True:
text = input("Enter marks (0-100): ")
try:
marks = int(text)
except ValueError:
print("Please type a whole number, like 75.")
continue
if 0 <= marks <= 100:
return marks
print("Marks must be between 0 and 100.")
marks = ask_marks()
print("You entered", marks)
$ python ask_number.py
The sample shows a user who typed abc, then 150, then 82.
Raising your own errors
Use raise when your function receives something that makes no sense. This is better than quietly returning a wrong answer, because the mistake is reported where it happens.
raise_demo.py
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
print(set_age(19))
try:
set_age(-5)
except ValueError as e:
print("Caught:", e)
$ python raise_demo.py
Remember this
Use open(path, mode) inside a with block so files always close properly.
'r' reads, 'w' overwrites, 'a' appends; write() does not add a new line for you.
Loop over a file object to read it line by line, and strip() each line.
try/except handles named exceptions; else runs on success and finally always runs.
Catch specific exceptions, validate input in a loop, and raise your own errors for impossible values.
Your turn
Write a small to-do saver. Create a function add_task(path, task) that appends a task as a new line, and load_tasks(path) that returns a list of tasks (an empty list if the file does not exist). Add three tasks, load them and print them numbered starting at 1. Use a temporary folder for the file.
add_task opens with 'a' and writes task + '\n'. load_tasks uses try/except FileNotFoundError around open, and strips each line. Use enumerate(tasks, start=1) to number the output.
solution.py
import os, tempfile
def add_task(path, task):
with open(path, "a", encoding="utf-8") as f:
f.write(task + "\n")
def load_tasks(path):
try:
with open(path, encoding="utf-8") as f:
return [line.strip() for line in f if line.strip()]
except FileNotFoundError:
return []
path = os.path.join(tempfile.mkdtemp(), "tasks.txt")
print("Before:", load_tasks(path)) # file does not exist yet
for task in ["Revise loops", "Practise dictionaries", "Build the chai bill project"]:
add_task(path, task)
for number, task in enumerate(load_tasks(path), start=1):
print(f"{number}. {task}")
$ python solution.py
Check yourself
What happens when you open an existing file with mode 'w'?
Mode 'w' truncates the file immediately. Use 'a' to append.
Which block always runs, whether or not an error happened?
finally runs in every case and is meant for cleanup. else runs only when no error occurred.
Why is 'with open(...) as f' preferred?
The with statement guarantees the file is closed when the block ends, even if an exception is raised inside.
Ask the CipherCode AI tutor
I want to practise file handling and exceptions in Python. Give me a mini project, like a contact book saved in a text file, split into small steps. After each step let me paste my code, and review it for crashes, bad input and any place I should catch a specific exception.
Reuse Python's standard library, write your own modules, install third-party packages with pip and keep projects separate with venv.
About 55 minutes
No programmer writes everything from scratch. Python's motto is 'batteries included': it ships with a large standard library of ready-made tools for maths, dates, random numbers, files, the web and more. Beyond that there are hundreds of thousands of third-party packages written by the community. This module shows how to use all of it, and how to split your own code into files.
What is a module?
A module is simply a Python file full of definitions (functions, constants) that you can load into another program with import. A package is a folder of modules. When you import math, Python finds math, runs it once, and gives you a name to reach everything inside it with a dot.
Ways to import
imports.py
import math # use as math.sqrt(...)
print(math.sqrt(144))
print(math.pi)
from math import floor, ceil # bring names in directly
print(floor(7.8), ceil(7.2))
import datetime as dt # give a module a shorter alias
print(dt.date(2026, 1, 26).strftime("%d %B %Y"))
from math import * # avoid: dumps every name into yours
$ python imports.py
Prefer import module or from module import name. Avoid import *: you can no longer tell where a name came from, and it can overwrite your own names.
You can explore any module from inside Python. dir(math) lists its contents and help(math.sqrt) shows the documentation. The official reference is at docs.python.org.
Three standard modules you will use all the time
math_random_datetime.py
import math
import random
import datetime
# math: more than the basic operators
print(math.ceil(4.1), math.floor(4.9)) # round up / down
print(math.factorial(5), math.gcd(12, 18))
print(round(math.sqrt(2), 4))
# random: pseudo-random numbers. seed() makes the sequence repeatable.
random.seed(7)
print(random.randint(1, 6)) # a dice roll, inclusive both ends
menu = ["chai", "coffee", "lassi"]
print(random.choice(menu)) # one random item
random.shuffle(menu) # shuffles in place
print(menu)
print(random.sample(range(1, 50), 3)) # 3 different numbers
# datetime: dates and differences
exam = datetime.date(2026, 12, 15)
launch = datetime.date(2026, 10, 1)
print("Days between:", (exam - launch).days)
print(exam.strftime("%A, %d %b %Y")) # day name, day, month, year
print(exam.weekday()) # Monday is 0
$ python math_random_datetime.py
Without random.seed() the numbers differ on every run, which is what you usually want in a game. We fixed the seed here so you can compare your own output. Seeded values can vary slightly between Python versions, so do not worry if your numbers differ.
Writing your own module
Any .py file is a module. Put related functions in one file, then import it from another file in the same folder. This keeps programs organised: one file for calculations, one for the main program. The import uses the file name without .py.
Run python main.py from the folder that contains both files. Python searches the current folder first, then the standard library and installed packages.
The __name__ == '__main__' guard
When a file is run directly, Python sets a special variable __name__ to the text '__main__'. When the file is imported, __name__ is the module's own name instead. This lets one file serve both purposes: it works as an importable toolbox, and it can also run a demo or tests when launched directly. Without the guard, importing the file would run its demo code every time.
guard_demo.py
def double(n):
return n * 2
print("__name__ is:", __name__)
if __name__ == "__main__":
# runs only when you execute this file directly,
# not when another file imports it
print("Running as a script")
print(double(21))
$ python guard_demo.py
Run directly, __name__ is '__main__'. If another file did import guard_demo, it would see __name__ as 'guard_demo' and skip the indented block.
pip: installing third-party packages
pip is Python's package installer. It downloads packages from the Python Package Index (PyPI) at pypi.org. You run it in the terminal, not inside Python. Use python -m pip so that you are sure pip belongs to the Python you are using (on macOS and Linux write python3 -m pip).
terminal
python -m pip install requests # install a package
python -m pip install "requests==2.32.3" # a specific version
python -m pip list # what is installed
python -m pip show requests # details about one package
python -m pip uninstall requests # remove it
python -m pip freeze > requirements.txt # save the exact list of packages
python -m pip install -r requirements.txt # install that list somewhere else
requirements.txt is how a project tells others (and your future self) which packages it needs.
Virtual environments
Imagine two projects: one needs version 1 of a package, the other needs version 2. If both install into the same place, they fight. A virtual environment (venv) is a private folder holding its own copy of Python's settings and packages for one project. Installing into it never affects your other projects or your system Python. Create one per project, as a habit.
terminal: create and use a venv
# 1. Go to your project folder
cd ciphercode-python
# 2. Create the environment in a folder named .venv
python -m venv .venv # macOS/Linux: python3 -m venv .venv
# 3. Activate it
.venv\Scripts\activate # Windows (Command Prompt / PowerShell)
source .venv/bin/activate # macOS and Linux
# The prompt now starts with (.venv). Installs go only into this project.
python -m pip install requests
# 4. Leave when you are finished
deactivate
If PowerShell refuses to run the activate script, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, or use Command Prompt. Never commit the .venv folder to Git; commit requirements.txt instead.
Your next steps
Build the three beginner projects from this level's project list. Projects are where reading turns into skill.
Practise a little every day. Thirty minutes daily beats five hours once a week.
When you are comfortable here, move on to the Intermediate level: object-oriented programming, comprehensions, decorators, working with APIs and testing.
Read other people's code and the official docs. Searching for an error message is a normal part of a programmer's day.
Remember this
A module is a .py file; import loads it, and the standard library gives you maths, dates, random numbers and more.
Prefer import module or from module import name; avoid import *.
Use if __name__ == '__main__' so a file can be both imported and run directly.
pip installs packages from PyPI; use python -m pip and keep a requirements.txt.
Create one virtual environment per project so dependencies never clash.
Your turn
Write a small dice-game program. Use random.seed(10), roll two dice 5 times with random.randint(1, 6), and print each roll and its total. Then use math to print the average total rounded up with math.ceil. Put the dice rolling in a function roll_two() and call it only inside an if __name__ == '__main__' block.
roll_two() returns a tuple (die1, die2). Collect the totals in a list, then sum(totals) / len(totals) and wrap with math.ceil.
solution.py
import random
import math
def roll_two():
"""Roll two dice and return them as a tuple."""
return random.randint(1, 6), random.randint(1, 6)
if __name__ == "__main__":
random.seed(10)
totals = []
for roll_number in range(1, 6):
a, b = roll_two()
totals.append(a + b)
print(f"Roll {roll_number}: {a} + {b} = {a + b}")
average = sum(totals) / len(totals)
print("Average total:", average)
print("Rounded up:", math.ceil(average))
$ python solution.py
Check yourself
What is the safest way to run pip so it matches your Python?
python -m pip runs pip as a module of that exact Python interpreter, avoiding mismatches between several installed versions.
What does if __name__ == '__main__' check?
__name__ is '__main__' only when the file is executed directly. When imported it holds the module's name.
Why use a virtual environment for each project?
Each venv has its own packages, so different projects can use different versions without conflicts.
Ask the CipherCode AI tutor
Walk me through setting up a clean Python project from scratch on my operating system: a folder, a virtual environment, installing one package with pip, writing a module with the __name__ guard, and saving requirements.txt. Explain what every command does and what could go wrong.
Build these to lock it in
Reading is not enough. Each project uses what you just learned, so build them without copying.
easy
Chai stall bill calculator
Ask for the number of cups of each drink, add GST and print a neat bill.
input and int()
arithmetic
f-strings
dictionaries
Build plan
Store the menu in a dictionary of drink names and prices in rupees.
Loop over the menu and ask how many cups of each drink were ordered.
Multiply quantity by price and keep a running subtotal.
Add 5% GST to the subtotal.
Print each line and the total, with prices aligned using f-string formatting.
medium
Number guessing game
The computer picks a number from 1 to 100 and gives higher or lower hints until you guess it.
random module
while loops
if/elif/else
try/except
Build plan
Pick a secret number with random.randint(1, 100).
Start a while loop that asks for a guess.
Use try/except so that typing letters does not crash the game.
Print 'higher' or 'lower' and count the attempts.
When the guess is right, print the attempts and end the loop with break.
hard
Marks tracker with a file
Save student marks to a text file, load them next time and print the class average and topper.
functions
files
lists and dicts
error handling
Build plan
Write add_student(name, marks) that appends one line to marks.txt.
Write load_students() that reads the file into a dictionary and skips bad lines.
Write average(data) and topper(data) as small functions.
Show a text menu: add, show all, show stats, quit.
Handle a missing file the first time the program runs.
Quick reference
Keep this open while you code.
You write
It means
print('Hi', name)
Show values on screen, separated by a space
x = 10
Create a variable and store 10 in it
type(x)
Tell you what kind of value x holds
f'{name} scored {marks}'
Build text with values inside it
int('5') float('2.5') str(7)
Convert between types
7 // 2 7 % 2 2 ** 3
Floor division (3), remainder (1), power (8)
s[0] s[-1] s[1:4]
First character, last character, a slice
if x > 5: ... elif ...: ... else: ...
Choose which code runs
for i in range(5):
Repeat 5 times with i = 0..4
while cond:
Repeat for as long as cond is True
items.append(x)
Add x to the end of a list
d['key'] d.get('key', 0)
Read a dict value; get() avoids KeyError
def add(a, b=0): return a + b
Define a function with a default
with open('f.txt') as f:
Open a file and close it automatically
try: ... except ValueError: ...
Handle an error instead of crashing
import math
Load a module from the standard library
Ready for Intermediate?
Finish the projects above, then keep the momentum going.