A statement in Python is a complete line of code that performs an action. Each line in your program is typically a statement. Here are some examples:
# These are all statements
name = "Alice"
print("Hello!")
if x > 0:
print("Positive number")
Types of Statements
Assignment statements (x = 5)
Function calls (print("Hello"))
Conditional statements (if, elif, else)
Loop statements (for, while)
Import statements (import math)
2. Expressions
An expression is a combination of values, variables, operators, and function calls that can be evaluated to produce a value. Examples:
# These are expressions
2 + 3 # evaluates to 5
name.upper() # evaluates to uppercase version of name
len("hello") # evaluates to 5
x > 0 # evaluates to True or False
📝 Exercise 1: Function Definition (1 point)
Write a function that takes a name as a parameter and returns a greeting:
# Write your code here
3. Functions and Methods
Functions are reusable blocks of code that perform specific tasks. Methods are functions that belong to objects.
Functions
print("Hello") # Built-in function
len("Python") # Built-in function
abs(-5) # Built-in function
def greet(): # User-defined function
print("Hi!")
Parameters are variables defined in a function's declaration. Arguments are the actual values passed to the function when it's called.
# name and age are parameters
def greet(name, age):
print(f"Hello {name}, you are {age} years old!")
# "Alice" and 25 are arguments
greet("Alice", 25)
Parameter Types
Required parameters (must be provided)
Optional parameters (have default values)
Keyword arguments (specified by name)
Variable-length arguments (*args, **kwargs)
5. Return Values
Functions can send back values using the return statement. These values can then be used in other parts of your program.
def calculate_area(width, height):
return width * height
# The return value is stored in area
area = calculate_area(5, 3)
print(f"The area is {area} square units")
📝 Exercise 2: Parameter Types (1 point)
Create a function that takes two parameters (name and age) and prints a formatted message:
# Write your code here
📝 Exercise 3: Return Values (1 point)
Write a function that calculates the area of a rectangle:
# Write your code here
📝 Exercise 4: Function Expression (1 point)
Create a function that returns the maximum of two numbers: