15 min read
Python Crash Course I
Syntax, basic data types, control flow, and defining functions
What You'll Learn
- Python syntax and structure
- Basic data types
- Control flow (if/else, loops)
- Functions
- Basic operations
Python Basics
Python syntax:
code.py
# Comments start with #
print("Hello, World!") # Output to console
# Variables - no declaration needed
name = "Data Analyst"
age = 25
salary = 75000.50
is_employed = TrueData Types
Numeric types:
code.py
# Integer
count = 100
# Float
price = 99.99
# Operations
total = count * price
average = total / countStrings:
code.py
# Creating strings
message = "Hello"
name = 'Python'
# String operations
full_message = message + " " + name
repeated = message * 3
# String methods
upper_case = message.upper()
length = len(message)Lists:
code.py
# Creating lists
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True]
# Accessing elements
first = numbers[0]
last = numbers[-1]
# List methods
numbers.append(6)
numbers.remove(3)
length = len(numbers)Dictionaries:
code.py
# Creating dictionaries
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# Accessing values
name = person["name"]
age = person.get("age")
# Adding/updating
person["email"] = "john@example.com"Control Flow
If statements:
code.py
age = 25
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")For loops:
code.py
# Loop through list
for number in [1, 2, 3, 4, 5]:
print(number)
# Loop with range
for i in range(5):
print(i)
# Loop through dictionary
for key, value in person.items():
print(f"{key}: {value}")While loops:
code.py
count = 0
while count < 5:
print(count)
count += 1Functions
Defining functions:
code.py
def greet(name):
return f"Hello, {name}!"
# Calling function
message = greet("Python")
print(message)Functions with multiple parameters:
code.py
def calculate_total(price, quantity, tax_rate=0.1):
subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
return total
# Calling with positional arguments
total1 = calculate_total(10, 5)
# Calling with keyword arguments
total2 = calculate_total(price=10, quantity=5, tax_rate=0.15)Return multiple values:
code.py
def get_stats(numbers):
total = sum(numbers)
average = total / len(numbers)
return total, average
total, avg = get_stats([1, 2, 3, 4, 5])List Comprehensions
Basic syntax:
code.py
# Traditional way
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension
squares = [x**2 for x in range(10)]
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]Common Operations
String formatting:
code.py
name = "Python"
version = 3.9
# f-strings (preferred)
message = f"Welcome to {name} {version}"
# .format()
message = "Welcome to {} {}".format(name, version)Working with files:
code.py
# Reading file
with open('data.txt', 'r') as file:
content = file.read()
# Writing file
with open('output.txt', 'w') as file:
file.write("Hello, World!")Practice Exercise
Create a function that calculates basic statistics:
code.py
def calculate_statistics(numbers):
"""Calculate mean, min, max of a list"""
if not numbers:
return None
total = sum(numbers)
count = len(numbers)
mean = total / count
minimum = min(numbers)
maximum = max(numbers)
return {
'mean': mean,
'min': minimum,
'max': maximum,
'count': count
}
# Test it
data = [10, 20, 30, 40, 50]
stats = calculate_statistics(data)
print(stats)Key Takeaways
- Python uses indentation for code blocks
- Lists are mutable, strings are immutable
- Dictionaries store key-value pairs
- Functions make code reusable
- List comprehensions are concise and powerful
Next Steps
Now let's learn how to import and export data!
Practice & Experiment
Test your understanding by running Python code directly in your browser.