Core Concepts
Syntax Basics
Python uses indentation to define code blocks instead of braces. This makes the code clean and readable.
def greet_user(name):
# Print a greeting message
print(f"Hello, {name}!")
if __name__ == "__main__":
user_name = "Alice"
greet_user(user_name)
Loops
Python provides for and while loops to iterate over sequences and execute code repeatedly.
# For loop example
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
# While loop example
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
Functions
Functions are reusable blocks of code that perform specific tasks. They help organize and structure your programs.
def calculate_area(length, width):
"""Calculate area of rectangle"""
area = length * width
return area
# Using the function
rect_area = calculate_area(5, 3)
print(f"Area: {rect_area}")
Data Types in Python
Python has several built-in data types that are essential for programming:
| Type | Example | Description |
|---|---|---|
| Integer | 42 | Whole numbers without decimal points |
| Float | 3.14 | Numbers with decimal points |
| String | "Hello" | Text enclosed in quotes |
| List | [1, 2, 3] | Ordered, mutable collection |
| Dictionary | {'key': 'value'} | Key-value pairs |
# Examples of different data types
my_int = 42
my_float = 3.14
my_string = "Python is great!"
my_list = ["apple", "banana", "cherry"]
my_dict = {"name": "John", "age": 30}
print(type(my_int)) # <class 'int'>
print(my_list[1]) # banana
print(my_dict["name"]) # John
Practice Exercise
Create a simple program that demonstrates multiple concepts:
def analyze_numbers(numbers):
"""
Analyze a list of numbers and return statistics
"""
total = 0
count = 0
for num in numbers:
if num > 0: # Only positive numbers
total += num
count += 1
average = total / count if count > 0 else 0
result = {
"sum": total,
"average": round(average, 2),
"count": count
}
return result
# Test the function
test_data = [10, -5, 20, 0, 15, -3, 25]
stats = analyze_numbers(test_data)
print(stats) # {'sum': 70, 'average': 14.0, 'count': 4}