Control Flow¶
Conditionals¶
if-else
¶
if-elif-else
¶
if temperature > 25:
print("It's hot!")
elif temperature > 15:
print("It's warm.")
else:
print("It's cold.")
Ternary Operator¶
Loops¶
for
-loop¶
The for
loop is used to iterate over a sequence:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
enumerate
¶
The enumerate()
function gives both the index and the corresponding element:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
range
¶
The range()
function generates a sequence of numbers:
start
: Starting value (default is0
).stop
: End of the sequence (exclusive).step
: Increment or decrement (default is1
).
Basic Range¶
Custom Start and Stop¶
Step Values¶
Reverse Range¶
Exception Handling¶
Basic Exception Handling¶
try
blocks allow you to test a block of code for errors, while the except
block lets you handle the error gracefully without stopping the program.
Multiple Exception Types¶
You can catch multiple exceptions to handle different error types distinctly:
try:
# Code that might raise different exceptions
except ValueError:
print("Value error occurred.")
except ZeroDivisionError:
print("Division by zero.")
finally
Block¶
finally
ensures that a block of code is executed, regardless of an exception being thrown or not. It's often used for cleaning up resources.
try:
# Risky code
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("This block executes no matter what.")