,

Python for Beginners: A Complete Comprehensive Course

python for beginners

A hands-on, 10-module course that takes you from zero to building real Python programs. Each module has short lessons, code to try, exercises, and a mini project. Plan on 30 to 60 minutes per module.

How to Use This Course

  • Type every example yourself. Don’t copy and paste.
  • Do the exercises before looking at hints.
  • Errors are normal. Read the message, it usually tells you what’s wrong.
  • Build the mini project at the end of each module.

Setup: Install Python from python.org (version 3.12 or newer). Use VS Code, or try code online at replit.com or python.org/shell. Check it works by running python --version in a terminal.

Module 1: Your First Program

Goal: Run code and print output.

print("Hello, world!")
print("I am learning Python")

Key ideas

  • print() shows text on screen.
  • Text goes inside quotes (a string).
  • Lines starting with # are comments. Python ignores them.
  • Python runs code top to bottom, one line at a time.
# This is a comment
print("Python is fun") # comment after code

Exercises

  1. Print your name.
  2. Print three lines about your favorite hobby.
  3. Add a comment above each line.

Mini project: Print a small “business card” with your name, city and favorite food.

Module 2: Variables and Data Types

Goal: Store and use information.

A variable is a labeled box that holds a value.

name = "Sam"
age = 25
height = 1.75
is_student = Trueprint(name, age, height, is_student)

The four basic types

TypeNameExample
strtext"hello"
intwhole number42
floatdecimal3.14
boolTrue or FalseTrue

Check a type with type(x):

print(type(42)) # <class 'int'>
print(type("hi")) # <class 'str'>

Naming rules

  • Use letters, numbers and underscores. Can’t start with a number.
  • Use snake_case: first_name, not FirstName.
  • Names are case sensitive: age and Age are different.

f-strings put variables inside text:

name = "Sam"
age = 25
print(f"{name} is {age} years old")

Getting input

name = input("What is your name? ")
print(f"Nice to meet you, {name}!")

input() always returns a string. Convert it when you need a number:

age = int(input("Age? "))
print(f"Next year you will be {age + 1}")

Exercises

  1. Store your favorite number in a variable and print it.
  2. Ask for a name and greet the person.
  3. Ask for two numbers and print their sum.

Mini project: A “Mad Libs” game. Ask for a noun, a verb and an adjective, then print a silly sentence using them.

Module 3: Operators and Strings

Goal: Do math and work with text.

Math operators

print(7 + 3) # 10 addition
print(7 - 3) # 4 subtraction
print(7 * 3) # 21 multiplication
print(7 / 2) # 3.5 division (always a float)
print(7 // 2) # 3 floor division
print(7 % 2) # 1 remainder
print(2 ** 3) # 8 power

Python follows normal math order. Use parentheses to be clear: (2 + 3) * 4.

Shortcuts

score = 10
score += 5 # same as score = score + 5
score -= 2
score *= 2

Comparison operators give True or False:

print(5 == 5) # equal
print(5 != 3) # not equal
print(5 > 3, 5 < 3, 5 >= 5, 5 <= 4)

Logical operators: and, or, not

age = 20
print(age > 18 and age < 65) # True
print(not age > 18) # False

String tools

word = "Python"
print(len(word)) # 6
print(word.upper()) # PYTHON
print(word.lower()) # python
print(word[0]) # P (first character)
print(word[-1]) # n (last character)
print(word[0:3]) # Pyt (slice)
print("Py" in word) # True
print(" hi ".strip()) # hi
print("a,b,c".split(",")) # ['a', 'b', 'c']
print(word.replace("P", "J")) # Jython

Indexing starts at 0, not 1.

Exercises

  1. Convert 100 minutes into hours and minutes using // and %.
  2. Ask for a word and print it in uppercase with its length.
  3. Check whether a number is even using %.

Mini project: A tip calculator. Ask for a bill total and tip percent, then print the tip and the total.

Module 4: Making Decisions (Conditionals)

Goal: Make your program choose.

age = int(input("Age? "))if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")

Rules

  • End the if line with a colon :.
  • Indent the code inside by 4 spaces. Indentation is how Python knows what belongs together.
  • elif means “else if”. You can have many. else is optional.

Combining conditions

has_ticket = True
is_open = Trueif has_ticket and is_open:
print("Come in")

Truthiness: empty values count as False.

name = ""
if not name:
print("Name is empty")

Exercises

  1. Print whether a number is positive, negative or zero.
  2. Grade converter: 90+ is A, 80+ is B, 70+ is C, otherwise F.
  3. Leap year checker (divisible by 4, except centuries unless divisible by 400).

Mini project: A number guessing check. Store a secret number, ask for a guess, and print “too high”, “too low” or “correct”.

Module 5: Loops

Goal: Repeat actions without copying code.

for loop: repeat a set number of times

for i in range(5):
    print(i)        # 0 1 2 3 4for i in range(1, 6):
print(i) # 1 2 3 4 5
for i in range(0, 10, 2):
print(i) # 0 2 4 6 8

Loop over text or lists

for letter in "cat":
    print(letter)for fruit in ["apple", "banana", "cherry"]:
print(fruit)

while loop: repeat while something is true

count = 3
while count > 0:
print(count)
count -= 1
print("Liftoff!")

If the condition never becomes False you get an infinite loop. Press Ctrl+C to stop it.

Control keywords

for n in range(10):
if n == 3:
continue # skip this round
if n == 6:
break # stop the loop
print(n)

Pattern: keep asking until valid

while True:
answer = input("Type yes to continue: ")
if answer == "yes":
break

Pattern: running total

total = 0
for n in range(1, 11):
total += n
print(total) # 55

Exercises

  1. Print the multiplication table for any number.
  2. Sum all even numbers from 1 to 100.
  3. Print a right triangle of stars (*, **, ***…).
  4. FizzBuzz: for 1 to 30 print Fizz for multiples of 3, Buzz for 5, FizzBuzz for both, otherwise the number.

Mini project: A complete number guessing game. The computer picks a random number and the player keeps guessing until correct.

import random
secret = random.randint(1, 20)

Module 6: Lists, Tuples, Sets and Dictionaries

Goal: Store collections of data.

Lists are ordered and changeable.

colors = ["red", "green", "blue"]print(colors[0])          # red
colors.append("yellow") # add to end
colors.insert(1, "pink") # add at position
colors.remove("green") # remove by value
last = colors.pop() # remove and return last
print(len(colors))
colors.sort() # sort in place
numbers = [4, 8, 1]
print(sum(numbers), max(numbers), min(numbers))

Tuples are ordered but can’t be changed.

point = (3, 5)
x, y = point # unpacking

Sets hold unique values with no order.

nums = {1, 2, 2, 3, 3}
print(nums) # {1, 2, 3}

Dictionaries store key and value pairs.

person = {"name": "Sam", "age": 25}print(person["name"])
person["city"] = "Lagos" # add
person["age"] = 26 # update
print(person.get("job", "none")) # safe lookup with default
for key, value in person.items():
print(key, value)

List comprehensions build lists in one line:

squares = [n * n for n in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [n for n in range(10) if n % 2 == 0]

Choosing the right one

NeedUse
Ordered items you will changelist
Fixed group of valuestuple
Unique items, fast “is it in here?”set
Look things up by namedict

Exercises

  1. Make a list of 5 numbers and print the largest and the average.
  2. Remove duplicates from a list using a set.
  3. Count how many times each letter appears in a word using a dictionary.

Mini project: A to-do list app. Show a menu to add a task, view tasks, and remove a task, running in a loop until the user quits.

Module 7: Functions

Goal: Package code so you can reuse it.

def greet(name):
    print(f"Hello, {name}!")greet("Sam")
greet("Ada")

Return values

def add(a, b):
    return a + bresult = add(3, 4)
print(result) # 7

print shows something. return hands a value back so you can use it.

Default and keyword arguments

def power(base, exponent=2):
    return base ** exponentprint(power(5))               # 25
print(power(2, 3)) # 8
print(power(exponent=3, base=2))

Scope: variables made inside a function exist only inside it.

def test():
    x = 10      # local variabletest()
print(x)      # would cause an error

Docstrings describe what a function does:

def area(width, height):
"""Return the area of a rectangle."""
return width * height

Good function habits

  • One function, one job.
  • Use clear verb names: calculate_total, is_even.
  • Prefer returning values over printing inside.

Exercises

  1. Write is_even(n) that returns True or False.
  2. Write average(numbers) that takes a list.
  3. Write is_palindrome(word).

Mini project: Rebuild your tip calculator and guessing game using functions. Add a main() function that runs the program.

def main():
    print("Program starts here")if name == "main":
main()

Module 8: Files, Errors and Modules

Goal: Save data, handle problems, and use other people’s code.

Reading and writing files

with open("notes.txt", "w") as f:
    f.write("First line\n")
    f.write("Second line\n")with open("notes.txt", "r") as f:
content = f.read()
print(content)
with open("notes.txt") as f:
for line in f:
print(line.strip())

Modes: "r" read, "w" write (erases old content), "a" append. The with block closes the file for you.

Handling errors

try:
number = int(input("Enter a number: "))
print(10 / number)
except ValueError:
print("That wasn't a number")
except ZeroDivisionError:
print("Can't divide by zero")

Common errors you will meet:

ErrorUsual cause
SyntaxErrortypo, missing colon or bracket
NameErrorvariable not defined or misspelled
TypeErrormixing types, like "5" + 5
IndexErrorlist position doesn’t exist
KeyErrordictionary key doesn’t exist
IndentationErrorwrong spacing

Modules

import math
print(math.sqrt(16), math.pi)import random
print(random.choice(["a", "b", "c"]))
from datetime import datetime
print(datetime.now())

Installing packages with pip:

pip install requests

JSON is a common format for saving structured data:

import jsondata = {"name": "Sam", "scores": [90, 85]}
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json") as f:
loaded = json.load(f)

Exercises

  1. Write a program that saves a list of names to a file and reads them back.
  2. Make input() for a number keep asking until the user types a valid one.
  3. Count the words in a text file.

Mini project: Upgrade your to-do app so tasks are saved to a JSON file and still there next time you run it.

Module 9: Object-Oriented Programming Basics

Goal: Model real things with classes.

A class is a blueprint. An object is something built from it.

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = agedef bark(self):
    print(f"{self.name} says woof!")

def birthday(self):
    self.age += 1rex = Dog("Rex", 3)
rex.bark()
rex.birthday()
print(rex.age) # 4

Key terms

  • __init__ runs when you create an object.
  • self means “this particular object”.
  • Variables on an object are attributes. Functions inside a class are methods.

Inheritance lets a class reuse another:

class Animal:
    def __init__(self, name):
        self.name = namedef speak(self):
    print("...")class Cat(Animal):
def speak(self):
print(f"{self.name} says meow")
Cat("Mia").speak()

Example: a bank account

class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Not enough money")
else:
self.balance -= amount

Exercises

  1. Create a Rectangle class with area() and perimeter() methods.
  2. Create a Student class that stores grades and returns the average.
  3. Make Car inherit from a Vehicle class.

Mini project: A simple inventory system with an Item class and a Store class that holds many items.

Module 10: Final Projects and Next Steps

Goal: Combine everything and keep growing.

Choose one capstone project

  1. Quiz game: questions stored in a dictionary, score tracking, saved high scores in a file.
  2. Expense tracker: add expenses with categories, show totals per category, save to JSON.
  3. Text adventure: rooms, choices, an inventory, and win or lose endings.
  4. Password generator: random passwords with length and character options.
  5. Contact book: add, search, edit and delete contacts using classes and files.

Capstone checklist

  • Plan first: write what the program should do in plain sentences.
  • Break it into small functions.
  • Handle bad input with try and except.
  • Save and load data from a file.
  • Test after every small change.
  • Add comments and docstrings.

Debugging toolkit

  1. Read the error message from the bottom up. The last line names the problem.
  2. Add print() statements to see what values really are.
  3. Test small pieces separately.
  4. Explain the code line by line out loud.
  5. Search the exact error message online.

Style tips

  • Follow PEP 8: 4-space indents, snake_case names, lines under about 79 characters.
  • Choose names that explain themselves.
  • Don’t repeat yourself. If you copy code twice, make a function.

Where to Go Next

Pick a direction based on what excites you:

InterestLearn next
Data and analysispandas, matplotlib, Jupyter notebooks
WebsitesFlask or Django
Automationos, pathlib, requests, selenium
Gamespygame
AI and machine learningNumPy, scikit-learn
Better codingGit and GitHub, testing with pytest, virtual environments

Suggested 8-Week Schedule

WeekModulesFocus
11, 2Setup, printing, variables
23, 4Operators, strings, if statements
35Loops
46Collections
57Functions
68Files, errors, modules
79Classes
810Capstone project

Practice Tips That Make It Stick

  • Code a little every day. 30 minutes daily beats 4 hours once a week.
  • Retype a finished exercise from memory a few days later.
  • Change working examples to see what breaks.
  • Build things you actually care about.
  • Share your projects and read other people’s code.

You’re ready to start. Open Module 1 and write your first line of code.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>