Laptop with the Python logo and glowing code panels
Programming

Python Basics: Variables, Loops and Functions with Examples

29 Oct 202611 min readLevel: Beginner100% FreeBy Tahmeer Tech

1. Variables — labelled boxes for data

A variable stores a value so you can use it later. In Python you create one just by giving it a name:

name = "Nouman"
age = 20
price = 99.5

Python decides the type automatically: text (string), whole numbers (int) and decimal numbers (float).

2. Loops — repeat without repeating yourself

A for loop runs a block of code a set number of times:

for i in range(3):
    message = "Lesson " + str(i + 1)
    # message becomes Lesson 1, Lesson 2, Lesson 3

A while loop keeps going until a condition becomes false — perfect for menus and games that wait for the user.

3. Functions — reusable mini-programs

A function is a named block of code you can run again and again:

def greet(name):
    return "Welcome to Tahmeer Tech, " + name

result = greet("Ayesha")

You give a function inputs (arguments), it does its work, and it can hand back an output with return.

Put it together — a tiny example

def total_marks(marks):
    total = 0
    for m in marks:
        total = total + m
    return total

my_marks = [80, 75, 90]
answer = total_marks(my_marks)   # 245

A list of marks goes in, a loop adds them, and the function returns the total. Variables, loops and functions — working together.

Go deeper — dictionaries and input

Two more tools you will use daily. A dictionary stores labelled data:

student = {"name": "Ali", "semester": 3}
print(student["name"])   # Ali

And input() lets your program ask the user questions, so the same code works for everyone, not just for fixed values.

Practice task (45 minutes)

Build a marks calculator: ask for 3 subject marks with input(), store them in a list, use a function to return the total and average, and print a grade (A for 80+, B for 65+, C for 50+, otherwise “Work harder”). Run it for two different students.

Common mistakes to avoid

  • Mixing text and numbers without converting with int() or str()
  • Wrong indentation — Python treats spaces as part of the code
  • Copy-pasting code you cannot explain line by line
Summary — key points

Variables store, loops repeat, functions organise. Type these examples yourself — reading code teaches a little, typing it teaches a lot.