No history yet

Python Basics

Storing Information with Variables

Think of variables as labeled boxes where you can store information. You give a box a name (the variable name) and put something inside it (the value). This makes it easy to find and use that information later. In Python, creating a variable is as simple as picking a name and using the equals sign.

# Assign the number 10 to a variable named 'score'
score = 10

# Assign a piece of text to a variable named 'player_name'
player_name = "Alex"

# Now we can print the values stored in our variables
print(score)
print(player_name)

The kind of information you store determines its data type. Python is flexible, but it's good to know the basic types.

Data TypeDescriptionExample
IntegerWhole numbers, positive or negative.age = 30
FloatNumbers with a decimal point.price = 19.99
StringText, wrapped in single or double quotes.greeting = "Hello!"
BooleanRepresents truth values, either True or False.is_active = True

Python automatically figures out the data type when you assign a value, so you don't have to declare it yourself. This makes the code clean and easy to read.

Making Decisions and Repeating Actions

Programs often need to make decisions. Should it do this, or should it do that? This is handled by control structures. The most common is the if statement, which runs a block of code only if a certain condition is true.

temperature = 75

if temperature > 70:
    print("It's a warm day!")
elif temperature < 40:
    print("It's cold outside!")
else:
    print("The weather is mild.")

In this example, Python checks the temperature. Since 75 is greater than 70, it prints the first message. elif (short for "else if") lets you check another condition, and else provides a fallback for when no conditions are met.

Sometimes you need to repeat an action multiple times. That's where loops come in. The for loop is great for iterating over a sequence of items, like a list of numbers or names.

# This loop will run for each name in the list
for name in ["Alice", "Bob", "Charlie"]:
    print("Hello, " + name)

Another type is the while loop, which keeps running as long as its condition is true. It's useful when you don't know exactly how many times you'll need to loop.

countdown = 5

while countdown > 0:
    print(countdown)
    countdown = countdown - 1  # Decrease the counter

print("Blast off!")

Be careful with while loops! If the condition never becomes false, you'll create an infinite loop that runs forever.

Packaging Your Code

As your scripts get more complex, you'll find yourself writing the same bit of code over and over. Functions let you bundle up a piece of code, give it a name, and run it whenever you want. This practice is known as DRY, or "Don't Repeat Yourself."

Here’s how you define and call a function:

# Define a function that greets someone
def greet(name):
    message = "Welcome, " + name + "!"
    return message

# Call the function with different names
print(greet("Sarah"))
print(greet("Tom"))

Functions can take inputs (called parameters, like name above) and give back an output using the return keyword. This makes them powerful, reusable tools.

What if you have many functions that are all related? You can group them together in a file called a module. A module is simply a Python file with a .py extension that contains functions, variables, and other code. You can then use the import statement to access that code in another script.

Imagine you have a file named helpers.py with the greet() function inside. You could use it in another file like this: import helpers print(helpers.greet("Maria"))

Python comes with a huge collection of built-in modules called the Standard Library, giving you tools for math, file operations, web access, and much more. For example, the random module lets you generate random numbers.

import random

# Generate a random integer between 1 and 10
random_number = random.randint(1, 10)
print(f"Your lucky number is {random_number}")

These building blocks—variables, control structures, functions, and modules—are the foundation of all Python programming. Let's review them before you test your knowledge.

Ready to see what you've learned? Give these questions a try.

Quiz Questions 1/5

In programming, what is the primary role of a variable?

Quiz Questions 2/5

What will the following Python code print?

score = 82
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("D")

With these fundamentals, you have the tools to start writing simple but powerful scripts to automate tasks and solve problems.