Learn Python
Beginner Python
Conditions, loops, collections, functions, comprehensions and exceptions.
Conditions and loops
score = 82
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
else:
grade = "C"
for number in range(1, 6):
print(number, number ** 2)Use while when the number of repetitions is not known in advance. Make sure its condition can eventually become false.
Collections
names = ["Ada", "Guido"]
point = (10, 20)
roles = {"admin", "editor"}
user = {"name": "Ada", "active": True}Functions
def greet(name: str, excited: bool = False) -> str:
message = f"Hello, {name}"
return message + "!" if excited else messageGive a function one clear responsibility. Return data instead of printing deep inside business logic.
Exceptions
try:
age = int(input("Age: "))
except ValueError:
print("Please enter a whole number")
else:
print(f"Next year: {age + 1}")Catch specific exceptions and only wrap the operation that can fail.
Exercise
Create a login loop with three attempts. Store users in a dictionary and never print or store plain-text passwords in a real application.