Basic Syntax β
Master Python's fundamental syntax rules including indentation, variables, comments, and code structure
π€ Indentation β
Python uses indentation instead of curly braces {} to define code blocks.
Think of it like this: Just like you indent paragraphs in a letter, Python uses indentation to show which code belongs together.
python
# Correct indentation - code inside the if block
if True:
print("This is indented")
print("This is also indented")
print("All these lines belong to the if block")
print("This line is outside the if block")
# Expected output:
# This is indented
# This is also indented
# All these lines belong to the if block
# This line is outside the if blockRules for Indentation β
- Use 4 spaces per indentation level
- Be consistent throughout your code
- Don't mix tabs and spaces
π¬ Comments β
Single-line Comments: β
python
# This is a comment
print("Hello, World!") # This is also a commentMulti-line Comments (Docstrings): β
python
"""
This is a multi-line comment
or docstring. It's often used
for function documentation.
"""
def my_function():
"""
This function does something amazing.
"""
passπ Variables and Data Types β
Creating Variables: β
python
# Variables are created when you assign a value
name = "Alice"
age = 25
height = 5.6
is_student = TrueVariable Naming Rules: β
- Must start with a letter or underscore
- Can contain letters, numbers, and underscores
- Case-sensitive (
nameandNameare different) - Cannot use Python keywords
python
# Valid variable names
user_name = "John"
age2 = 30
_private = "secret"
# Invalid variable names
# 2age = 30 # Cannot start with number
# user-name = "John" # Cannot contain hyphens
# class = "Python" # Cannot use keywordsπ― Python Keywords β
Python has reserved words that cannot be used as variable names:
python
# Common keywords
and, or, not, if, else, elif, for, while, def, class,
import, from, as, try, except, finally, with, lambda,
return, pass, break, continue, True, False, Noneπ Basic Data Types β
python
# String
name = "Python"
message = 'Hello, World!'
# Integer
age = 25
count = 0
# Float
price = 19.99
temperature = -5.5
# Boolean
is_active = True
is_complete = False
# None (represents absence of value)
result = Noneπ Checking Types β
python
name = "Alice"
age = 25
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>π Practice Exercise β
Try this simple program:
python
# Personal information
first_name = "John"
last_name = "Doe"
age = 30
is_programmer = True
# Print information
print("Name:", first_name, last_name)
print("Age:", age)
print("Is programmer:", is_programmer)π― Key Takeaways β
- Python uses indentation to define code structure
- Use 4 spaces for indentation
- Comments start with
#or use"""for multi-line - Variables are created by assignment
- Python is case-sensitive
- Follow naming conventions for readable code
Continue to: Data Types and Variables β