Reputation: 23
def main():
month = 0
date = 0
year = 0
date = [month, date, year]
user = input("Enter according to mm/dd/yy:")
user = user.split('/')
month = user[0]
date = user[1]
year = user[2]
while int(month) > 12 or int(month) < 1 :
print("Month is incorrect.")
user = input("Enter according to mm/dd/yy:")
while int(date) > 31 or int(date) < 0:
print("Date is incorrect.")
user = input("Enter according to mm/dd/yy:")
while int(year) > 15 or int(year) < 15:
print("Year is incorrect.")
user = input("Enter according to mm/dd/yy:")
I keep on getting Month incorrect when it's correct. Please help. I'm trying to get the user's input to match the correct form of mm/dd/yy. And I'm trying to convert yy -> 2015. Please help.
Upvotes: 1
Views: 50
Reputation: 1727
Just like @nneonneo's comment pointed out, you forgot to update month
, date
and year
.
This would cause your while-loop to only use the very first recorded values for these fields.
Your current problem can be solved simply by adding this code at the end of each while-loop:
user = input("Enter according to mm/dd/yy:")
month,date,year = user.split('/')
As you might have guessed, the above is a nicer implementation of this piece of code from your question:
user = input("Enter according to mm/dd/yy:")
user = user.split('/')
month = user[0]
date = user[1]
year = user[2]
This would reduce the clutter in every while-loop.
Also, assuming your current indentation is correct, your code won't give you your desired output because it is not accounting for the case where the user starts with all 3 invalid fields: month
, date
and year
. If the user enters a correct month first, he would be able to enter an invalid month later on and still produce an output.
Instead of using three while loops, you should use an if-elif-else
block. This would ensure you get a proper answer:
def main():
user = input("Enter according to mm/dd/yy:")
month,date,year = user.split('/')
while True:
if int(month) > 12 or int(month) < 1 :
print("Month is incorrect.")
elif int(date) > 31 or int(date) < 0:
print("Date is incorrect.")
elif int(year) > 15 or int(year) < 15:
print("Year is incorrect.")
else:
break
user = input("Enter according to mm/dd/yy:")
month,date,year = user.split('/')
main()
Upvotes: 1
Reputation: 21
There is a bug in your code. Suppose if my input is "15/30/15", then it says incorrect month and tries to fetch user input in format "mm/dd/yy", but now the user is not spliting based on '\', so the while loop keeps running till the user[0] is assigned to new month. This error occurs for incorrect date and year as well. To fix it just call the user input function and split the user inside the while loop itself.
Upvotes: 2