No history yet

Python Basics

Storing Your Information

Think of a variable as a labeled box where you can store information. You give the box a name, and you can put something inside it. Later, you can look inside the box by using its name, or you can even replace the contents with something new.

Variable

noun

A symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name.

The information you store comes in different types. Python is smart about figuring out the type on its own. The most common data types you'll use are:

  • Integers: Whole numbers, like 5, -10, or 0.
  • Floats: Numbers with a decimal point, like 3.14 or -0.5.
  • Strings: Text, which you write inside single (' ') or double (" ") quotes. For example, "Hello, world!".
  • Booleans: Represents one of two values: True or False. They're useful for making decisions.
# An integer
student_count = 25

# A float
average_score = 88.5

# A string
course_name = "Introduction to Data Analysis"

# A boolean
is_enrolled = True

print(student_count)
print(course_name)

Making Decisions and Repeating Actions

Programs often need to make decisions. Just like you might check the weather before deciding to take an umbrella, a program can check a condition before running a specific piece of code. This is done with if statements.

You can provide a path for when the condition is true, and an alternative path for when it isn't using else. If you have multiple conditions to check, you can use elif (short for "else if").

temperature = 75

if temperature > 80:
    print("It's a hot day!")
elif temperature < 60:
    print("Better bring a jacket.")
else:
    print("The weather is perfect.")

What about repeating tasks? Instead of writing the same code over and over, you can use a loop. A for loop is great for when you want to go through a sequence of items, like a list of names or numbers, and do something with each one.

# This loop will run 3 times
for student in ["Alice", "Bob", "Charlie"]:
    print(f"Sending email to {student}...")

A while loop is different. It 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 = 3

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

print("Liftoff!")

Use a for loop when you have a specific list of items to iterate through. Use a while loop when you want to repeat an action until a condition changes.

Organizing Your Code

As your programs get bigger, you'll want to keep them organized. Functions are a key tool for this. A function is a named, reusable block of code that performs a specific task. Think of it like a recipe: it has a name, it might need some ingredients (called arguments), and it produces a result.

Function

noun

A block of organized, reusable code that is used to perform a single, related action.

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

# Call the function with two arguments
sum_result = add_numbers(5, 3)
print(sum_result) # This will print 8

Python also comes with many pre-written functions organized into modules. A module is simply a file containing Python code. You can bring the code from a module into your program using the import statement. For example, the math module contains functions for advanced mathematical operations.

# Import the math module to get access to its functions
import math

# Use the sqrt function from the math module
number = 64
square_root = math.sqrt(number)

print(f"The square root of {number} is {square_root}.")

Handling Errors

Sometimes, code doesn't work as planned. An error, or an exception, can happen for many reasons, like trying to divide by zero or accessing a file that doesn't exist. Instead of letting these errors crash your program, you can handle them gracefully.

Python's try...except block is the way to do this. You put the code that might cause an error in the try block. If an error occurs, the code in the except block is run, and the program continues instead of stopping.

numerator = 10
denominator = 0

try:
    # This line will cause a ZeroDivisionError
    result = numerator / denominator
    print(result)
except ZeroDivisionError:
    # This block runs because the error happened
    print("Error: You can't divide by zero!")

print("The program continued without crashing.")

Good error handling makes your code more robust and reliable. It anticipates problems and gives your program a plan for what to do when they occur.

With these fundamentals, you have the building blocks to start writing Python scripts for data analysis. You can store data, control how your program flows, organize your logic, and handle unexpected issues.

Quiz Questions 1/5

In programming, what is the best analogy for a variable?

Quiz Questions 2/5

What will be the output of the following Python code?

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