Docsity

Python Programming for Beginners: Variables, Control Flow, Functions and Files, Study Guides, Projects, Research of Computer Science

Toggle sidebar
bg1
Python Programming for Beginners:
Variables, Control Flow, Functions and
Files
A study guide with runnable code, a summary table and practice questions
Author: Psychedelic Tunes
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
1. How Python runs your code
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.
2. Variables, data types and operators
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 .
# Variables are names that refer to values. Python works out the type itself.
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__)
# Arithmetic
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
•
•
•
Psychedelic Tunes Page 1 of 10
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Python Programming for Beginners: Variables, Control Flow, Functions and Files and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!

Python Programming for Beginners:

Variables, Control Flow, Functions and

Files

A study guide with runnable code, a summary table and practice questions

Author: Psychedelic Tunes

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

1. How Python runs your code

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.

2. Variables, data types and operators

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.

Variables are names that refer to values. Python works out the type itself.

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)

Arithmetic

print(7 / 2, 7 // 2, 7 % 2, 2 ** 10) # true division, floor division, remainder, power

f-strings format values inside text

bmi = 62 / height_m ** 2 print(f"{name} is {age} and has a BMI of {bmi:.1f}")

Type conversion: input() always returns a string, so convert before maths

typed = "42" print(typed + "8", int(typed) + 8, float(typed) / 8)

Strings are sequences: index, slice, and use methods

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

      • Add, subtract, multiply^3 * 4 → 12 / True division (always a float)^7 / 2 → 3. // Floor division^7 // 2 → 3 % Remainder (modulo)^7 % 2 → 1 ** Power 2 ** 10 → 1024 == != < > <= >= Comparison, gives a bool 5 >= 3 → True and or not Logical operators True and not False → True += -= *= Update in place x += 1 is x = x + 1

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

List: ordered, changeable

scores = [72, 88, 95, 61] scores.append(79) scores.sort() print(scores, "max:", max(scores), "avg:", sum(scores) / len(scores))

Tuple: ordered, cannot be changed (immutable)

point = (3, 4) x, y = point # unpacking print("distance from origin:", (x ** 2 + y ** 2) ** 0.5)

Dictionary: key -> value lookups

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"))

Set: unordered, no duplicates

tags = {"python", "beginner", "python"} print(sorted(tags), len(tags))

List comprehension: build a list in one line

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))

Scope: a variable created inside a function is local to it

count = 0 def increment(): count = 99 # a NEW local variable, not the global one return count print(increment(), count)

Functions are values: pass one to sorted() as the key

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,

  1. , or several values returned from a function. Tuples can also be dictionary keys; lists cannot. 17. The default list is created once , when the function is defined, and is shared by every call. f(1) returns [1] , then f(2) returns [1, 2] , and the first result also shows [1, 2] because it is the same list. Fix: def f(a, L=None): then if L is None: L = []. 18. "w" creates the file or erases existing content before writing. "a" keeps existing content and adds new text to the end.

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.