Please type a year: 2019 2019 was the year of the pig. Please type a year: 2000 2000 was the year of the dragon. Please type a year: 1955 1955 was the year of the sheep. Please type a year:
The output is the same:
Please type a year: 2019 2019 was the year of the pig. Please type a year: 2000 2000 was the year of the dragon. Please type a year: 1955 1955 was the year of the sheep. Please type a year:
Please type a month, e.g., January: July Thank you, July is month number 7.
Please type a month, e.g., January: Juli Bad month "Juli".
The
None
in
line
15
is a dummy value.
Use it where you have no value to put there.
Our only purpose in storing
None
in the
list
is to make January have index 1 instead of index 0.
Please type a month, e.g., January: July Thank you, July is month number 7.
Please type a month, e.g., January: Juli Bad month "Juli".
Please type a month, e.g., January: July Thank you, July is month number 7.
Please type a month, e.g., January: Juli Bad month "Juli".
What would
months[::-1].index(month)
do?
What would
months[::-1].index(month) - 1
do?
If you don’t need the index number,
it’s faster to search with
in
and
not
in.
if month in months:
print(f"Thank you, {month} is in months.")
else:
print(f'Bad month "{month}".')
If you don’t need the index number,
and you’re searching for the number 0 or the empty string
"",
it’s easier to call the functions
any
and
all.
numbers = [0, 0, 0, 10, 0]
if any(numbers):
print("The list contains a non-zero value.")
else:
print("All the numbers are 0.")
The list contains a non-zero value.
strings = ["", "", "", "hello", ""]
if any(strings):
print("The list contains a non-empty value.")
else:
print("All the strings are the empty string.")
The list contains a non-empty value.
numbers = [20, 30, 10, 0, 50]
if all(numbers):
print("All the numbers are non-zero.")
else:
print("The list contains 0.")
The list contains 0.
strings = ["hello", "goodbye", "", "hello again", "Hiya fellah!"]
if all(strings):
print("All the strings are non-empty.")
else:
print("The list contains the empty string.")
We’ll have a faster way to search the months when we learn about dictionaries.