← Back to blogPython for beginners · 18 min read

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.


A laptop showing beginner Python code with simple icons for automation, data, websites, and AI

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:

python
age = 18

if age >= 18:
    print("Access allowed.")

The output would be:

text
Access allowed.

The condition is:

python
age >= 18

This 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:

python
is_active = True

if is_active:
    print("Account is active.")

The output would be:

text
Account is active.

The `print()` line is indented, so Python knows it belongs inside the `if` statement.

Incorrect example:

python
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:

python
is_paid = False

if is_paid:
    print("Payment received.")
else:
    print("Payment still needed.")

The output would be:

text
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:

python
score = 85

if score >= 90:
    print("Excellent")
elif score >= 70:
    print("Good")
else:
    print("Needs improvement")

The output would be:

text
Good

Python 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:

text
Good

The `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.

python
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:

text
You can view this page.

Both values are true, so access is allowed.

Use `or` when at least one condition must be true.

python
has_coupon = True
is_member = False

if has_coupon or is_member:
    print("Discount applied.")
else:
    print("No discount available.")

The output would be:

text
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:

python
age = 18

if age >= 18
    print("Access allowed.")

Correct:

python
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:

python
status = "active"

if status = "active":
    print("Account is active.")

Correct:

python
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:

python
tasks = ["Write email", "Review file", "Send invoice"]

for task in tasks:
    print(task)

The output would be:

text
Write email
Review file
Send invoice

The 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:

python
products = ["Notebook", "Pen", "Folder"]

for product in products:
    print("Product:", product)

The output would be:

text
Product: Notebook
Product: Pen
Product: Folder

You 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:

python
for product in products:
    print(product)

Less clear example:

python
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:

python
for number in range(5):
    print(number)

The output would be:

text
0
1
2
3
4

Notice that Python starts at 0.

This is normal in programming.

If you want to print numbers from 1 to 5, you can write:

python
for number in range(1, 6):
    print(number)

The output would be:

text
1
2
3
4
5

The 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:

python
prices = [20, 75, 150, 40]

for price in prices:
    if price >= 100:
        print("High price:", price)

The output would be:

text
High price: 150

The 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:

python
count = 1

while count <= 3:
    print("Count:", count)
    count = count + 1

The output would be:

text
Count: 1
Count: 2
Count: 3

The 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:

python
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:

python
count = 1

while count <= 3:
    print(count)
    count = count + 1

Always make sure a `while` loop has a way to stop.

Lists: Storing Groups of Values

A list stores multiple values in order.

Example:

python
tasks = ["Write email", "Review file", "Send invoice"]

This list stores three tasks.

You can print the whole list:

python
tasks = ["Write email", "Review file", "Send invoice"]

print(tasks)

The output would be:

text
['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:

python
tasks = ["Write email", "Review file", "Send invoice"]

print(tasks[0])
print(tasks[1])
print(tasks[2])

The output would be:

text
Write email
Review file
Send invoice

The 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:

python
tasks = ["Write email", "Review file"]

tasks.append("Send invoice")

print(tasks)

The output would be:

text
['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:

python
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:

python
customer = {
    "name": "Sample Customer",
    "email": "customer@example.com",
    "status": "active"
}

print(customer["name"])
print(customer["email"])

The output would be:

text
Sample Customer
customer@example.com

Lists use positions.

Dictionaries use keys.

Updating Dictionary Values

You can update a value in a dictionary.

Example:

python
task = {
    "title": "Review file",
    "status": "open"
}

task["status"] = "complete"

print(task)

The output would be:

text
{'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:

python
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:

text
Basic Plan 20
Standard Plan 50
Premium Plan 100

This 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:

python
def say_hello():
    print("Hello!")

This creates the function.

To run the function, you call it:

python
say_hello()

The output would be:

text
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:

python
def greet_user(name):
    print("Hello,", name)

greet_user("Alex")
greet_user("Jordan")

The output would be:

text
Hello, Alex
Hello, Jordan

The function works with different names because the name is passed into the function.

The parameter is:

python
name

The values passed into the function are:

python
"Alex"
"Jordan"

Parameters make functions flexible.

Functions With Multiple Parameters

A function can receive more than one value.

Example:

python
def calculate_total(price, quantity):
    total = price * quantity
    print(total)

calculate_total(10, 3)

The output would be:

text
30

The 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:

python
def calculate_total(price, quantity):
    return price * quantity

total = calculate_total(10, 3)

print(total)

The output would be:

text
30

The 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`:

python
def add_numbers(a, b):
    print(a + b)

add_numbers(2, 3)

The output would be:

text
5

Example using `return`:

python
def add_numbers(a, b):
    return a + b

result = add_numbers(2, 3)

print(result)

The output would be:

text
5

Both 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:

python
import random

number = random.randint(1, 10)

print(number)

The output might be:

text
7

The number may be different each time because it is random.

The line:

python
import random

tells 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`:

python
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:

bash
pip install requests

After installing a package, you can import it in your Python file:

python
import requests

Beginners 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:

python
print("Hello"

This code is missing a closing parenthesis.

Correct version:

python
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:

python
print(username)

Correct:

python
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:

python
age = 25

message = "Age: " + age

print(message)

This causes an error because Python cannot combine text and a number in that way.

Correct version:

python
age = 25

message = "Age: " + str(age)

print(message)

The output would be:

text
Age: 25

The `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:

python
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:

python
items = ["Pen", "Notebook"]

print(items[1])

The output would be:

text
Notebook

Key Errors

A key error happens when you try to access a dictionary key that does not exist.

Example:

python
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:

python
customer = {
    "name": "Sample Customer",
    "email": "customer@example.com"
}

print(customer["email"])

The output would be:

text
customer@example.com

A 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:

python
price = 50
quantity = 3

print("Price:", price)
print("Quantity:", quantity)

total = price * quantity

print("Total:", total)

The output would be:

text
Price: 50
Quantity: 3
Total: 150

Printing 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:

python
price = 100
discount = 20

final_price = price + discount

print(final_price)

The output would be:

text
120

The code runs, but the logic is wrong.

A discount should subtract from the price, not add to it.

Correct version:

python
price = 100
discount = 20

final_price = price - discount

print(final_price)

The output would be:

text
80

Python 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:

python
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:

text
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:

python
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:

text
Notebook total: 15
Folder total: 8

This 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.

Keep reading with us

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.

Request quote