Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in web development, data analysis, automation, AI, and more.
Show Example Answer
Download and install Python from python.org.
Verify installation in your terminal:
python --version
Create a simple script hello.py
:
print("Hello, World!")
Run it in your terminal or IDE.
Jupyter Notebook is a web-based programming platform for users to easily create and share many different kinds of documents. For example, editing and running python code.
Download and install Jupyter Notebook (Not JupyterLab) from jupyter.org.
If you installed Python, you should be able to use pip to install Jupyter Notebook.
Read more about how to use Jupyter Notebook on their online documentation.
Show Answer
- Web development (e.g., using Django or Flask)
- Data analysis (e.g., with pandas and numpy)
Show Example Answer
print("Welcome to Python!")
print("Your name")
Variables and Data Types
Data Types:
int
– Whole numbers (5
,100
)float
– Decimal numbers (3.14
,0.5
)str
– Text values ("hello"
,'Python'
)bool
–True
orFalse
x = 10
name = "Alice"
pi = 3.14
is_active = True
type()
method to discover the type of any variable or data.
>>> x = 10
>>> type(x)
<class 'int'>
>>> type(True)
<class 'bool'>
>>> type(1.0)
<class 'float'>
>>> type(str(12))
<class 'str'>
value = "42"
?
Show Answer
str
(string), because the value is in quotes.
Show Example Answer
integer_var = 5
float_var = 3.14
string_var = "Hello, Python!"
bool_var = True
print("Integer:", integer_var)
print("Float:", float_var)
print("String:", string_var)
print("Boolean:", bool_var)
Operators
+
, -
, *
, /
, //
(integer division), %
(modulo), **
(exponentiation)Comparison:
==
, !=
, <
, >
, <=
, >=
Logical:
and
, or
, not
Assignment:
=
, +=
, -=
, *=
a = 5
b = 2
print(a + b) # 7
print(a ** b) # 25
print(a > b) # True
print(10 // 3)
?
Show Answer
3
(integer division)
print(17 % 5)
?
Show Answer
2
(remainder of division)
//
, *
, and -
is equivalent to int_a % int_b
?
Show Answer
int_a - (int_b * (int_a // int_b))
Show Example Answer
import math
radius = 5
area_circle = math.pi * radius ** 2
print("Circle:", area_circle)
length, width = 10, 4
area_rectangle = length * width
print("Rectangle:", area_rectangle)
base, height = 8, 3
area_triangle = 0.5 * base * height
print("Triangle:", area_triangle)
Show Example Answer
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Integer Division:", a // b)
print("Modulo:", a % b)
print("Exponentiation:", a ** b)
Show Example Answer
x = int(input("Enter a number: "))
if x >= 10 and x <= 20:
print("The number is between 10 and 20.")
else:
print("The number is outside the range.")
+=
, -=
, and *=
work in a loop.
Show Example Answer
count = 0
product = 1
difference = 6*5*3*2*1
for i in range(1, 6):
count += 1
product *= i
difference -= count
print(f"Count: {count}, Product: {product}, Difference: {difference}")
Conditional Statements
x = 0
if x > 0:
print("Positive number")
elif x == 0:
print("Zero")
else:
print("Negative number")
elif
for multiple conditions and avoid deep nesting for readability.
x = -5
?
Show Answer
Negative number
x = 10
y = 20
if x < y:
print("x is less than y")
elif x == y:
print("x is equal to y")
else:
print("x is greater than y")
Show Answer
x is less than y
Show Example Answer
num = int(input("Enter a number: "))
if num % 2 == 0 and num % 3 == 0:
print("Divisible by both 2 and 3.")
elif num % 2 == 0:
print("Divisible by 2.")
elif num % 3 == 0:
print("Divisible by 3.")
else:
print("Divisible by neither 2 nor 3.")
Show Example Answer
age = int(input("Enter your age: "))
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
Show Example Answer
score = int(input("Enter your score: "))
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
elif score >= 70:
print("Grade C")
elif score >= 60:
print("Grade D")
else:
print("Grade F")
Loops
for i in range(5):
print(i) # Prints 0 1 2 3 4
While loop:
count = 0
while count < 3:
print(count)
count += 1
for
loops when the number of iterations is known, while
loops for unknown or condition-based repetition.
For Loops
for
loop to print every character in a string.
Show Example Answer
word = "hello"
for char in word:
print(char)
for
loop that counts from 5 to 15 and prints only the odd numbers.
Show Example Answer
for i in range(5, 16):
if i % 2 == 1:
print(i)
for
loop to print all elements in a list along with their indices.
Show Example Answer
mylist = ["apple", "banana", "cherry"]
for index, value in enumerate(mylist):
print(index, value)
for
loop that calculates the factorial of 5.
Show Example Answer
factorial = 1
for i in range(1, 6):
factorial *= i
print(factorial)
for
loops.
Show Example Answer
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end="\t")
print()
While Loops
while
loop. Test this in a terminal and in an IDE.
Show Example Answer
i = 1
while i <= 10:
print(i)
i += 1
while
loop to print numbers from 10 down to 1.
Show Example Answer
i = 10
while i >= 1:
print(i)
i -= 1
while
loop to repeatedly ask the user for input until they type exit
.
Show Example Answer
while True:
user_input = input("Enter something (type 'exit' to quit): ")
if user_input == "exit":
break
print(f"You typed: {user_input}")
while
loop that calculates the sum of numbers from 1 to 100.
Show Example Answer
i = 1
total = 0
while i <= 100:
total += i
i += 1
print(total)
while
loop to print the first 10 powers of 2.
Show Example Answer
i = 0
while i < 10:
print(2 ** i)
i += 1
Show Answer
for i in range(0, 11, 2):
print(i)
for
loop.
Show Example Answer
numbers = [int(x) for x in input("Enter numbers separated by spaces: ").split()]
total = 0
for num in numbers:
total += num
print(f"The sum of the numbers is: {total}")
Lists & Collections
mylist = [1, 2, 3]
mylist.append(4) # Adds 4
Tuples: Ordered, immutable collections.
mytuple = (1, 2, 3)
Dictionaries: Key-value pairs.
mydict = {"name": "Alice", "age": 30}
print(mydict["name"]) # Alice
Sets: Unordered, unique elements.
myset = {1, 2, 3}
Lists
2
from mylist = [1, 2, 3]
?
Show Answer
mylist.remove(2)
or
del mylist[1] # 1 is the index of 2
Show Example Answer
numbers = [5, 2, 9, 1, 3]
numbers.sort()
numbers.append(7)
numbers.remove(1)
print(numbers)
Show Example Answer
mylist = [10, 20, 30, 40]
print(mylist[0]) # First element
print(mylist[-1]) # Last element
Show Example Answer
mylist = [1, 2, 3]
mylist[1] = 99
print(mylist)
Show Example Answer
mylist = [10, 20, 30]
for item in mylist:
print(item)
Show Example Answer
mylist = [1, 2, 3, 4]
middle = mylist[1:3]
print(middle)
Tuples
Show Example Answer
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c)
Show Example Answer
my_tuple = (10, 20, 30)
# my_tuple[1] = 99 # This will raise an error
print("Tuples cannot be modified.")
Show Example Answer
single = (42,)
print(type(single)) #
Show Example Answer
mylist = [1, 2, 3]
mytuple = tuple(mylist)
print(mylist)
print(mytuple)
Show Example Answer
mytuple = ("a", "b", "c")
for item in mytuple:
print(item)
Show Example Answer
mytuple = (100, 200, 300)
print(mytuple[-1])
Dictionaries
Show Example Answer
print(friends["Bob"])
Show Example Answer
friends["David"] = 35
print(friends)
Show Example Answer
del friends["Charlie"]
print(friends)
Show Example Answer
for name, age in friends.items():
print(f"{name} is {age} years old.")
Show Example Answer
if "Alice" in friends:
print("Alice is in the dictionary.")
else:
print("Alice is not in the dictionary.")
Sets
Show Example Answer
fruits = {"apple", "banana", "cherry"}
print(fruits)
Show Example Answer
fruits.add("orange")
print(fruits)
Show Example Answer
fruits.remove("banana")
print(fruits)
Show Example Answer
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "cherry", "date"}
print(set1 | set2) # Union
print(set1 & set2) # Intersection
print(set1 - set2) # Difference
Show Example Answer
if "apple" in fruits:
print("Apple is in the set.")
else:
print("Apple is not in the set.")
Show Example Answer
for fruit in fruits:
print(fruit)
Functions & Scope
What are functions? Functions are reusable blocks of code that perform a specific task. You can define your own functions in Python using the def
keyword or use built-in functions like print()
or len()
. Functions help you organize your code, avoid repetition, and make your programs easier to read and debug.
A function may take parameters (inputs), run some logic using those inputs, and optionally return a result. Here's a simple example:
def greet(name):
return f"Hello, {name}!"
Calling greet("Alice")
returns "Hello, Alice!"
.
What is scope? Scope refers to where a variable is accessible in your code. Variables defined inside a function are local to that function, meaning they cannot be accessed from outside the function. This protects variables from being accidentally changed by other parts of the program.
Here's an example:
def say_hi():
message = "Hi"
print(message)
say_hi()
# print(message) # This would cause an error because 'message' is not defined outside the function
In contrast, variables defined outside of any function are in the global scope and can be accessed by the whole program—though it's generally better practice to keep variables local when possible to avoid bugs and confusion.
Standard Functions
A standard function in Python is defined using the def
keyword. It lets you create reusable blocks of code that take inputs (called parameters), perform operations, and optionally return a result using the return
statement.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
def multiply(a, b=2):
return a * b
print(multiply(3))
Show Answer
6
(because the default value for b
is 2)
Show Answer
def square(x):
return x * x
print(square(int(input())))
is_even
that returns True
if a number is even, and False
otherwise.
Show Example Answer
def is_even(n):
return n % 2 == 0
print(is_even(4)) # True
print(is_even(5)) # False
for
loop.
Show Example Answer
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial(5))
Show Example Answer
def square_list(numbers):
return [x * x for x in numbers]
print(square_list([1, 2, 3, 4]))
Show Example Answer
def count_vowels(text):
vowels = 'aeiouAEIOU'
count = 0
for char in text:
if char in vowels:
count += 1
return count
print(count_vowels("hello world"))
Show Example Answer
def demo_scope():
message = "Hello from inside"
print(message)
demo_scope()
# print(message) # Uncommenting this will raise an error because 'message' is not defined outside
Lambda Functions
A lambda function is an anonymous, one-line function defined using the lambda
keyword. It's useful for short operations or when passing a simple function as an argument.
square = lambda x: x * x
print(square(4)) # Output: 16
map()
, filter()
, or sorted()
.
double = lambda x: x * 2
print(double(5))
Show Answer
10
Show Example Answer
cube = lambda x: x ** 3
print(cube(3))
Show Example Answer
add_ten = lambda x: x + 10
print(add_ten(5)) # Output: 15
map()
to square all numbers in a list.
Show Example Answer
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)
filter()
to extract even numbers from a list.
Show Example Answer
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Show Example Answer
pairs = [(1, 3), (2, 1), (4, 2)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)
File Input/Output
with open("file.txt", "r") as f:
content = f.read()
Writing to a file:
with open("file.txt", "w") as f:
f.write("Hello!")
with
to handle files—it closes them automatically.
Show Answer
with open("file.txt", "r") as f:
lines = f.readlines()
Error Handling
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This always runs")
except
.
Show Answer
- Syntax error: Mistake in code structure, found before running.
- Runtime error: Error that occurs while the program is running (e.g., division by zero).
Numpy & Pandas
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2) # [2 4 6]
pandas: DataFrames for tabular data.
import pandas as pd
df = pd.read_csv("data.csv")
print(df.head())
numpy
is essential for numerical computation. pandas
is great for data analysis.
df
?
Show Answer
df.head(3)
Data Visualization with matplotlib
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [5, 6, 7, 8])
plt.title("My Plot")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.show()
Show Answer
plt.show()
GUI with Tkinter
import tkinter as tk
window = tk.Tk()
label = tk.Label(window, text="Hello, Tkinter!")
label.pack()
window.mainloop()
Show Answer
import tkinter as tk
def on_click():
print("Clicked!")
window = tk.Tk()
button = tk.Button(window, text="Click me", command=on_click)
button.pack()
window.mainloop()
Modules & Packages
import math
print(math.sqrt(16)) # 4.0
Installing packages:
pip install requests
Show Answer
pip list --outdated
Working with the Internet
import requests
response = requests.get("https://example.com")
print(response.text)
Downloading an image:
img_url = "https://example.com/image.jpg"
img_data = requests.get(img_url).content
with open("image.jpg", "wb") as file:
file.write(img_data)
"wb"
mode for binary files like images.
Show Answer
if response.status_code == 200:
print("Success!")
Final Project: Image Downloader Script
- Accept a list of URLs (from file or user input).
- Download each image and save it in a folder.
- Show a progress bar (
tqdm
library). - Handle errors (invalid URL, connection issues).
- Optional: Download only specific file types, let user choose folder, retry failed downloads, add GUI with
tkinter
.
requests
for downloading, os
for file handling, argparse
for command-line arguments, and tqdm
for progress bars.
Show Answer
import os
filename = os.path.basename(url)
