No history yet

Python Basics

The Building Blocks

Think of a variable as a labeled box where you can store information. You give the box a name, and you can put things inside it. In Python, you can store different kinds of information, or data types.

The most common data types are:

  • Strings: Plain text, like a name or a message. You write them inside quotes. ("hello")
  • Integers: Whole numbers, positive or negative. (10, -5)
  • Floats: Numbers with a decimal point. (3.14, -0.5)
  • Booleans: Can only be one of two values: True or False. They're perfect for tracking states or answering yes/no questions.
# String: Storing text
user_name = "Alex"

# Integer: Storing a whole number
user_age = 32

# Float: Storing a number with a decimal
account_balance = 150.75

# Boolean: Storing a True/False value
is_active = True

Variables are like labeled containers. You give them a name and use them to store and retrieve different kinds of data, from text to numbers to simple True or False values.

Making Decisions and Repeating Actions

Programs aren't just lists of instructions executed in order. They need to react to different situations. This is where control structures come in. They control the flow of your code.

To make a decision, you use an if statement. It checks if a condition is true and runs a block of code only if it is. You can add elif (else if) to check other conditions, and else to run a block of code if none of the conditions are met.

temperature = 75

if temperature > 80:
    print("It's hot outside.")
elif temperature < 60:
    print("You might need a jacket.")
else:
    print("The weather is pleasant.")

Sometimes you need to repeat an action. That's what loops are for. A for loop is great for when you want to go through a sequence of items, like a list of names, and do something with each one.

tasks = ["Check email", "Call manager", "Write report"]

for task in tasks:
    print(f"To do: {task}")

A while loop is different. It keeps repeating as long as a certain condition is true. It's useful when you don't know exactly how many times you need to loop.

countdown = 3

while countdown > 0:
    print(countdown)
    countdown = countdown - 1

print("Liftoff!")

Packaging Your Code

As your programs get bigger, you'll find yourself writing the same bit of code over and over. Functions let you package a block of code, give it a name, and reuse it whenever you want. This keeps your code organized and easy to read.

function

noun

A reusable block of code that performs a specific task. It can take in data (arguments) and send data back (return a value).

You define a function using the def keyword, followed by the function's name and parentheses. Inside the parentheses, you can specify parameters, which are variables that hold the data you pass into the function. The return keyword sends a value back out.

# Define a function that adds two numbers
def add_numbers(num1, num2):
    result = num1 + num2
    return result

# Call the function with two arguments
sum_result = add_numbers(5, 10)

print(sum_result) # This will print 15

Functions help you write cleaner, more modular code. Define it once, use it many times.

Handling the Unexpected

What happens if your code tries to do something impossible, like divide a number by zero or convert the word "apple" into a number? The program will crash with an error. This is where error handling comes in.

Python gives you a way to anticipate and manage potential errors using a try...except block. You put the code that might cause an error inside the try block. If an error occurs, the code inside the except block is executed, and the program continues running instead of crashing.

user_input = "hello"

try:
    # This line will cause an error
    number = int(user_input)
    print(f"The number is {number}")
except ValueError:
    # This block runs because of the error
    print("That's not a valid number!")

Using try...except makes your code more robust and user-friendly. It can handle bad input or unexpected situations gracefully.

Quiz Questions 1/5

What is the data type of the value 10.5 in Python?

Quiz Questions 2/5

Consider the following code snippet:

temperature = 25
if temperature > 30:
    print("It's hot!")
elif temperature > 20:
    print("It's warm.")
else:
    print("It's cool.")

What will be printed to the console?