Alien colors
A simple check against a green alien awards 5 points.
AlienColor = 'green'
if AlienColor == 'green':
print("Player gets 5 points.")
Adding an else branch handles other colors, giving 10 points for anything else.
AlienColor = 'green'
if AlienColor == 'green':
print("Player gets 5 points by shooting this alien.")
else:
print("Player gets 10 points.")
An elif chain distinguishes green, yellow, and other colors.
AlienColor = 'green'
if AlienColor == 'green':
print("Player gets 5 points.")
elif AlienColor == 'yellow':
print("Player gets 10 points.")
else:
print("Player gets 15 points.")
Life stages
Using a person's age to print a life stage. Two versions are shown.
age = 24
if age < 2:
print("It's a baby")
elif age >= 2 and age < 4:
print("It's a child")
elif age >= 4 and age < 13:
print("It's a tween")
elif age >= 13 and age < 18:
print("It's a teenager")
elif age >= 18 and age < 65:
print("It's an adult")
else:
print("It's an elder")
# alternative solution
age = 24
if age < 2:
print("It's a baby")
elif 2 <= age < 4:
print("It's a child")
elif 4 <= age < 13:
print("It's a tween")
elif 13 <= age < 18:
print("It's a teenager")
elif 18 <= age < 65:
print("It's an adult")
else:
print("It's an elder")
Checking for an empty sequence
Two ways to test whether a list is empty.
a = []
if len(a) == 0:
print("Empty.")
else:
print("Not empty.")
# alternative solution
if not a:
print("Empty.")
else:
print("Not empty.")
Nested lists
Iterating through a list that contains a string, a tuple, and a nested dictionary.
a = ["str, 12345", ('tunpe', 2) ,{'dict':{'dict': {'dict': 4}}}]
for i in range(len(a)):
if i == 0:
print(a[i], end=' ')
elif i == 1:
for j in a[i]:
print(j, end=' ')
elif i == 2:
for k1, v1 in a[i].items():
print(f"key: {k1}, value: {v1}")
for k2, v2 in v1.items():
print(f"key: {k2}, value: {v2}")
for k3, v3 in v2.items():
print(f"key: {k3}, value: {v3}", end=' ')
print()
Sequence packing
Pairing two lists with zip and then building a dictionary with adjusted ages.
name = ['lys', 'wjq', 'hfcj', 'xhz', 'jcg']
age = [104, 504, 1909, 14, 3.14]
info = {k:v + 10 for k, v in zip(name, age)}
for k, v in info.items():
print(f"Name: {k}, NowAge: {v}")