Python Conditions, Loops, Functions, and Libraries Explained
Once you understand variables, the next step is learning how Python makes decisions, repeats work, organizes code, and uses libraries. This article explains the remaining beginner foundations before building small projects.
Python Conditions, Loops, Functions, Libraries, and Debugging Explained
Once you understand variables, data types, and operators, Python becomes much more useful.
At that point, your programs can do more than store values or calculate simple totals.
They can start making decisions.
They can repeat work.
They can organize code into reusable pieces.
They can use tools that other developers already built.
They can also break, show errors, and teach you what needs to be fixed.
This article covers the rest of the beginner Python foundations you should understand before moving into small projects.
You do not need to master everything perfectly right away. The goal is to understand what each concept does and why it matters.
What You Will Learn
By the end of this article, you should understand:
- how Python makes decisions with `if`, `else`, and `elif`
- why indentation matters in Python
- how `for` loops repeat work
- how `while` loops work
- how lists store groups of values
- how dictionaries store labeled information
- how functions help you reuse code
- what Python libraries are
- how imports work
- what beginner debugging means
- how to read common Python errors
Conditions: How Python Makes Decisions
A condition lets a program decide what to do.
This is one of the most important ideas in programming.
Without conditions, a program would always do the same thing every time. That would make it very limited.
Real programs need to react to different situations.
For example, a program might need to ask:
- Is the user logged in?
- Is the password correct?
- Is the cart empty?
- Is the payment complete?
- Is the task finished?
- Is the score high enough?
- Is the file available?
- Is the form complete?
Python uses conditions to answer questions like these.
The most common condition tools in Python are:
- `if`
- `else`
- `elif`
The If Statement
An `if` statement checks whether something is true.
Example:
age = 18
if age >= 18:
print("Access allowed.")The output would be:
Access allowed.The condition is:
age >= 18This asks:
Is `age` greater than or equal to 18?
Because `age` is 18, the condition is true. Python runs the indented line below the `if` statement.
Why Indentation Matters
Python uses indentation to understand what belongs inside a block of code.
A block of code is a group of lines that belong together.
Correct example:
is_active = True
if is_active:
print("Account is active.")The output would be:
Account is active.The `print()` line is indented, so Python knows it belongs inside the `if` statement.
Incorrect example:
is_active = True
if is_active:
print("Account is active.")This will cause an error because the `print()` line is not indented.
In Python, spacing is not only for style. It affects how the code works.
The Else Statement
`else` gives Python a backup option.
Example:
is_paid = False
if is_paid:
print("Payment received.")
else:
print("Payment still needed.")The output would be:
Payment still needed.The condition `is_paid` is false, so Python skips the first block and runs the `else` block.
You can read this code like this:
If the payment is complete, print one message. Otherwise, print another message.
This kind of logic appears everywhere in software.
The Elif Statement
`elif` means “else if.”
It lets you check more than one condition.
Example:
score = 85
if score >= 90:
print("Excellent")
elif score >= 70:
print("Good")
else:
print("Needs improvement")The output would be:
GoodPython checks the conditions from top to bottom.
First, it checks whether the score is 90 or higher.
That is false.
Then it checks whether the score is 70 or higher.
That is true, so Python prints:
GoodThe `else` block does not run because Python already found a true condition.
Combining Conditions
Sometimes a program needs to check more than one condition at the same time.
Python uses `and` and `or` for this.
Use `and` when both conditions must be true.
is_logged_in = True
has_permission = True
if is_logged_in and has_permission:
print("You can view this page.")
else:
print("Access denied.")The output would be:
You can view this page.Both values are true, so access is allowed.
Use `or` when at least one condition must be true.
has_coupon = True
is_member = False
if has_coupon or is_member:
print("Discount applied.")
else:
print("No discount available.")The output would be:
Discount applied.Only one condition needs to be true when using `or`.
Common Beginner Mistakes With Conditions
Conditions are powerful, but beginners often make a few common mistakes.
Forgetting the Colon
Incorrect:
age = 18
if age >= 18
print("Access allowed.")Correct:
age = 18
if age >= 18:
print("Access allowed.")The colon tells Python that an indented block is coming next.
Using One Equal Sign Instead of Two
One equal sign assigns a value.
Two equal signs compare values.
Incorrect:
status = "active"
if status = "active":
print("Account is active.")Correct:
status = "active"
if status == "active":
print("Account is active.")One equal sign means “store this value.”
Two equal signs mean “check whether these values are equal.”
Loops: How Python Repeats Work
A loop tells Python to repeat something.
This is one of the biggest reasons programming is useful.
Computers are good at repetitive work. They can repeat steps quickly and consistently without getting bored.
Instead of writing the same code many times, you can write a loop once.
Python has two common beginner loops:
- `for` loops
- `while` loops
For Loops
A `for` loop is usually used when you want to go through a group of items.
Example:
tasks = ["Write email", "Review file", "Send invoice"]
for task in tasks:
print(task)The output would be:
Write email
Review file
Send invoiceThe loop goes through the list one item at a time.
Each item is temporarily stored in the variable `task`.
How to Read a For Loop
Look at this example:
products = ["Notebook", "Pen", "Folder"]
for product in products:
print("Product:", product)The output would be:
Product: Notebook
Product: Pen
Product: FolderYou can read the loop like this:
For each product in the list of products, print the product.
The variable name after `for` should usually describe one item from the list.
Good example:
for product in products:
print(product)Less clear example:
for x in products:
print(x)Both examples work, but the first one is easier to understand.
Readable code matters because you will often come back to your own code later and need to understand what you wrote.
Looping Through Numbers
Python has a function called `range()` that helps you loop through numbers.
Example:
for number in range(5):
print(number)The output would be:
0
1
2
3
4Notice that Python starts at 0.
This is normal in programming.
If you want to print numbers from 1 to 5, you can write:
for number in range(1, 6):
print(number)The output would be:
1
2
3
4
5The second number in `range(1, 6)` is where Python stops, but Python does not include that number.
Using Loops With Conditions
Loops become more useful when combined with conditions.
Example:
prices = [20, 75, 150, 40]
for price in prices:
if price >= 100:
print("High price:", price)The output would be:
High price: 150The loop checks every price in the list.
The condition only prints prices that are 100 or higher.
This pattern is very common in real programs:
- loop through a group of items
- check each item
- do something only when a condition is true
While Loops
A `while` loop repeats as long as a condition is true.
Example:
count = 1
while count <= 3:
print("Count:", count)
count = count + 1The output would be:
Count: 1
Count: 2
Count: 3The loop keeps running while `count` is less than or equal to 3.
Each time the loop runs, `count` increases by 1.
Eventually, `count` becomes 4. At that point, the condition is false, so the loop stops.
For Loop vs While Loop
Use a `for` loop when you already have a group of items to go through.
Examples:
- every task in a list
- every product in a cart
- every name in a list
- every number in a range
Use a `while` loop when something should continue until a condition changes.
Examples:
- keep counting until a limit is reached
- keep asking until valid input is given
- keep retrying while something is not ready
- keep running while a setting is turned on
Beginner rule:
Use a `for` loop when looping through a list.
Use a `while` loop when you are waiting for a condition to become false.
Infinite Loops
An infinite loop is a loop that never stops.
This often happens when a `while` loop condition never becomes false.
Example:
count = 1
while count <= 3:
print(count)This loop never changes `count`.
That means `count` stays 1 forever.
The condition `count <= 3` is always true, so the loop keeps running.
Correct version:
count = 1
while count <= 3:
print(count)
count = count + 1Always make sure a `while` loop has a way to stop.
Lists: Storing Groups of Values
A list stores multiple values in order.
Example:
tasks = ["Write email", "Review file", "Send invoice"]This list stores three tasks.
You can print the whole list:
tasks = ["Write email", "Review file", "Send invoice"]
print(tasks)The output would be:
['Write email', 'Review file', 'Send invoice']Lists are useful when you have many related values.
Examples include:
- tasks
- products
- prices
- usernames
- messages
- scores
- file names
Accessing Items in a List
Each item in a list has a position.
In Python, positions start at 0.
Example:
tasks = ["Write email", "Review file", "Send invoice"]
print(tasks[0])
print(tasks[1])
print(tasks[2])The output would be:
Write email
Review file
Send invoiceThe first item is position 0, not position 1.
This feels strange at first, but it becomes normal with practice.
Adding Items to a List
You can add an item to the end of a list with `append()`.
Example:
tasks = ["Write email", "Review file"]
tasks.append("Send invoice")
print(tasks)The output would be:
['Write email', 'Review file', 'Send invoice']The new item is added to the end of the list.
Dictionaries: Storing Labeled Information
A dictionary stores information using key-value pairs.
A key is the label.
A value is the information stored under that label.
Example:
customer = {
"name": "Sample Customer",
"email": "customer@example.com",
"status": "active"
}In this dictionary:
- `"name"` is a key
- `"Sample Customer"` is a value
- `"email"` is a key
- `"customer@example.com"` is a value
- `"status"` is a key
- `"active"` is a value
A dictionary is useful when each value needs a label.
Accessing Dictionary Values
You can access a value by using its key.
Example:
customer = {
"name": "Sample Customer",
"email": "customer@example.com",
"status": "active"
}
print(customer["name"])
print(customer["email"])The output would be:
Sample Customer
customer@example.comLists use positions.
Dictionaries use keys.
Updating Dictionary Values
You can update a value in a dictionary.
Example:
task = {
"title": "Review file",
"status": "open"
}
task["status"] = "complete"
print(task)The output would be:
{'title': 'Review file', 'status': 'complete'}The task started as open, then changed to complete.
This is useful because information often changes in real programs.
Lists of Dictionaries
Real programs often use lists and dictionaries together.
Example:
products = [
{"name": "Basic Plan", "price": 20},
{"name": "Standard Plan", "price": 50},
{"name": "Premium Plan", "price": 100}
]
for product in products:
print(product["name"], product["price"])The output would be:
Basic Plan 20
Standard Plan 50
Premium Plan 100This pattern is common because a list can hold many items, and each item can be described with a dictionary.
A list stores the collection.
A dictionary describes each item.
Functions: Reusing Code
A function is a reusable block of code.
You write it once, then use it whenever you need it.
Example:
def say_hello():
print("Hello!")This creates the function.
To run the function, you call it:
say_hello()The output would be:
Hello!Functions help keep code organized.
They also help avoid repeating the same logic many times.
Why Functions Matter
Without functions, a program can become messy quickly.
Imagine copying the same calculation into five different places.
If the calculation changes, you need to update it five times.
With a function, you can write the calculation once and reuse it.
Functions help you:
- avoid repeating code
- organize your program
- make code easier to read
- make code easier to update
- break big problems into smaller steps
Functions With Parameters
A parameter lets a function receive information.
Example:
def greet_user(name):
print("Hello,", name)
greet_user("Alex")
greet_user("Jordan")The output would be:
Hello, Alex
Hello, JordanThe function works with different names because the name is passed into the function.
The parameter is:
nameThe values passed into the function are:
"Alex"
"Jordan"Parameters make functions flexible.
Functions With Multiple Parameters
A function can receive more than one value.
Example:
def calculate_total(price, quantity):
total = price * quantity
print(total)
calculate_total(10, 3)The output would be:
30The function receives a price and a quantity.
Then it multiplies them and prints the total.
Return Values
Sometimes a function should give back a result.
That is what `return` does.
Example:
def calculate_total(price, quantity):
return price * quantity
total = calculate_total(10, 3)
print(total)The output would be:
30The function calculates the result and returns it.
Then the returned result is stored in the variable `total`.
Print vs Return
Beginners often confuse `print` and `return`.
`print` displays something on the screen.
`return` sends a value back from a function.
Example using `print`:
def add_numbers(a, b):
print(a + b)
add_numbers(2, 3)The output would be:
5Example using `return`:
def add_numbers(a, b):
return a + b
result = add_numbers(2, 3)
print(result)The output would be:
5Both examples show 5, but they work differently.
Use `return` when you want to use the result later.
Libraries: Using Code That Already Exists
A library is code that someone else already built so you do not have to start from zero.
Python has libraries for many tasks.
Libraries can help with:
- dates and times
- random numbers
- math tools
- reading files
- working with folders
- sending web requests
- reading spreadsheets
- creating charts
- analyzing data
- building websites
- testing code
Libraries are one reason Python is so practical.
You can build faster because you can use existing tools.
Importing a Library
To use a library, you import it.
Example:
import random
number = random.randint(1, 10)
print(number)The output might be:
7The number may be different each time because it is random.
The line:
import randomtells Python that you want to use the `random` library.
Built-In Libraries
Python comes with useful built-in libraries.
Examples include:
- `random` for random numbers and choices
- `datetime` for dates and times
- `math` for math tools
- `os` for working with files and folders
- `json` for working with JSON data
- `csv` for working with CSV files
Example using `datetime`:
from datetime import date
today = date.today()
print(today)The output depends on the day you run the code.
This example uses Python’s built-in date tools to get today’s date.
External Packages and Pip
Some libraries do not come with Python by default.
These are external packages.
Python uses a tool called `pip` to install them.
Example:
pip install requestsAfter installing a package, you can import it in your Python file:
import requestsBeginners do not need to master external packages right away.
For now, understand this:
- Python includes some libraries by default.
- Other packages can be installed.
- `pip` is used to install external packages.
- importing and installing are not the same thing.
Installing makes the package available on your computer.
Importing uses the package inside your Python file.
Errors Are Part of Programming
Every programmer gets errors.
Beginners get errors.
Experienced developers get errors.
An error does not mean you failed.
It means Python found something it could not understand or run.
The goal is not to avoid every error.
The goal is to learn how to read errors, understand them, and fix them.
That skill is called debugging.
Syntax Errors
A syntax error means Python could not understand the structure of your code.
Example:
print("Hello"This code is missing a closing parenthesis.
Correct version:
print("Hello")Syntax errors often come from:
- missing parentheses
- missing quotation marks
- missing colons
- bad indentation
- misspelled keywords
Name Errors
A name error often happens when you use a variable that does not exist.
Incorrect:
print(username)Correct:
username = "Sample User"
print(username)Python reads from top to bottom.
You need to create a variable before using it.
Type Errors
A type error happens when Python receives the wrong kind of value.
Incorrect:
age = 25
message = "Age: " + age
print(message)This causes an error because Python cannot combine text and a number in that way.
Correct version:
age = 25
message = "Age: " + str(age)
print(message)The output would be:
Age: 25The `str()` function converts the number into text.
Index Errors
An index error happens when you try to access a list position that does not exist.
Example:
items = ["Pen", "Notebook"]
print(items[2])This causes an error.
The list has two items:
- `items[0]`
- `items[1]`
There is no `items[2]`.
Correct version:
items = ["Pen", "Notebook"]
print(items[1])The output would be:
NotebookKey Errors
A key error happens when you try to access a dictionary key that does not exist.
Example:
customer = {
"name": "Sample Customer"
}
print(customer["email"])This causes an error because the dictionary has a `"name"` key but not an `"email"` key.
Correct version:
customer = {
"name": "Sample Customer",
"email": "customer@example.com"
}
print(customer["email"])The output would be:
customer@example.comA Simple Debugging Process
When your code breaks, do not panic.
Use a simple process:
1. Read the error message. 2. Look at the line number. 3. Check the line before the error too. 4. Check spelling. 5. Check quotation marks. 6. Check parentheses. 7. Check indentation. 8. Print values to see what is happening. 9. Change one thing at a time. 10. Run the code again.
Debugging is not separate from programming.
Debugging is part of programming.
Using Print to Debug
The `print()` function is a simple debugging tool.
Example:
price = 50
quantity = 3
print("Price:", price)
print("Quantity:", quantity)
total = price * quantity
print("Total:", total)The output would be:
Price: 50
Quantity: 3
Total: 150Printing values helps you see what the program is doing.
This is especially useful when the code runs, but the result is not what you expected.
Logic Errors
Not every bug creates an error message.
Sometimes the code runs, but the answer is wrong.
Example:
price = 100
discount = 20
final_price = price + discount
print(final_price)The output would be:
120The code runs, but the logic is wrong.
A discount should subtract from the price, not add to it.
Correct version:
price = 100
discount = 20
final_price = price - discount
print(final_price)The output would be:
80Python cannot always know your intention.
It follows your instructions exactly, even when those instructions do not match what you meant.
Mini Practice
Read this code and guess the output:
products = [
{"name": "Basic Plan", "price": 20},
{"name": "Premium Plan", "price": 100}
]
for product in products:
if product["price"] >= 50:
print(product["name"], "is a higher-priced item.")
else:
print(product["name"], "is a lower-priced item.")The output would be:
Basic Plan is a lower-priced item.
Premium Plan is a higher-priced item.This example combines several beginner concepts:
- a list
- dictionaries
- a loop
- a condition
- printed output
That is how Python programs grow.
You learn small pieces first, then combine them into bigger ideas.
Another Practice Example
Read this code:
def calculate_total(price, quantity):
return price * quantity
items = [
{"name": "Notebook", "price": 5, "quantity": 3},
{"name": "Folder", "price": 2, "quantity": 4}
]
for item in items:
total = calculate_total(item["price"], item["quantity"])
print(item["name"], "total:", total)The output would be:
Notebook total: 15
Folder total: 8This example uses:
- a function
- a list
- dictionaries
- a loop
- multiplication
- printed output
The function handles the calculation.
The list stores multiple items.
Each dictionary describes one item.
The loop goes through each item.
This is a good example of how beginner concepts work together.
What You Know Now
At this point, you have seen the core beginner building blocks of Python.
You have learned that:
- variables store information
- data types describe what kind of information you have
- operators calculate and compare values
- conditions make decisions
- loops repeat work
- lists store groups of values
- dictionaries store labeled information
- functions reuse code
- libraries add extra tools
- debugging helps you find and fix problems
These ideas are the foundation for almost every Python project.
Even advanced software is built from smaller pieces like these.
Final Thoughts
This article covered a lot of Python basics, but every concept has a clear purpose.
Conditions help programs make decisions.
Loops help programs repeat work.
Lists and dictionaries help programs organize information.
Functions help programs reuse logic.
Libraries help programs do more without starting from zero.
Debugging helps you understand and fix problems.
You do not need to memorize everything perfectly before moving forward.
The better goal is to understand what each tool is for.
Once you understand the purpose of each concept, Python becomes much less intimidating.
Now the beginner foundation is ready.
The next step in the Fun with Python series is to start building small, useful, and fun Python apps.
Want more notes like this?
Join the Luca Techs newsletter for practical articles about software, automation, SEO, business systems, and the projects we are learning from.
Planning a project?
Tell us what you want to build and we will help shape the path.