Python Syntax Basics
1. Basic Structure
Python uses indentation (typically 4 spaces) to define code blocks.
Example:
if x > 0:
print("Positive")
else:
print("Non-positive")
2. Variables and Data Types
Variables don't require explicit declaration.
x = 10 # int
name = "John" # str
price = 3.14 # float
is_active = True # bool
3. Operators
Arithmetic: +, -, *, /, //, %, **
Comparison: ==, !=, <, >, <=, >=
Logical: and, or, not
Assignment: =, +=, -=
4. Control Flow
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for i in range(5):
Python Syntax Basics
print(i)
while count < 5:
print(count)
count += 1
5. Data Structures
List: fruits = ["apple", "banana", "cherry"]
Dictionary: person = {"name": "Alice", "age": 25}
Tuple: coordinates = (10, 20)
Set: unique_values = {1, 2, 3}
6. Functions
def greet(name):
return "Hello, " + name
7. Importing Modules
import math
print(math.sqrt(16))
8. Comments
# This is a single-line comment
"""
This is a
multi-line comment
"""
9. Classes and Objects
Python Syntax Basics
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy")
my_dog.bark()