I made an age calculator in python which uses while loops to regulate the kind of answer the user can input.
while True:
try:
month = int(input("What is your birth month?\n"))
if month < 13 and month > 0:
break
else:
print("Error: You must enter a valid month.")
continue
except ValueError:
print("Error: You must enter a whole number.")
continue
However, I also want the user to be able to enter the name of the month but have it converted to its number value before the ValueError denies the response because it's not an int value. I'm pretty sure I need to keep the ValueError so that the user cannot enter random words and then have the program crash, but I also don't know how to bypass it to allow input of certain words because they will be converted to int value (the month names like january). I've tried using dictionaries and assigning each month their numerical value, but despite many attempts I don't know how to place it so it actually works.
I made a dictionary:
monthConversions = {
"january": 1,
"february": 2,
"march": 3,
"april": 4,
"may": 5,
"june": 6,
"july": 7,
"august": 8,
"september": 9,
"october": 10,
"november": 11,
"december": 12
}
and I figured I should probably do monthConversions.get(month) or monthConversions.get(int(month)) but no matter where I put it, the program either gets stuck because the ValueError keeps on denying the response or it gives me this error:
invalid literal for int() with base 10
I've also tried completely excluding the except ValueError: part of the code, but an except or finally block is required and at the end of the day I still want the user to get an error if they input a non-numerical value that is also not a dictionary key.
I also tried altering this: month = int(input("What is your birth month?\n")) to not only accept int values, but the program either gets stuck (doesn't accept any kind of response) or doesn't work at all. I tried defining the month variable outside of the loop:
month = ""
but that pretty much broke the program.
I experimented with a lot of parts of the code but nothing came even close to working properly. I just can't figure out for the life of me how I'm supposed to make this work, despite the answer probably being simple lol. Any suggestions are welcome :D
CodePudding user response:
You could do something like this:
monthConversions = { "january": 1, "february": 2, "march": 3, "april": 4, "may": 5, "june": 6, "july": 7, "august": 8, "september": 9, "october": 10, "november": 11, "december": 12 }
while True:
in_str = input("What is your birth month?\n")
in_str = monthConversions.get(in_str.lower(),in_str)
try:
month = int(in_str)
if month > 12 or month < 1:
raise ValueError
break
except ValueError:
print("Error: You must enter a month name or whole number from 1 to 12")
print("\nmonth is", month)
CodePudding user response:
Solution 1
Here is a solution using a dictionary and the "get" method
month_dict = {
'January': 1,
'February': 2,
'March': 3,
'April': 4,
'May': 5,
'June': 6,
'July': 7,
'August': 8,
'September': 9,
'October': 10,
'November': 11,
'December': 12
}
while True:
# get the input from the user
input_str = input('Enter a month name or number: ')
# try to convert the input string to an integer
try:
input_num = int(input_str)
# use the input number as the value to look up the month name in the dictionary
month_name = next(key for key, value in month_dict.items() if value == input_num)
if month_name:
# if the month name was found in the dictionary, print it along with the month number
print(f'The month number {input_num} corresponds to the month name {month_name}.')
else:
# if the input number is not a valid month number, print an error message
print('Error: the month number must be between 1 and 12.')
# if the input string cannot be converted to an integer, it must be a month name
except ValueError:
# use the input string as the key to look up the month number in the dictionary
month_num = month_dict.get(input_str)
if month_num:
# if the month number was found in the dictionary, print it along with the month name
print(f'The month name {input_str} corresponds to the month number {month_num}.')
else:
# if the input string is not a valid month name, print an error message
print('Error: the input is not a valid month name.')
Solution 2
Here is an alternative solution that doesn't use a dictionary. It uses the list index instead of a dictionary values
# define a list of month names
month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
while True:
# get the input from the user
input_str = input('Enter a month name or number: ')
# try to convert the input string to an integer
try:
input_num = int(input_str)
# check if the input number is within the valid range of month numbers (1-12)
if 1 <= input_num <= 12:
# print the month name and number
print(f'The month number {input_num} corresponds to the month name {month_names[input_num-1]}.')
else:
# if the input number is not valid, print an error message
print('Error: the month number must be between 1 and 12.')
# if the input string cannot be converted to an integer, it must be a month name
except ValueError:
# check if the input string is in the list of month names
if input_str in month_names:
# print the month name and number
print(f'The month name {input_str} corresponds to the month number {month_names.index(input_str) 1}.')
else:
# if the input string is not in the list of month names, print an error message
print('Error: the input is not a valid month name.')
if you need the month name/number further ahead on the program, you can save the info in a variable instead of printing it