Python Syntax Summary
Python Syntax Summary
2. Control Flow
# if-elif-else
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
# for loop
for fruit in fruits:
print(fruit)
# while loop
i = 0
while i < 5:
print(i)
i += 1
3. Functions
def greet(name):
return "Hello, " + name
print(greet("Alice"))
def bark(self):
print(self.name + " says woof!")
my_dog = Dog("Rex")
my_dog.bark()
5. Built-in Functions
Python Syntax Summary
len(), type(), int(), str(), float(), range(), sum(), max(), min()
6. List Comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
7. Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This runs no matter what")
8. File I/O
# Write to a file
with open("file.txt", "w") as f:
f.write("Hello world")
9. Importing Modules
import math
print(math.sqrt(16))
nums = [1, 2, 3]
squares = list(map(lambda x: x**2, nums)) # [1, 4, 9]