Python Icon

Python Beginner Course

A vibrant, interactive, and glassy guide to learning Python

Introduction to Python

What is 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.
Python is popular for beginners because of its easy-to-read syntax.
Write a short description of Python, mentioning what makes it unique compared to other languages. For example, how its readability benefits beginners.
Show Example Answer
Python is a high-level, interpreted language known for its readable syntax. This makes it easy for beginners to learn and use, compared to more complex languages like C++ or Java.
Installing Python
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.
Use an IDE like VS Code or PyCharm for syntax highlighting and debugging.
Using Jupyter Notebook (Optional)
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.
Sample Question: What are some uses of Python? Name two.
Show Answer
  • Web development (e.g., using Django or Flask)
  • Data analysis (e.g., with pandas and numpy)
After installing Python, create a program that prints "Welcome to Python!" followed by your name.
Show Example Answer
print("Welcome to Python!")
  print("Your name")

Variables and Data Types

Variables store data for later use.
Data Types:
x = 10
name = "Alice"
pi = 3.14
is_active = True
You can use the 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'>
Python is dynamically typed—you don’t need to specify the data type when creating a variable.
Sample Question: What type will Python assign to value = "42"?
Show Answer
str (string), because the value is in quotes.
Create variables of each data type (integer, float, string, boolean) and print them out with a description.
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

Arithmetic: +, -, *, /, // (integer division), % (modulo), ** (exponentiation)
Comparison: ==, !=, <, >, <=, >=
Logical: and, or, not
Assignment: =, +=, -=, *=
Practice with these operators in simple expressions to understand their precedence.

a = 5
b = 2
print(a + b)    # 7
print(a ** b)   # 25
print(a > b)    # True
Sample Question: What is the output of print(10 // 3)?
Show Answer
3 (integer division)
Sample Question: What is the output of print(17 % 5)?
Show Answer
2 (remainder of division)
Sample Question: What code using //, *, and - is equivalent to int_a % int_b?
Show Answer
int_a - (int_b * (int_a // int_b))
Write a small program that calculates the area of a circle, a rectangle, and a triangle, using appropriate operators.
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)
Create a program that takes two numbers from the user and prints the results of all arithmetic operations between them.
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)
Try combining comparison and logical operators. Write a program that checks if a number is between 10 and 20 (inclusive).
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.")
Demonstrate how +=, -=, 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")
Use elif for multiple conditions and avoid deep nesting for readability.
Sample Question: What will this code print if x = -5?
Show Answer
Negative number
Sample Question: What is the output of the following code?
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
Write a Python program that asks for user input (a number) and prints whether it is divisible by 2, 3, both, or neither.
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.")
Ask the user to input their age. If they are 18 or older, print "Adult". If they are between 13 and 17, print "Teenager". Otherwise, print "Child".
Show Example Answer
age = int(input("Enter your age: "))
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")
Create a grading system: ask the user for a score between 0 and 100 and print their grade (A, B, C, D, F).
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 loop:
for i in range(5):
    print(i)  # Prints 0 1 2 3 4
While loop:
count = 0
while count < 3:
    print(count)
    count += 1
Use for loops when the number of iterations is known, while loops for unknown or condition-based repetition.

For Loops

Use a for loop to print every character in a string.
Show Example Answer
word = "hello"
for char in word:
    print(char)
Write a 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)
Use a 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)
Write a for loop that calculates the factorial of 5.
Show Example Answer
factorial = 1
for i in range(1, 6):
    factorial *= i
print(factorial)
Create a multiplication table (1–5) using nested 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

Create a small snippet that prints numbers from 1 to 10 using a while loop. Test this in a terminal and in an IDE.
Show Example Answer

i = 1
while i <= 10:
    print(i)
    i += 1
Use a while loop to print numbers from 10 down to 1.
Show Example Answer
i = 10
while i >= 1:
    print(i)
    i -= 1
Use a 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}")
Write a 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)
Use a while loop to print the first 10 powers of 2.
Show Example Answer
i = 0
while i < 10:
    print(2 ** i)
    i += 1
Write a loop that prints all even numbers from 0 to 10.
Show Answer
for i in range(0, 11, 2):
    print(i)
Create a program that asks the user to input a list of numbers and then prints the sum of all numbers using a 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

Lists: Ordered, mutable 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}
Use lists for ordered collections you want to modify, tuples for fixed data, dictionaries for key-value lookup, and sets for uniqueness.

Lists

Sample Code Question: How do you remove 2 from mylist = [1, 2, 3]?
Show Answer
mylist.remove(2)
or
del mylist[1]  # 1 is the index of 2
Create a list with a few numbers, sort it, add a new number, remove one, and print the final list.
Show Example Answer
numbers = [5, 2, 9, 1, 3]
numbers.sort()
numbers.append(7)
numbers.remove(1)
print(numbers)
Access the first and last elements of a list.
Show Example Answer
mylist = [10, 20, 30, 40]
print(mylist[0])   # First element
print(mylist[-1])  # Last element
Replace the second element of a list with a new value.
Show Example Answer
mylist = [1, 2, 3]
mylist[1] = 99
print(mylist)
Use a for-loop to print all elements in a list.
Show Example Answer
mylist = [10, 20, 30]
for item in mylist:
    print(item)
Use list slicing to get the middle two elements from a list of 4 items.
Show Example Answer
mylist = [1, 2, 3, 4]
middle = mylist[1:3]
print(middle)

Tuples

Create a tuple of three items and unpack it into separate variables.
Show Example Answer
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c)
Demonstrate that tuples are immutable by attempting to change an element.
Show Example Answer
my_tuple = (10, 20, 30)
# my_tuple[1] = 99  # This will raise an error
print("Tuples cannot be modified.")
Create a tuple with a single item and print its type.
Show Example Answer
single = (42,)
print(type(single))  # 
Convert a list to a tuple and print both.
Show Example Answer
mylist = [1, 2, 3]
mytuple = tuple(mylist)
print(mylist)
print(mytuple)
Use a for-loop to print all elements in a tuple.
Show Example Answer
mytuple = ("a", "b", "c")
for item in mytuple:
    print(item)
Use tuple indexing to access the last element.
Show Example Answer
mytuple = (100, 200, 300)
print(mytuple[-1])

Dictionaries

Retrieve the age of Bob from the dictionary.
Show Example Answer
print(friends["Bob"])
Add a new friend and their age to the dictionary.
Show Example Answer
friends["David"] = 35
print(friends)
Remove Charlie from the dictionary.
Show Example Answer
del friends["Charlie"]
print(friends)
Iterate over the dictionary and print both keys and values.
Show Example Answer
for name, age in friends.items():
    print(f"{name} is {age} years old.")
Check if the key "Alice" exists in the dictionary.
Show Example Answer
if "Alice" in friends:
    print("Alice is in the dictionary.")
else:
    print("Alice is not in the dictionary.")

Sets

Create a set of fruits.
Show Example Answer
fruits = {"apple", "banana", "cherry"}
print(fruits)
Add a new fruit to the set.
Show Example Answer
fruits.add("orange")
print(fruits)
Remove a fruit from the set.
Show Example Answer
fruits.remove("banana")
print(fruits)
Demonstrate union, intersection, and difference with two fruit sets.
Show Example Answer
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "cherry", "date"}

print(set1 | set2)  # Union
print(set1 & set2)  # Intersection
print(set1 - set2)  # Difference
Check if "apple" is in the set.
Show Example Answer
if "apple" in fruits:
    print("Apple is in the set.")
else:
    print("Apple is not in the set.")
Loop through the set and print each fruit.
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.

Use functions to break code into reusable parts. Prefer local variables inside functions to avoid conflicts.

Standard Functions

What is a standard function?

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!
Use standard functions when your logic spans multiple lines, needs multiple steps, or will be reused in different parts of your code.
Sample Question: What is the output of the following code?
def multiply(a, b=2):
    return a * b
print(multiply(3))
Show Answer 6 (because the default value for b is 2)
Write a function that returns the square of a number.
Show Answer
def square(x):
    return x * x
print(square(int(input())))
Create a function called 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
Write a function that calculates the factorial of a number using a for loop.
Show Example Answer
def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

print(factorial(5))
Write a function that takes a list of numbers and returns a new list with each number squared.
Show Example Answer
def square_list(numbers):
    return [x * x for x in numbers]

print(square_list([1, 2, 3, 4]))
Create a function that takes a string and returns the number of vowels in it.
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"))
Demonstrate the concept of variable scope by creating a variable inside a function and trying to access it outside.
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

What is a lambda function?

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
Use lambda functions when you need a simple function for a short time, especially when using map(), filter(), or sorted().
Sample Question: What will be the output of this code?
double = lambda x: x * 2
  print(double(5))
Show Answer 10
Write a lambda function that returns the cube of a number and test it with the number 3.
Show Example Answer
cube = lambda x: x ** 3
  print(cube(3))
Create a lambda function that adds 10 to any number passed to it.
Show Example Answer
add_ten = lambda x: x + 10
  print(add_ten(5))  # Output: 15
Use a lambda function with 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)
Use a lambda function with 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)
Sort a list of tuples by the second item in each tuple using a lambda function.
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

Reading a file:
with open("file.txt", "r") as f:
    content = f.read()
Writing to a file:
with open("file.txt", "w") as f:
    f.write("Hello!")
Always use with to handle files—it closes them automatically.
Sample Code Question: How do you read all lines from a file into a list?
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")
Always catch specific exceptions, not just a generic except.
Sample Question: What is the difference between a syntax error and a runtime error?
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 pandasNumpy & Pandas

numpy: Efficient arrays and math.
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.
Sample Code Question: How do you select the first 3 rows of a DataFrame 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()
Customize your plots with titles, labels, and legends for clarity.
Sample Question: Which function displays the plot window?
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()
Tkinter is great for simple GUI apps. Start with basic widgets like Label and Button.
Sample Code Question: How do you add a button that prints "Clicked!" when pressed?
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

Importing modules:
import math
print(math.sqrt(16))  # 4.0
Installing packages:
pip install requests
Organize your code into modules for easier maintenance.
Sample Question: What’s the command to list outdated pip packages?
Show Answer pip list --outdated

Working with the Internet

HTTP requests:
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)
Always use "wb" mode for binary files like images.
Sample Code Question: How do you check if a request was successful?
Show Answer
if response.status_code == 200:
    print("Success!")

Final Project: Image Downloader Script

Objective: Create a script that downloads images from a list of URLs and saves them to a folder. Add features: file type filtering, progress bar, error handling, and optional GUI.
  1. Accept a list of URLs (from file or user input).
  2. Download each image and save it in a folder.
  3. Show a progress bar (tqdm library).
  4. Handle errors (invalid URL, connection issues).
  5. Optional: Download only specific file types, let user choose folder, retry failed downloads, add GUI with tkinter.
Use requests for downloading, os for file handling, argparse for command-line arguments, and tqdm for progress bars.
Sample Code Question: How do you extract the file name from a URL in Python?
Show Answer
import os
filename = os.path.basename(url)
Bonus: Add a feature to fetch a random image from an API like Unsplash!
Glassmorphism Example Try out your skills by building a web interface with Flask for extra fun!