No history yet

Python Fundamentals

Variables and Data Types

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). In Python, these values come in different types, and the program treats them differently based on what they are.

The most common data types are:

  • Integers (int): Whole numbers, like 10, -5, or 0.
  • Floats (float): Numbers with decimal points, like 3.14 or -0.5.
  • Strings (str): Text, enclosed in single or double quotes, like 'hello' or "world".
  • Booleans (bool): Represent truth values. They can only be True or False.
# Assigning values to variables
user_age = 25              # An integer
item_price = 19.99         # A float
user_name = "Alex"         # A string
is_logged_in = True        # A boolean

# You can print them to see their values
print(user_name)
print(item_price)

Making Decisions and Repeating Actions

Programs often need to make decisions or repeat actions. Control structures let you manage this flow. Conditionals use if, elif (short for "else if"), and else to run code only when certain conditions are met.

score = 85

if score >= 90:
    print("You got an A!")
elif score >= 80:
    print("You got a B.")
else:
    print("You can do better!")

# Output will be: You got a B.

In Python, indentation is not just for looks—it's how you group code. The lines indented under an if, elif, or else statement are the ones that will execute if the condition is true.

Loops are for repeating a block of code. A for loop is great for iterating over a sequence of items, like numbers in a range or characters in a string.

# This loop runs 5 times, for numbers 0 through 4
for i in range(5):
    print(f"The current number is {i}")

A while loop runs as long as its condition remains true. It's useful when you don't know in advance how many times you need to repeat.

count = 3

while count > 0:
    print(f"{count}...")
    count = count - 1  # Decrease the count each time

print("Liftoff!")

Building with Reusable Blocks

As your programs get more complex, you don't want to repeat the same code over and over. Functions are reusable blocks of code that perform a single, specific task. You define a function once and can call it whenever you need it.

# Define a function that takes a name and returns a greeting
def greet(name):
    return f"Hello, {name}!"

# Call the function with different arguments
message_one = greet("Alice")
message_two = greet("Bob")

print(message_one)
print(message_two)

Sometimes, the functions you need already exist. Python has a rich standard library of modules, which are files containing functions and variables you can use. You just have to import the module to access its tools.

# Import the 'math' module to use its functions
import math

# Calculate the square root of 81
result = math.sqrt(81)

print(result)  # Output: 9.0

Handling the Unexpected

Errors, called exceptions in Python, happen. A user might enter text where a number is expected, or you might try to divide by zero. Instead of letting these errors crash your program, you can handle them gracefully 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.

For example, let's try converting user input to a number. If the user types "abc", a ValueError will occur, but our program will handle it.

try:
    user_input = input("Enter a number: ")
    number = int(user_input)
    print(f"Your number squared is {number**2}")
except ValueError:
    print("That wasn't a valid number. Please try again.")

Now that you've got a handle on these core concepts, let's test your knowledge.

Quiz Questions 1/5

In Python, which data type is used to store a whole number like 42?

Quiz Questions 2/5

What is the primary purpose of a for loop?

These building blocks—variables, control structures, functions, and error handling—are the foundation of almost everything you'll do in Python.