Python Fundamentals for Impact
Python Basics
Storing Information
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 your program.
In Python, the information you store comes in different types. The most common ones are:
- Integers: Whole numbers, like 5, -10, or 100.
- Floats: Numbers with decimal points, like 3.14 or -0.5.
- Strings: Plain text, wrapped in quotes. For example,
"hello"or'world'. - Booleans: Represent truth values. They can only be
TrueorFalse.
# An integer for a person's age
age = 30
# A float for an item's price
price = 19.99
# A string for a name
name = "Alex"
# A boolean to check student status
is_student = True
# We can print these values to see them
print(name)
print(age)
When you run this code, it will print the name "Alex" and the age 30 to the screen. Python automatically knows what type of data each variable holds.
Making Decisions
Programs often need to make choices. Just like you might decide to bring an umbrella if it's raining, a program can execute different code based on whether a condition is true or false. This is done with if, elif (short for "else if"), and else statements.
An
ifstatement checks a condition. If it's true, the code inside it runs. If not, the program skips it and checks the nextelifor moves to theelseblock, which runs if no previous conditions were met.
temperature = 15
if temperature > 25:
print("It's a hot day! Wear shorts.")
elif temperature > 10:
print("It's a bit chilly. A jacket is a good idea.")
else:
print("It's cold! Wear a warm coat.")
In this example, since temperature is 15, the first condition (> 25) is false. The program then checks the elif condition (> 10), which is true. It prints the message about needing a jacket and ignores the else part.
Repeating Actions
Sometimes you need to perform the same action multiple times. Instead of writing the same code over and over, you can use a loop. Python has two main types of loops: for loops and while loops.
A for loop is used when you want to repeat an action for each item in a sequence, like a list of numbers or names.
# A list of chores
chores = ["Wash dishes", "Take out trash", "Walk the dog"]
# Loop through each chore and print it
for chore in chores:
print("To do:", chore)
A while loop, on the other hand, keeps running as long as a certain condition remains true. It's useful when you don't know exactly how many times you need to repeat the action.
# Countdown from 5
countdown = 5
while countdown > 0:
print(countdown)
countdown = countdown - 1 # Decrease the count by 1
print("Blast off!")
Creating Reusable Code
As your programs get bigger, you'll find yourself wanting to reuse chunks of code. Functions let you bundle up a block of code, give it a name, and run it whenever you want just by calling its name. This keeps your code organized and easy to manage.
You define a function using the def keyword. You can also give it inputs, called parameters, to work with. Many functions also return a value as an output.
# Define a function that greets someone
def greet(name):
# This function takes one parameter: name
message = "Hello, " + name + "!"
return message # It returns the new message string
# Call the function with different names
greeting_for_maria = greet("Maria")
greeting_for_sam = greet("Sam")
print(greeting_for_maria)
print(greeting_for_sam)
Handling Errors
Sometimes, code doesn't run as planned. A user might enter text where a number is expected, or you might try to divide a number by zero. These situations cause errors, or "exceptions," that can crash your program.
To prevent this, you can use a try...except block. You put the code that might cause an error in the try block. If an error occurs, the code in the except block runs, and the program continues instead of crashing.
user_input = "abc"
try:
# Try to convert the input to a number
number = int(user_input)
print("The number is:", number)
except ValueError:
# This runs if the conversion fails
print("That's not a valid number!")
Because "abc" cannot be turned into an integer, the try block fails and Python jumps to the except block, printing a helpful message instead of stopping.
Time to test your knowledge on these core concepts.
In programming, what is the best way to describe a variable?
What is the data type of the value 17.5 in Python?
These are the fundamental building blocks of Python. With variables, conditionals, loops, functions, and error handling, you have the tools to start writing your own simple but powerful programs.