Learn how to use if, elif, and else to control the flow of your Python programs.
# Example
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Master Python's for and while loops, and learn how to use break and continue for control flow.
# For loop
for i in range(5):
print(i)
# While loop
n = 3
while n > 0:
print(n)
n -= 1
# Break and continue
for i in range(5):
if i == 3:
break
if i == 1:
continue
print(i)
Understand how to define and use functions, pass parameters, and return values in Python.
# Function definition
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Explore essential built-in functions like len, range, enumerate, zip, map, and filter.
# len, range, enumerate
lst = [10, 20, 30]
print(len(lst))
for idx, val in enumerate(lst):
print(idx, val)
# zip
names = ["A", "B"]
ages = [20, 21]
for n, a in zip(names, ages):
print(n, a)
# map, filter
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x%2==0, nums))
print(squares)
print(evens)
Learn how to read input from the console and write to files in Python.
# Input from user
name = input("Enter your name: ")
print("Hello,", name)
# Write to file
with open("output.txt", "w") as f:
f.write("Hello, file!\n")
# Read from file
with open("output.txt") as f:
print(f.read())
Handle errors gracefully using try, except, finally, and raise in Python.
# try, except, finally, raise
try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
finally:
print("Done.")