Python Fundamentals
Master the basics of Python programming including syntax, variables, data types, and operators
Python Fundamentals
Master Python programming basics with free flashcards and interactive practice that reinforce core concepts. This lesson covers variables and data types, control flow structures, functions, and basic data structures—essential building blocks for writing effective Python code.
💻 Welcome to Python Fundamentals!
Python has become one of the world's most popular programming languages, powering everything from web applications to data science and artificial intelligence. Whether you're starting your coding journey or adding Python to your skill set, understanding these fundamental concepts is crucial. This lesson will equip you with the core knowledge needed to write clean, functional Python code.
Core Concepts
1. Variables and Data Types 📊
Variables in Python are containers that store data values. Unlike some programming languages, Python doesn't require explicit type declarations—it uses dynamic typing, meaning the interpreter determines the type automatically.
Basic Data Types:
| Type | Description | Example |
|---|---|---|
| int | Whole numbers | 42, -7, 0 |
| float | Decimal numbers | 3.14, -0.5, 2.0 |
| str | Text (strings) | "Hello", 'Python' |
| bool | True/False values | True, False |
| NoneType | Represents absence of value | None |
Variable Naming Rules:
- Must start with a letter or underscore
- Can contain letters, numbers, and underscores
- Case-sensitive (
nameandNameare different) - Cannot use Python keywords (like
if,for,class)
💡 Tip: Use descriptive variable names like user_age instead of x to make your code more readable.
🧠 Memory Device: Think of variables as labeled boxes—the name is the label, and the value is what's inside the box.
2. Operators ⚡
Python supports various operators to perform operations on variables and values:
Arithmetic Operators:
| Operator | Operation | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division (float) | 5 / 2 | 2.5 |
| // | Floor division (int) | 5 // 2 | 2 |
| % | Modulus (remainder) | 5 % 2 | 1 |
| ** | Exponentiation | 5 ** 2 | 25 |
Comparison Operators:
==(equal to),!=(not equal to)>(greater than),<(less than)>=(greater or equal),<=(less or equal)
Logical Operators:
and(both conditions must be True)or(at least one condition must be True)not(reverses the boolean value)
3. Control Flow Structures 🔀
Control flow determines the order in which code executes. Python uses indentation (not braces) to define code blocks.
If-Elif-Else Statements:
These allow conditional execution of code:
age = 18
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")
For Loops:
Iterate over sequences (lists, strings, ranges):
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While Loops:
Repeat while a condition is True:
count = 0
while count < 5:
print(count)
count += 1
⚠️ Warning: Always ensure while loops have a way to terminate, or you'll create an infinite loop!
🧠 Memory Device - "FEW": For iterating over Elements, While when the condition is uncertain.
4. Functions 🔧
Functions are reusable blocks of code that perform specific tasks. They help organize code and avoid repetition.
Defining Functions:
def greet(name):
"""This function greets the person passed in as a parameter"""
return f"Hello, {name}!"
result = greet("Alice")
print(result) # Output: Hello, Alice!
Function Components:
def: Keyword to define a function- Function name: Follows variable naming rules
- Parameters: Input values (optional)
- Docstring: Documentation string (optional but recommended)
return: Sends a value back to the caller (optional)
Default Parameters:
def power(base, exponent=2):
return base ** exponent
print(power(5)) # Output: 25 (uses default exponent=2)
print(power(5, 3)) # Output: 125
💡 Tip: Use docstrings (triple quotes) to document what your function does—your future self will thank you!
5. Basic Data Structures 📦
Python provides built-in data structures to organize collections of values:
Lists (ordered, mutable):
numbers = [1, 2, 3, 4, 5]
numbers.append(6) # Add to end
numbers[0] = 10 # Modify element
first = numbers[0] # Access by index
Tuples (ordered, immutable):
coordinates = (10, 20)
x, y = coordinates # Unpacking
# coordinates[0] = 5 # ERROR: Can't modify tuples
Dictionaries (key-value pairs):
student = {
"name": "John",
"age": 20,
"grade": "A"
}
print(student["name"]) # Output: John
student["age"] = 21 # Modify value
Sets (unordered, unique elements):
unique_numbers = {1, 2, 3, 3, 4} # Duplicates removed
print(unique_numbers) # Output: {1, 2, 3, 4}
| Structure | Ordered? | Mutable? | Duplicates? |
|---|---|---|---|
| List | ✓ | ✓ | ✓ |
| Tuple | ✓ | ✗ | ✓ |
| Dictionary | ✓ (3.7+) | ✓ | Keys: ✗ |
| Set | ✗ | ✓ | ✗ |
🔧 Try this: Create a list of your favorite foods, then use a for loop to print each one!
Examples with Explanations
Example 1: Temperature Converter 🌡️
def celsius_to_fahrenheit(celsius):
"""Convert Celsius temperature to Fahrenheit"""
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
# Test the function
temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C is {temp_f}°F") # Output: 25°C is 77.0°F
Explanation: This function demonstrates:
- Function definition with a parameter
- Arithmetic operations
- The
returnstatement - F-strings for formatted output (note the
fbefore the string)
Example 2: Grade Calculator 📝
def calculate_grade(score):
"""Determine letter grade based on numeric score"""
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
scores = [95, 82, 76, 58, 91]
for score in scores:
grade = calculate_grade(score)
print(f"Score: {score} → Grade: {grade}")
Explanation: This example shows:
- Conditional logic with if-elif-else
- For loop iterating over a list
- Function calls within a loop
- Multiple return statements (function exits at first match)
🤔 Did you know? Python evaluates elif conditions in order and stops at the first True condition, making the order important!
Example 3: Shopping Cart with Dictionary 🛒
# Create a shopping cart
cart = {
"apple": 2.50,
"banana": 1.20,
"orange": 3.00
}
# Add a new item
cart["grape"] = 4.50
# Calculate total
total = 0
for item, price in cart.items():
print(f"{item}: ${price}")
total += price
print(f"\nTotal: ${total:.2f}") # Output: Total: $11.20
Explanation: This demonstrates:
- Dictionary creation and modification
- The
.items()method to iterate over key-value pairs - Variable accumulation in a loop
- String formatting with
.2ffor 2 decimal places
Example 4: List Comprehension and Filtering 🔍
# Traditional approach
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers) # Output: [2, 4, 6, 8, 10]
# Pythonic approach using list comprehension
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]
# Square even numbers
squared_evens = [num**2 for num in numbers if num % 2 == 0]
print(squared_evens) # Output: [4, 16, 36, 64, 100]
Explanation: This showcases:
- Traditional loop with conditional append
- List comprehension: a concise way to create lists
- Combining filtering (if condition) with transformation (expression)
- The modulus operator
%to check for even numbers
💡 Tip: List comprehensions are more "Pythonic" (idiomatic Python style) and often faster than traditional loops.
Common Mistakes ⚠️
1. Indentation Errors
# ❌ WRONG
if True:
print("This will cause an IndentationError")
# ✅ CORRECT
if True:
print("Properly indented")
Why it matters: Python uses indentation to define code blocks. Use 4 spaces (not tabs) as the standard.
2. Mutable Default Arguments
# ❌ WRONG - Don't use mutable defaults!
def add_item(item, my_list=[]):
my_list.append(item)
return my_list
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] - Unexpected!
# ✅ CORRECT
def add_item(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
print(add_item(1)) # [1]
print(add_item(2)) # [2] - As expected
Why it matters: Default mutable arguments are created once and shared across function calls, leading to unexpected behavior.
3. Using == vs is
# For None, use 'is'
value = None
if value is None: # ✅ CORRECT
print("Value is None")
if value == None: # ⚠️ Works but not recommended
print("Value is None")
# For values, use '=='
if value == 0: # ✅ CORRECT for value comparison
print("Zero")
Why it matters: is checks identity (same object), == checks equality (same value). For None, True, and False, always use is.
4. Modifying List While Iterating
numbers = [1, 2, 3, 4, 5]
# ❌ WRONG
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # Can skip elements!
# ✅ CORRECT - Iterate over a copy
for num in numbers[:]:
if num % 2 == 0:
numbers.remove(num)
# ✅ BETTER - Use list comprehension
numbers = [num for num in numbers if num % 2 != 0]
5. Variable Scope Confusion
x = 10
def modify_x():
x = 5 # Creates a local variable, doesn't modify global x
print(x) # Prints 5
modify_x()
print(x) # Still prints 10
# To modify global variable:
def modify_x_global():
global x
x = 5
modify_x_global()
print(x) # Now prints 5
Why it matters: Variables created inside functions are local by default. Use global keyword carefully (or better yet, return values instead).
Key Takeaways 🎯
- Variables store data and are dynamically typed in Python
- Indentation is critical—it defines code structure, not just formatting
- Functions make code reusable and organized; use descriptive names and docstrings
- Lists are mutable and ordered; tuples are immutable
- Dictionaries store key-value pairs for fast lookups
- For loops iterate over sequences; while loops run while conditions are true
- List comprehensions provide concise syntax for creating lists
- Always test edge cases and watch for common pitfalls like mutable defaults
🌍 Real-world analogy: Think of Python fundamentals as the foundation of a house. You can build different structures (applications) on top, but without solid fundamentals, everything else becomes unstable.
📚 Further Study
- Python Official Tutorial: https://docs.python.org/3/tutorial/
- Real Python - Python Basics: https://realpython.com/tutorials/basics/
- Python Style Guide (PEP 8): https://pep8.org/
📋 Quick Reference Card
| Concept | Syntax | Example |
|---|---|---|
| Variable | name = value | age = 25 |
| If statement | if condition: | if x > 0: |
| For loop | for item in sequence: | for i in range(5): |
| While loop | while condition: | while count < 10: |
| Function | def name(params): | def add(a, b): |
| List | [item1, item2] | nums = [1, 2, 3] |
| Dictionary | {key: value} | data = {"name": "Jo"} |
| String format | f"{variable}" | f"Age: {age}" |
Key Operators:
- Arithmetic:
+-*///%** - Comparison:
==!=<><=>= - Logical:
andornot - Membership:
innot in
Remember: Python uses 4 spaces for indentation (PEP 8 standard)