Lesson 02 – Python Basics¶
Prerequisites: Review Lesson 00 – Visualizing with Mermaid and Lesson 01 – Markdown Fundamentals to plan and document program flow.
This lesson introduces foundational Python concepts you'll use throughout the curriculum. You'll learn how Python handles syntax, variables, control flow, and functions—plus how to run a script from the command line.
By the end, you’ll be able to write and run basic Python programs with confidence.
1. Python Syntax: The Shape of the Language¶
Python is known for being readable and consistent. Its syntax is simple but strict about structure.
- Indentation defines blocks. Four spaces (not tabs) is the convention.
- Statements end with a newline, not a semicolon.
- Comments begin with
#and go to the end of the line. - Strings can use
'single',"double", or'''triple quotes'''for multi-line blocks.
Example:
# This is a comment
a = 5
b = "hello"
print(a, b) # prints: 5 hello
2. Variables and Data Types: Storing Values¶
Python lets you create variables on the fly—no need for a declaration keyword.
Here are some common data types and how to use them:
count = 10 # int
price = 9.99 # float
name = "Widget" # str
is_active = True # bool
items = ["a", "b", "c"] # list
print(type(count)) # <class 'int'>
Key points:
- Use
type()to inspect a variable’s type. - Variable names are case-sensitive and usually written in
snake_case. - Values can be reassigned to new types—but keep that in mind when debugging.
3. Control Flow and Loops: Making Decisions¶
Python provides standard tools for branching and repetition:
Conditional logic:¶
if condition:
...
elif another_condition:
...
else:
...
Loops:¶
forloops iterate over sequences.whileloops repeat while a condition is true.breakexits the loop early.continueskips the rest of the current iteration.
Example:
for i in range(3):
if i == 1:
continue # skip when i is 1
print(i) # prints 0 and 2
4. Functions: Organizing Logic¶
Functions let you define reusable blocks of logic. They begin with def, use parentheses for parameters, and can return values.
def calculate_discount(price: float, discount_rate: float) -> float:
"""Calculate the discounted price based on the original price and discount rate.
This method applies a percentage discount to the given price and returns
the final amount. It does not handle negative prices or discount rates
greater than 100%.
Args:
price (float): The original price of the item.
discount_rate (float): The discount rate as a percentage (e.g., 15.0 for 15%).
Returns:
float: The discounted price.
Raises:
ValueError: If price is negative or discount_rate is not between 0 and 100.
Examples:
>>> calculate_discount(100.0, 15.0)
85.0
"""
if price < 0 or not 0 <= discount_rate <= 100:
raise ValueError("Invalid input")
return price * (1 - discount_rate / 100)
Why this is good practice:
- Docstrings (triple-quoted strings below the function) describe usage.
- Type hints clarify what each parameter and return value should be.
- Raising exceptions helps catch incorrect input early.
Functions should do one thing clearly. This makes them easier to test and reuse.
5. Running Python Scripts: From Editor to Terminal¶
Once your code is saved, you can execute it from the command line.
Step 1: Save the file¶
# Save as main.py
Step 2: Use a script entry point¶
This prevents your script from running when imported elsewhere:
# main.py
if __name__ == "__main__":
print("Running script")
Step 3: Run it in the terminal¶
python main.py
This command runs your code using the Python interpreter.
6. Git Basics: Version Control Essentials¶
Even small scripts benefit from tracking changes in a Git repository. Git stores each revision so you can experiment freely and revert mistakes.
While Git is commonly used from the command line, GitHub Desktop offers a free graphical interface for managing repositories. It simplifies committing, branching, and syncing if you prefer to avoid terminal commands.
Initialize a repository¶
Start versioning your project folder:
git init
Commit your work¶
Add files and save a snapshot with a message describing the change:
git add .
git commit -m "Initial commit"
Review history¶
List previous commits to see how your project evolved:
git log --oneline
These basics keep your code history organized and make collaboration easier.
7. Practice Exercises¶
Ready to experiment? Try these short challenges. Each one lists a sample input and the output you should see when it works correctly.
Exercise 1: FizzBuzz¶
Print the numbers 1–20. Replace multiples of 3 with Fizz, multiples of
5 with Buzz, and numbers divisible by both with FizzBuzz.
Expected Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Exercise 2: Reverse a String¶
Ask the user for a word and display it backward.
Input: hello
Output: olleh
Exercise 3: Prime Checker¶
Prompt for an integer and print whether it is prime.
Input: 7
Output: 7 is prime
Exercise 4: Word Counter¶
Read a sentence and report how many words it contains.
Input: "open source makes collaboration easy"
Output: 5
Exercise 5: Temperature Converter¶
Convert Celsius to Fahrenheit using the formula F = C * 9/5 + 32.
Input: 100
Output: 212.0
These exercises reinforce basic syntax, loops, and user input. Try implementing them on your own before peeking at the solutions.
🖥 Screencast¶
Want a guided walkthrough? Watch the screencast version of this lesson here: 🎥 Python Basics Video
Additional Resources¶
- Python Basics Cheat Sheet – quick syntax reference.
- GitHub Walkthrough Assignment – step-by-step guide for pushing code to GitHub.
Next Up¶
Take the next step with Lesson 03 – SQL Foundations, where you'll learn to store and query the data your Python scripts produce.