Conditional statements allow your program to make decisions based on certain conditions.
if, elif, else
# Simple if statement
age = 18
if age >= 18:
print("You are an adult!")
print("You can vote!")
print("Program continues...")
# if-else statement
temperature = 25
if temperature > 30:
print("It's hot outside!")
else:
print("It's not too hot.")
# if-elif-else statement
score = 85
if score >= 90:
grade = "A"
print("Excellent!")
elif score >= 80:
grade = "B"
print("Good job!")
elif score >= 70:
grade = "C"
print("Not bad!")
else:
grade = "F"
print("Need improvement!")
print(f"Your grade is: {grade}")
# Nested conditionals
age = 20
has_license = True
if age >= 18:
if has_license:
print("You can drive!")
else:
print("You need a license to drive.")
else:
print("You are too young to drive.")
Loops allow you to execute a block of code repeatedly.
for Loop
# Basic for loop
print("Counting from 1 to 5:")
for i in range(1, 6):
print(i)
# Range with step
print("\nEven numbers from 2 to 10:")
for i in range(2, 11, 2):
print(i)
# Countdown
print("\nCountdown:")
for i in range(5, 0, -1):
print(i)
print("Blast off!")
# Iterating through a string
word = "Python"
print("Letters in 'Python':")
for letter in word:
print(letter)
# Iterating through a list
fruits = ["apple", "banana", "cherry"]
print("\nFruits:")
for fruit in fruits:
print(f"I like {fruit}!")
while Loop
# Basic while loop
count = 1
while count <= 5:
print(f"Count: {count}")
count = count + 1 # or count += 1
print("Loop finished!")
# Using break
print("Finding first even number:")
for num in range(1, 10):
if num % 2 == 0:
print(f"Found: {num}")
break # Exit loop immediately
# Using continue
print("\nPrinting odd numbers:")
for num in range(1, 10):
if num % 2 == 0:
continue # Skip to next iteration
print(num)
Lists
Lists are ordered collections of items. They are mutable (can be changed).
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
print("Fruits:", fruits)
print("Numbers:", numbers)
print("Mixed:", mixed)
# Accessing elements
print("\nFirst fruit:", fruits[0])
print("Last fruit:", fruits[-1])
# Modifying lists
fruits.append("orange") # Add to end
print("\nAfter adding orange:", fruits)
fruits.insert(1, "grape") # Insert at position
print("After inserting grape:", fruits)
fruits.remove("banana") # Remove item
print("After removing banana:", fruits)
# List slicing
print("\nFirst two fruits:", fruits[0:2])
print("All fruits:", fruits[:])
Tuples (Concept Only)
Tuples are ordered collections like lists, but they are immutable (cannot be changed).
# Creating tuples
coordinates = (10, 20)
colors = ("red", "green", "blue")
print("Coordinates:", coordinates)
print("Colors:", colors)
# Accessing elements
print("\nX coordinate:", coordinates[0])
print("Y coordinate:", coordinates[1])
# Tuples are immutable - this would cause an error:
# coordinates[0] = 15 # TypeError!
# Unpacking tuples
x, y = coordinates
print(f"\nUnpacked: x = {x}, y = {y}")
Dictionaries (Basic Usage)
Dictionaries store key-value pairs. They are unordered and mutable.
# Creating dictionaries
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
print("Student:", student)
# Accessing values
print("\nName:", student["name"])
print("Age:", student.get("age"))
# Adding/updating values
student["email"] = "[email protected]"
student["age"] = 21
print("\nUpdated student:", student)
# Removing items
del student["grade"]
print("After removing grade:", student)
# Dictionary methods
print("\nKeys:", student.keys())
print("Values:", student.values())
print("Items:", student.items())
Functions are reusable blocks of code that perform a specific task.
What is a Function?
A function is a named block of code that can be called to perform a specific task. Functions help organize code and make it reusable.
Creating and Calling Functions
# Define a function
def greet():
print("Hello, World!")
print("Welcome to Python!")
# Call the function
greet()
greet() # Can call multiple times
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
print("Nice to meet you!")
# Call with different arguments
greet_person("Alice")
greet_person("Bob")
# Function with multiple parameters
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
introduce("Charlie", 25)
# Function that returns a value
def add_numbers(a, b):
result = a + b
return result
# Use the return value
sum_result = add_numbers(5, 3)
print("Sum:", sum_result)
# Another example
def calculate_area(length, width):
area = length * width
return area
room_area = calculate_area(10, 8)
print(f"Room area: {room_area} square feet")
# Function to check if number is even
def is_even(number):
if number % 2 == 0:
return True
else:
return False
print("Is 4 even?", is_even(4))
print("Is 7 even?", is_even(7))
# Function to find maximum of two numbers
def find_max(a, b):
if a > b:
return a
else:
return b
max_num = find_max(10, 20)
print(f"Maximum: {max_num}")
# Function to calculate average
def calculate_average(numbers):
total = sum(numbers)
count = len(numbers)
return total / count
scores = [85, 90, 78, 92, 88]
avg = calculate_average(scores)
print(f"Average score: {avg}")