Python Basics: Variables, Loops, and Functions
Master the fundamentals of Python programming with practical examples. Learn variables, data types, loops, and functions to build a strong foundation.
Python is one of the most beginner-friendly programming languages, and that reputation is earned: the syntax reads almost like English, and you can write useful programs within your first week. But "beginner-friendly" doesn't mean the fundamentals are optional. Everything you'll ever build in Python, from scripts to web apps to machine learning pipelines, rests on the same four building blocks: variables, data types, loops, and functions. This guide walks through each one with runnable examples and, just as important, the reasoning and pitfalls around them.
One request before we start: don't just read the code. Type it out and run it, either in a local install of Python 3 or an in-browser environment. Predict what each snippet prints before you run it. That prediction habit is the fastest way to build real fluency.
Understanding variables
A variable is a name attached to a value. Think of it as a label you stick on a piece of data so you can refer to it later:
# Creating variables
name = "Alice"
age = 25
is_student = True
gpa = 3.8
# Variables can be reassigned
age = 26 # Happy birthday!
Two things make Python's variables friendlier than most languages. First, you don't declare types: Python figures out that "Alice" is a string and 25 is an integer on its own. This is called dynamic typing. Second, a variable can be reassigned to anything at any time, even a value of a different type. That flexibility is convenient, but it puts the burden of clarity on your naming.
Which brings us to conventions. Python style (defined in a document called PEP 8) uses snake_case for variables and functions:
# Good variable names
user_name = "Bob"
total_price = 99.99
is_premium = False
# Avoid these patterns
userName = "Bob" # camelCase (not a Python convention)
TOTAL_PRICE = 99.99 # SCREAMING_SNAKE_CASE (reserve for constants)
# Note: classes use PascalCase, e.g. class UserAccount:
Conventions feel cosmetic until you read someone else's code, or your own from three weeks ago. Names like total_price make a program self-explanatory; names like x2 and temp make every read a puzzle. Naming is the cheapest documentation you will ever write.
Data types
Python ships with a small set of built-in types that cover most everyday programming:
# Strings - text data
message = "Hello, Kodion!"
multiline = """This is a
multiline string"""
# Integers and floats - numeric data
count = 42
price = 19.99
# Booleans - True or False
is_logged_in = True
is_admin = False
# Lists - ordered, changeable collections
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
# Dictionaries - key-value pairs
user = {
"name": "Alice",
"age": 30,
"city": "New York",
}
# Tuples - ordered and immutable
coordinates = (10, 20)
rgb = (255, 128, 0)
Knowing the types is step one; choosing the right one for the job is the actual skill. A rough guide:
| Type | Example | Reach for it when |
|---|---|---|
str | "hello" | Text of any kind |
int / float | 42 / 19.99 | Counting / measuring |
bool | True | Yes-or-no state |
list | ["a", "b"] | An ordered collection that will change |
dict | {"name": "Ada"} | Labeled data you look up by key |
tuple | (10, 20) | A fixed group of values that shouldn't change |
The list-versus-dictionary decision comes up constantly. If you'd naturally say "the third item," you want a list. If you'd say "the user's email," you want a dictionary. And when you're unsure what type a value is, ask Python directly with type(value).
One more tool you'll use in nearly every program: f-strings, which embed values inside text by prefixing the string with f and wrapping expressions in curly braces, like f"{name} is {age}". You'll see them throughout the rest of this guide.
Mastering loops
Loops repeat work so you don't have to. Python has two: for loops, which walk through a collection or a range, and while loops, which repeat as long as a condition holds. The rule of thumb: use for when you know what you're iterating over, and while when you only know the stopping condition.
For loops
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Loop with range
for i in range(5): # 0, 1, 2, 3, 4
print(f"Count: {i}")
# Loop with index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
Notice that range(5) produces the numbers 0 through 4, not 1 through 5. Starting from zero and stopping just before the endpoint trips up every beginner at least once, so build the habit of asking "what's the first value, and what's the last?" whenever you write a range. Also notice enumerate: when you need both the position and the item, it's the Pythonic answer, much cleaner than managing a separate counter variable by hand.
While loops
# Countdown example
count = 5
while count > 0:
print(f"Blast off in {count}...")
count -= 1
print("Liftoff!")
# Getting user input
password = ""
while not password:
password = input("Enter a non-empty password: ")
A while loop keeps going until its condition becomes false, which means something inside the loop must move it toward stopping. In the countdown, that's count -= 1. Delete that line and the loop runs forever, printing the same message until you kill the program. Infinite loops are a rite of passage; when you hit one, press Ctrl+C to interrupt it, then ask "what was supposed to change?"
Loop control
Sometimes you need to bail out early or skip an iteration:
# break - exit the loop entirely
for i in range(10):
if i == 5:
break # Stop when i equals 5
print(i)
# continue - skip to the next iteration
for i in range(5):
if i == 2:
continue # Skip printing 2
print(i) # Prints 0, 1, 3, 4
break is the natural fit for searches ("stop once you've found it"), while continue suits filtering ("skip the ones that don't apply"). Use both sparingly; if a loop has several of each, it's usually a sign the logic wants to be reorganized or moved into a function.
Functions: reusable code
Functions let you write logic once, name it, and reuse it anywhere. They're the single biggest step from "writing lines of code" to "building programs," for three reasons: they eliminate copy-paste duplication, they give chunks of logic descriptive names, and they let you test pieces of your program in isolation.
# Simple function
def greet():
print("Hello, Kodion!")
greet() # Call the function
# Function with a parameter
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice") # Output: Hello, Alice!
greet_person("Bob") # Output: Hello, Bob!
# Function with a return value
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
The distinction that confuses nearly every beginner: print displays a value on the screen; return hands a value back to the code that called the function. A function that prints its answer is a dead end, because nothing else can use the result. A function that returns its answer feeds calculations, comparisons, and other functions. When in doubt, return the value and let the caller decide whether to print it.
Default parameters
Defaults make arguments optional, which keeps simple calls simple:
def welcome(name, greeting="Welcome"):
return f"{greeting}, {name}!"
print(welcome("Alice")) # Output: Welcome, Alice!
print(welcome("Bob", "Hi")) # Output: Hi, Bob!
One warning worth learning early: never use a mutable value like a list as a default (def add_item(item, items=[])). Python creates that default list once, when the function is defined, and every call without the argument shares the same list, accumulating items across calls. The standard fix is a default of None, replaced with a fresh list inside the function.
Positional and keyword arguments
def calculate_total(price, quantity, discount=0):
subtotal = price * quantity
total = subtotal * (1 - discount)
return total
# Positional arguments
total1 = calculate_total(10, 5) # 50
# Keyword arguments
total2 = calculate_total(price=10, quantity=5, discount=0.1) # 45
# Mixed (positional first, then keyword)
total3 = calculate_total(10, 5, discount=0.2) # 40
Keyword arguments earn their keep as functions grow. A call like calculate_total(10, 5, 0.2) forces the reader to remember what the third number means; discount=0.2 says it outright. Favor keywords whenever a bare value would be ambiguous.
Returning multiple values
def get_user_info():
name = "Alice"
age = 30
email = "alice@example.com"
return name, age, email
name, age, email = get_user_info()
print(f"{name} is {age} and their email is {email}")
Under the hood, Python packs those values into a tuple and unpacks them on the left side of the assignment. It's a tidy pattern for two or three related values; beyond that, a dictionary (or later, a class) communicates intent better.
Common beginner mistakes
Everyone makes these. Knowing them in advance turns hours of confusion into minutes:
- Confusing
=with==. One assigns, the other compares.if age = 18:is a syntax error;if age == 18:is a question. - Printing instead of returning. If your function prints its result, you can't use that result anywhere else. Return it.
- Off-by-one range errors.
range(1, 10)ends at 9. Check your endpoints. - Inconsistent indentation. Python's structure is its indentation. Pick four spaces, configure your editor, and never mix tabs and spaces.
- Mutable default arguments. The shared-list trap described above. Default to
Noneinstead. - Modifying a list while looping over it. Removing items mid-loop skips elements. Loop over a copy, or build a new list with the items you want to keep.
And a meta-mistake: not reading error messages. Python's tracebacks tell you the file, the line, and the problem. Read the last line first; it names the error, and it's usually right.
Practice: where the learning actually happens
You don't learn Python by reading about Python. After this guide, pick one small project and build it with nothing but variables, types, loops, and functions: a number-guessing game, a tip calculator, or a todo list in the terminal. Each will feel slightly too hard, which is exactly the point. When you get stuck, struggle for fifteen minutes before looking anything up; that struggle is the learning.
Frequently asked questions
Do I need to memorize all the syntax?
No. Fluency comes from repetition, not memorization. Look things up freely; after you've typed a for loop thirty times, it will be in your fingers. What matters is understanding what each construct is for.
What's the difference between a list and a tuple?
Both hold ordered values, but lists can be changed after creation (add, remove, reorder) while tuples cannot. Use a tuple when the group of values is fixed, like coordinates or an RGB color; use a list when the collection will grow or shrink.
Why does my function print "None"?
Because it doesn't return anything. A function without a return statement returns None automatically, so print(my_function()) shows None. Add a return with the value you want to hand back.
How long does it take to learn these basics?
With consistent practice of around thirty minutes to an hour a day, most people are comfortable with variables, loops, and functions within two to three weeks. Consistency beats intensity: daily short sessions outperform weekend marathons because your brain consolidates between sessions.
Your next step
You now have the four building blocks every Python program is made of: variables to name data, types to structure it, loops to repeat work, and functions to organize it. The next move is to write code today, even ten lines. If you want a guided path with instant feedback, the interactive Python Essentials course on Kodion starts exactly here, with an AI tutor that gives you hints instead of answers, and takes you from these fundamentals to building real programs.
Kodion Team
Kodion Editorial
Written by the team that builds Kodion's courses: working engineers who test every example in the interactive editor before it ships. How we create and review content
Continue Learning
📚 Related Articles
Python List Comprehensions, Step by Step
Learn Python list comprehensions step by step: turn any loop into one clean line, filter with if, and know exactly when a plain loop is the better choice.
Build Your First REST API: A Beginner's Roadmap
Design and build a working REST API in Python with FastAPI: endpoints, Pydantic models, status codes, and curl tests, explained step by step.