






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







How to use this guide. Every program in this guide was run with Python 3, and the text under each program is its real output. Type the code yourself rather than copying it, because typing builds the habit. Save each block as a .py file and run it with python3 file.py (or python file.py on some systems), or paste it into an online Python editor.
Contents
How Python runs your code Variables, data types and operators Strings Control flow: if, for and while Lists, tuples, dictionaries and sets Functions Files and error handling Common beginner mistakes Summary table Practice questions and answers
Python is an interpreted , high-level language. The interpreter reads your file from top to bottom and runs each statement in turn. Three things make Python beginner-friendly:
Readable syntax. Blocks of code are marked by indentation (normally 4 spaces), not by braces. Indentation is part of the language: wrong indentation is an error. Dynamic typing. You do not declare types; a variable takes the type of the value you give it. A large standard library. Modules such as math , csv , random and datetime come built in, imported with import.
A comment starts with # and is ignored by Python. Use comments to explain why the code does something.
A variable is a name that refers to a value, created with = (assignment). Names may contain letters, digits and underscores, cannot start with a digit, and are case-sensitive ( Score and score are different). By convention Python uses snake_case.
name = "Amina" # str age = 20 # int height_m = 1.68 # float is_student = True # bool
print(type(name).name, type(age).name, type(height_m).name, type(is_student).name)
print(7 / 2, 7 // 2, 7 % 2, 2 ** 10) # true division, floor division, remainder, power
bmi = 62 / height_m ** 2 print(f"{name} is {age} and has a BMI of {bmi:.1f}")
typed = "42" print(typed + "8", int(typed) + 8, float(typed) / 8)
course = "Intro to Python" print(course[0], course[-1], course[0:5], course.upper(), len(course)) print(course.split(), course.replace("Python", "Programming"))
str int float bool 3.5 3 1 1024 Amina is 20 and has a BMI of 22. 428 50 5. I n Intro INTRO TO PYTHON 15 ['Intro', 'to', 'Python'] Intro to Programming
Type Example Notes int 42 , -7 Whole numbers of any size float 3.14 , 1.0 Decimal numbers; small rounding errors are normal ( 0.1 + 0.2 == 0.3 is False ) str "hello" , 'A'
Text; single or double quotes
bool True , False Result of comparisons NoneType None "No value", e.g. what a function returns if it has no return
Operator Meaning Example ā result
input() returns text. age = input("Age? ") gives a string such as "20". Convert it with int(age) or float(age) before doing maths, otherwise "42" + "8" joins the strings to make "428" , as the output above shows.
3. Strings
Strings are sequences of characters. Each character has an index starting at 0; negative indexes count from the end ( -1 is the last character). A slice s[start:stop] includes start but stops before stop. In the output above, course[0:5] is "Intro" (indexes 0 to 4).
Strings are immutable : methods such as upper() and replace() return a new string and leave the original unchanged. Useful methods: lower() , upper() , strip() (remove surrounding spaces and newlines), split() (break into a list of words), join() , replace() , find() , startswith() , count().
What to notice
if / elif / else checks conditions from top to bottom and runs only the first block whose condition is true. That is why 83 gets a B: it fails >= 90 and passes >= 80 , so the later checks never run. range(stop) counts from 0 up to, but not including , stop. range(2, 11, 3) gives 2, 5, 8 (the next value, 11, is not included). The sum 1 + 2 + ⦠+ 100 = 5,050, which matches the formula n(n + 1)/2 = 100 à 101 / 2. A while loop repeats as long as its condition is true. Use it when you do not know in advance how many repetitions are needed. Money growing at 7% a year first passes 2,000 after 11 years (1, à 1.07¹¹ = 2,104.85). Make sure something inside the loop changes the condition, or the loop never ends. continue skips to the next repetition; break leaves the loop completely.
5. Lists, tuples, dictionaries and sets
scores = [72, 88, 95, 61] scores.append(79) scores.sort() print(scores, "max:", max(scores), "avg:", sum(scores) / len(scores))
point = (3, 4) x, y = point # unpacking print("distance from origin:", (x ** 2 + y ** 2) ** 0.5)
prices = {"coffee": 3.50, "bagel": 2.25} prices["muffin"] = 2.75 # add a new key for item, price in prices.items(): print(f"{item:7} ${price:.2f}") print("tea" in prices, prices.get("tea", "not on menu"))
tags = {"python", "beginner", "python"} print(sorted(tags), len(tags))
squares = [n * n for n in range(1, 6)] evens = [n for n in range(10) if n % 2 == 0] print(squares, evens)
[61, 72, 79, 88, 95] max: 95 avg: 79. distance from origin: 5. coffee $3. bagel $2. muffin $2. False not on menu ['beginner', 'python'] 2 [1, 4, 9, 16, 25] [0, 2, 4, 6, 8]
Type Syntax Ordered? Changeable? Duplicates? Use it for List [1, 2, 3]
Yes Yes Yes A sequence you will add to, sort or change Tuple (1, 2,
Yes No Yes Fixed groups such as coordinates or a function returning two values Dictionary {"a": 1}
Yes Keys must be unique
Looking up values by a key
Type Syntax Ordered? Changeable? Duplicates? Use it for Keeps insertion order (Python 3.7+) Set {1, 2, 3}
No Yes No Removing duplicates, fast membership tests
Useful list methods: append(x) , insert(i, x) , remove(x) , pop() , sort() , reverse() , index(x) , count(x). Use len() , sum() , min() and max() on any of these collections.
Lists are references. After y = x , both names point to the same list, so y.append(4) also changes x. To make an independent copy, use y = x.copy() or y = x[:].
6. Functions
A function is a named, reusable block of code. Define it with def , give it parameters , and send a result back with return. Values passed in a call are arguments.
def area_of_rectangle(width, height=1): """Return the area. height defaults to 1 if not given.""" return width * height
print(area_of_rectangle(4, 5), area_of_rectangle(4), area_of_rectangle(height=2, width=3))
def min_max(values): return min(values), max(values) # returns a tuple
low, high = min_max([7, 2, 9, 4]) print("low", low, "high", high)
def average(*numbers): # any number of arguments return sum(numbers) / len(numbers)
print(average(2, 4, 6), average(10, 20))
def factorial(n): """Recursive: the function calls itself on a smaller problem.""" if n <= 1: return 1 # base case stops the recursion return n * factorial(n - 1)
print("5! =", factorial(5))
count = 0 def increment(): count = 99 # a NEW local variable, not the global one return count print(increment(), count)
students = [("Ben", 3.2), ("Ava", 3.9), ("Cal", 2.8)] print(sorted(students, key=lambda s: s[1], reverse=True))
1 Line one 2 Line two 3 Line three {'Ava': 91, 'Ben': 78, 'Cal': 85} class average: 84. missing.txt was not found 24 'twelve' is not a whole number
Mode Meaning "r" Read (default). Error if the file does not exist "w" Write. Creates the file, or erases it if it exists "a" Append. Adds to the end, creating the file if needed "r+" Read and write add "b" Binary mode, e.g. "rb" for images
The with statement closes the file automatically, even if an error happens. Each line read from a file ends with "\n" ; strip() removes it. The csv module handles commas and quotes correctly. DictReader turns each row into a dictionary using the header row as keys. Values arrive as strings , so convert numbers with int() or float(). The class average is (91 + 78 + 85) Ć· 3 = 84.67. try / except catches an error (an exception ) so the program can respond instead of crashing. Catch specific exceptions such as FileNotFoundError and ValueError rather than every error. Optional else runs if no error occurred, and finally always runs.
8. Common beginner mistakes
Mistake Symptom Fix Mixing tabs and spaces, or wrong indentation
IndentationError Use 4 spaces consistently
= instead of == in a condition SyntaxError = assigns, == compares Forgetting to convert input() TypeError or "428" instead of 50
int(input(...))
Off-by-one with range Loop runs one time too few range(1, n + 1) to include n Calling a function without () Prints average() not average Mutable default argument def f(a, L=[])
List keeps growing between calls Use L=None and create the list inside Modifying a list while looping over it Items skipped Loop over a copy, or build a new list Comparing floats with == 0.1 + 0.2 == 0.3 is False Use round() or math.isclose()
9. Summary table
Topic Key syntax Remember Variables (^) x = 5 No type declarations; names are case-sensitive Types int float str bool None type(x) shows the type; convert with int() float() str() Division / // % / always gives a float; // floors; % is the remainder Strings s[0] , s[1:4] , f"{x:.2f}" Index from 0; slice stops before the end index; immutable if if ⦠elif ⦠else First true branch runs; indentation marks the block for for x in range(1, 11): range excludes the stop value while while cond: Something must change the condition break / continue
inside loops Leave the loop / skip to next repetition
List [ ] , append , sort Ordered, changeable; y = x shares, x.copy() copies Tuple ( ) Ordered, unchangeable Dictionary (^) {key: value} , d.get(k, default)
Fast lookup by key
Set (^) { } , set() No duplicates, unordered Comprehension (^) [n*n for n in xs if n > 0] Build a list in one line Functions (^) def f(a, b=1): return ⦠return ā print ; base case for recursion Files (^) with open("f.txt", "r") as f:
"w" erases; with closes the file
Errors (^) try: ⦠except ValueError: Catch specific exceptions
10. Practice questions
What do 10 // 3 , 10 % 3 and 10 / 4 evaluate to? Which of these are valid variable names? total_2 , 2total , my-score , _count , class What is printed by print("5" * 3, int("5") * 3)? For s = "programming" , what are s[3:7] , s[-3:] and s[::-1]? What does list(range(10, 0, -3)) produce? What is printed? x = [1, 2, 3]; y = x; y.append(4); print(x) What are bool("") , bool("0") and bool([])? Explain. Write a program that prints the numbers 1 to 15, but prints "Fizz" for multiples of 3, "Buzz" for multiples of 5 and "FizzBuzz" for multiples of both. What is the final value of i? i = 1 then while i < 50: i *= 3 Explain the difference between break and continue. Write a function c_to_f(c) that converts Celsius to Fahrenheit, and test it on ā40, 0, 37 and 100. Write a function is_prime(n) and use it to list the primes below 30. What is the difference between print and return inside a function? What does d.get("b", 0) return if d = {"a": 1}? Why is this safer than d["b"]? Write a list comprehension that returns the words longer than 3 letters in "the quick fox" , in upper case. When should you use a tuple instead of a list? What is wrong with def f(a, L=[]): L.append(a); return L? What do f(1) and then f(2) return? What is the difference between opening a file with "w" and with "a"? Write a function word_counts(path) that returns a dictionary of how many times each word appears in a text file, ignoring case and punctuation.
if n % d == 0: return False return True
print([n for n in range(1, 30) if is_prime(n)])
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Checking divisors only up to ān is enough: if n had a factor larger than ān, it would also have one smaller than ān.
13. print only displays a value on the screen. return ends the function and gives the value back to the caller, so it can be stored or used in further calculations. A function that only prints returns None. 14. It returns 0. get returns the default when the key is missing, while d["b"] raises a KeyError and stops the program if not handled. 15. [w.upper() for w in "the quick fox".split() if len(w) > 3] ā ['QUICK']. 16. When the group of values should not change: coordinates (x, y) , RGB colours, a date (2026, 10,
19.
def word_counts(path): counts = {} with open(path) as f: for line in f: for word in line.lower().split(): word = word.strip(".,!?;:"'") if word: counts[word] = counts.get(word, 0) + 1 return counts
with open("sample.txt", "w") as f: f.write("The cat sat. The cat ran!\nA dog sat.\n") print(word_counts("sample.txt"))
Output:
{'the': 2, 'cat': 2, 'sat': 2, 'ran': 1, 'a': 1, 'dog': 1}
20.
text = input("Enter a whole number: ") try: print("Double:", int(text) * 2) except ValueError: print(f"Sorry, {text!r} is not a whole number.")
Typing 12 prints Double: 24 ; typing twelve prints Sorry, 'twelve' is not a whole number.
This guide is an original study aid written for revision. All code was run with Python 3.