Python is a high-level, interpreted programming language known for its readability and versatility. It combines object-oriented, functional, and procedural programming paradigms with a clean syntax structure.
Basic Syntax Elements
Indentation Rules
Python uses whitespace indentation to define code blocks instead of curly braces:
if x > 5:
print("Greater than 5")
y = x * 2
Note: The number of spaces must be consistant within each block.
Comenting Code
Single-line comments use #:
# Calculate total price
total = price * quantity
Multi-line comments use triple quotes:
"""
This function calculates
the area of a rectangle
given width and height
"""
Operators Overview
Data Types
Python has several built-in data types:
- Immutable: int, float, bool, str, tuple
- Mutable: list, dict, set
Type checking examples:
num = 42
print(type(num)) # Output: <class>
print(isinstance(num, int)) # Output: True</class>
Variable Declaration
Variables are created when first assigned:
counter = 0
message = "Hello"
is_valid = True
Naming rules:
- Start with letter or underscore
- Contain letters, numbers, underscores
- Case-sensitive
Control Flow Structures
Conditional Statements
if temperature > 30:
print("Hot day")
elif temperature > 20:
print("Warm day")
else:
print("Cool day")
Loop Constructs
While loop example:
count = 0
while count < 5:
print(count)
count += 1
For loop example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Loop Control Statements
# Break example
for num in range(10):
if num == 5:
break
print(num)
# Continue example
for num in range(10):
if num % 2 == 0:
continue
print(num)
The pass statemant acts as a placeholder:
def empty_function():
pass