Statistical Analysis with Python
Python Basics
Python's Building Blocks
Python is known for its clean and readable syntax. Unlike many other languages that use brackets or keywords to define blocks of code, Python uses indentation. This might seem strange at first, but it forces code to be organized and easy to read.
Let's start with the most basic operation: displaying information. The print() function is used to output text or the value of a variable to the console. It's the standard way to see what your program is doing.
print("Hello, World!")
Variables are names that act as containers for storing data. You can assign a value to a variable using the equals sign (=). Python automatically figures out the data type based on the value you assign.
The most common data types you'll encounter are:
- Integers (
int): Whole numbers, like5,-10, or2024. - Floats (
float): Numbers with a decimal point, like3.14or-0.5. - Strings (
str): Sequences of characters, used for text. They must be enclosed in single (') or double (") quotes. - Booleans (
bool): Represent one of two values:TrueorFalse. They are crucial for making decisions in your code.
# Assigning values to variables
student_count = 25 # An integer
gpa = 3.8 # A float
course_name = "Statistics" # A string
is_enrolled = True # A boolean
# Printing the values
print(student_count)
print(course_name)
Making Decisions and Repeating Actions
Programs often need to make decisions based on certain conditions. This is handled with control structures. The most common is the if-elif-else statement. It allows your program to execute different blocks of code depending on whether a condition is true or false.
grade = 85
if grade >= 90:
print("Excellent!")
elif grade >= 80:
print("Good job.")
else:
print("Keep trying!")
# Output: Good job.
Sometimes you need to repeat an action multiple times. This is where loops come in. A for loop is used to iterate over a sequence (like a list of numbers), executing a block of code for each item in the sequence.
# This loop will run 5 times
for i in range(5): # range(5) generates numbers from 0 to 4
print(f"This is repetition number {i}")
A while loop, on the other hand, continues to execute a block of code as long as a certain condition remains true. You have to make sure the condition eventually becomes false, or you'll create an infinite loop!
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1 # Decrease the counter
print("Liftoff!")
Packaging Code with Functions
As your programs get more complex, you'll find yourself writing the same piece of code over and over. Functions are reusable blocks of code that perform a specific task. They help you organize your code, make it more readable, and avoid repetition.
You define a function using the def keyword, followed by the function's name, parentheses (), and a colon :. The code inside the function must be indented.
# Define a function to greet someone
def greet(name):
message = f"Hello, {name}!"
return message
# Call the function and print its return value
greeting = greet("Alice")
print(greeting)
# Output: Hello, Alice!
In this example,
nameis a parameter, a placeholder for the data we want the function to work with. When we call the function withgreet("Alice"), the value"Alice"is the argument that gets passed into thenameparameter.
Interacting with the User
Besides printing output, your programs can also receive input from the user. The input() function pauses the program and waits for the user to type something and press Enter.
It's important to remember that input() always returns the user's input as a string. If you need to treat the input as a number, you have to convert it first using functions like int() or float().
# Ask the user for their name
user_name = input("What is your name? ")
# Ask for their age and convert it to an integer
user_age_str = input("How old are you? ")
user_age = int(user_age_str)
years_to_100 = 100 - user_age
print(f"Hello, {user_name}. You will be 100 in {years_to_100} years.")
This covers the core building blocks of Python. With variables, data types, control structures, and functions, you have the tools to write simple yet powerful programs to solve all sorts of problems.
In Python, how are blocks of code, such as the body of a function or a loop, defined?
What is the data type of the variable user_age after this code runs?
user_age = input("Enter your age: ")