🔄 Quick Recap (Day 4)
You learned about variables and data types (int, float, str, bool).
You practiced checking types and converting between them.
🎯 What You’ll Learn Today
Why consistent naming and formatting matter.
Basic naming conventions for variables and functions.
How to spot and fix simple syntax errors.
📖 Why Code Style Matters
Just like neat handwriting makes a school notebook easier to read, consistent code style helps anyone (including future you) understand your programs quickly:
Readability: Well-organized code is easier to follow and maintain.
Collaboration: When many people work on code, everyone follows the same conventions.
Debugging: Clean code helps spot mistakes faster.
Python’s official style guide, PEP 8, recommends using:
snake_case for variable and function names (lowercase with underscores).
4 spaces for indentation, not tabs.
Line length limited to ~79 characters so lines don’t wrap awkwardly.
📖 Naming Conventions
Variables & functions:
user_age,calculate_total()Constants (values that don’t change):
PI = 3.14,MAX_RETRIES = 5Classes (later lessons):
MyClass(CamelCase)
Example:
# bad style
X=42
def f(x):return x*2
# good style following PEP 8
user_age = 42
def double(number):
return number * 2Notice spaces around = and around operators.
📖 Spotting Syntax Errors
Python will show an error if it can’t understand your code. Common mistakes include:
Missing colon
:afterif,for,def.Mismatched quotes or parentheses.
Indentation problems (mixing spaces and tabs).
Example error:
File "example.py", line 2
print("Hello World!)
^
SyntaxError: EOL while scanning string literalThis means you started a string with " but forgot to close it before the end of the line.
🧙♂️ Take the Wand and Try Yourself
Create a new file
style_test.py.Inside, write two functions with bad style (no spaces, odd names), for example:
def addNumbers(a,b):return a+b result=addNumbers(2,3) print(result)Run
python style_test.pyto confirm it works.Now refactor your code following PEP 8:
Rename to snake_case.
Add spaces around operators and after commas.
Separate function definition and call onto separate lines.
Solution Example (style_test.py):
# style_test.py: improved style
def add_numbers(a, b):
return a + b
result = add_numbers(2, 3)
print(result)Expected output:
5Run:
python style_test.pyOnce you see the correct output and your code looks tidy, you’re mastering code style!
On Day 6, we’ll explore conditional logic with if statements—see you there!