In python, I need the input of a user to be between a range of years.
Using if statement returns the error (if he's out of range) to the user and invite him to make another choice of year.
The second time he chooses a year need to be tested again with the same conditions. Which doesn't happen yet.
What would be the best solution to have his input tested all over again, until conditions are met ?
Here's some piece of the actual code
year = input("Enter a year between 1900 and 2099 : ")
if year >= "1900" or year <= "2099":
year = (input("The year you entered is out of range, please try again : "))
year = int(year)
Thanks in advance
Explanation:
You can use a while loop. A while loop will run until a certain condition is False. In this case it will run until the break keyword is used, because the condition will always be True. You can also use try and except do make sure the input it an integer. And use continue to start the loop again if it is not an integer.
Code:
prompt = "Enter a year between 1900 and 2099: "
while True:
year = input(prompt)
try:
year = int(year)
except ValueError:
prompt = "The year you entered is out of range, please try again : "
continue
if year >= 1900 or year <= 2099:
break
else:
prompt = "The year you entered is out of range, please try again : "
Related
Trying to create an input validation for a date in format YYYY-MM-DD. I have two methods of doing this.
The first method seems to work, and loops back through to get input each time an error is raised.
The function in the second method is causing an infinite loop, but a nearly identical function in the first method does not.
If I enter a correctly formatted date in the second method, it prints as expected, but for any other input, it creates the infinite loop.
I'm not sure where this is breaking down?
I've looks in a number of Google results, and there are lots of date validations out there, but I haven't found one that explicitly addresses how to loop back around and try again.
I wasn't sure what else to try without essentially just rewriting method one.
import datetime as dt
#METHOD 1 - This is the first method for validating date input, which takes in individual blocks and validates each one individually.
def get_date(year_prompt, month_prompt, day_prompt):
#Year Input
while True:
try:
year = int(input(year_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if year in range(2000,3000,1):
break
else:
print("Sorry, your response must be in YYYY format and later than the year 2000.\n")
continue
#Month Input
while True:
try:
month = int(input(month_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if month in range(1,13,1):
break
else:
print("Sorry, needs to be MM and between 1-12\n")
continue
#Day Input
while True:
try:
day = int(input(day_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if day in range(1,32,1):
break
else:
print("Sorry, needs to be DD and between 1-31\n")
continue
#Takes the three inputs and puts them together into a date
date = dt.datetime(year, month, day)
#Returns the date
return date
#Runs the first method of getting and validating a date.
date = get_date("\nYYYY: ", "\nMM: ", "\nDD: ")
#Prints the validated date.
print("\nThe date you entered is: ", date, "\n")
#METHOD 2 - This is the second method for validating date, which takes in the whole date in one input, and attempts to validate it against the YYYY-MM-DD format.
def input_validation(date):
while True:
try:
dt.datetime.strptime(date, '%Y-%m-%d')
break
except ValueError:
print("\nSorry, this does not appear to be a valid date in format YYYY-MM-DD")
continue
return date
#Prints the validated date.
print("\nThe date you entered is: ", input_validation(input("Enter a date in format YYYY-MM-DD: ")), "\n")
My expected result for the second method, is either a date in format YYYY-MM-DD, or an error message that then asks for the input again.
You can get rid of the infinite loop while True, and return True or False based on the date being in the correct format
def input_validation(date):
#Flag to check date format
flag = False
try:
#If date is of correct format, set flag to True
dt.datetime.strptime(date, '%Y-%m-%d')
flag = True
except ValueError:
print("\nSorry, this does not appear to be a valid date in format YYYY-MM-DD")
#Return flag
return flag
print(input_validation('2019-01-31'))
print(input_validation('2019-001-31'))
print(input_validation('2019-01-311'))
The output will be
True
Sorry, this does not appear to be a valid date in format YYYY-MM-DD
False
Sorry, this does not appear to be a valid date in format YYYY-MM-DD
False
You can wrap this function around your while True to continue taking input from user
while True:
date_str = input('Enter Date')
if input_validation(date_str):
break
I am new to Python, my second week doing it. I have a code I wrote where one enters year a car was made and it outputs price.
When I enter 1961, I get what I want. When I enter 1962 I get my result.
How can I structure the code such that if I enter any given year period it gives a correct price? Outside the range, it gives an error message. After entering a year and getting a result the user has the option to enter another year or to exit.
year = int(input('Enter year:\n'))
if year < 1962:
print('Car did not exist yet!')
print('Please enter a valid year from 1962'),int(input('Please enter another year:\n'))
if year <= 1964:
print('$', 18500), int(input('Please enter another year:\n'))
if year >= 1965 <=1968:
print('$', 6000), int(input('Please enter another year:\n'))
if year >=1969 <=1971:
print ('$', 12000), int(input('Please enter another year:\n'))
Thank you for any feedback. I tried if/elif to no avail.
You could use a while loop to overcome this issue.
An example of this could include:
year = int(input('Enter year: '))
while year: # this line forces the program to continue until the user enters no data
if year < 1962:
print('Car did not exist yet!')
print('Please enter a valid year after 1962')
elif year <= 1964:
print('$18500')
elif year >= 1965 <= 1968:
print('$6000')
elif year >= 1969 <= 1971:
print('$12000')
else:
print('Error Message') # You can change the error message to display if the year entered is after 1971
year = int(input('Please enter another year: '))
I'm trying to code horoscope that comes after the user input the birth month and day.
print("To figure out your horoscope, enter the following questions")
month = int(input("what month were you born(january,december,august: "))
days = int(input("what day were you born(2,4,12: "))
if month == 'december':
astro_sign = 'Sagittarius are nice people' if (day < 22) else 'Capricon are adventurous'
print(astro_sign)
However, every time I execute the code, it gives me an error:
print(astro_sign)
NameError: name 'astro_sign' is not defined
Currently, I only put one month which is 12 and day is below 22, later on when one piece of this code works, I'm going to add more months. Can anyone please help me?
That is because you are introducing/creating your astro_sign variable inside your conditional if month == '12':. So, every time you enter something that is not in fact '12', you will end up getting this error.
Simply, create your astro_sign before the conditional, so it is at least available in the event you don't enter your condition:
astro_sign = ''
if month == '12':
# rest of code here
Furthermore, you will never actually enter that condition with your current code, because you are casting your input for month as an int here:
month = int(input("month: "))
However, your condition is explicitly checking for a string per your single quotes: '12'.
So, instead of:
if month == '12':
You in fact should do:
if month == 12:
Remove the single quotes, so you are comparing int to int.
print("Please enter your birthday")
month = int(input("month: "))
day = int(input("day: "))
if month == '12':
print('Sagittarius are nice people')
if day < 22:
print('Capricon are adventurous')
see if this actually works for you (Tell me if I got it all wrong please)
I'm trying to write a basic function that takes a number and returns the abbreviation of each month. It sounds simple enough, but how can I use a "try-except"block to handle any exceptions?
Here's what I have so far.
def month():
months = "JanFebMarchAprilMayJuneJulyAugSepOctNovDec"
n = eval(input("Enter month Number: "))
pos = (n-1)*3
monthAbbrev = months
return monthAbbrev
I guess my question is how can I put in a try-expect handle indexes that are out of range?
I'm completely lost here. Thanks for your help
This simply returns the month at the correct index and if it doesn't exist it retruns the String Error replace it by whatever you need.
def month(n):
months = ("Jan", "Feb", "Mar", ...)
try:
return months[n-1]
except IndexError:
return "Error"
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%b")
Get month name from number
Surround that with a try except to catch any errors
I've looked all over stack overflow and so I really need help. I'm making a program that is supposed to calculate the age of a person by asking for their birth year, validating their birth year is correct, as in a whole number, and not words or any other invalid types of answers. And then subtracting the birth year from our current year. I'm having trouble with the inputting our current year and subtracting the user input birth year from it.
# Function Boolean is_valid_integer(String input_string)
# Declare Boolean is_valid
#
# is_valid = is input_string a valid integer?
# Return is_valid
# End Function
def is_valid_integer(input_string):
try:
val = int(input_string)
is_valid = True
except ValueError:
is_valid = False
return is_valid
# Function Integer get_year_born()
# Declare Boolean is_valid
#
# Display "What year were you born in? "
# Input input_string
# Set is_valid = is_valid_integer(input_string)
# While Not is_valid
# Display "Please only enter whole years."
# Input input_string
# is_valid = is_valid_integer(input_string)
# End While
# input_integer = int(input_string)
# Return input_integer
# End Function
def get_year_born():
input_string = input("What year were you born in? ")
is_valid = is_valid_integer(input_string)
while not is_valid:
input_string = input("Please only enter whole years. ")
is_valid = is_valid_integer(input_string)
input_integer = int(input_string)
return input_integer
# Function Integer calculate_difference()
# difference = 2017 - input_integer
# End Function
import datetime
def calculate_difference(difference):
difference = 2017 - input_integer
return difference
# Module calculate_age_year()
# Set born = get_year_born()
# Call calculate_difference()
# End Module
def calculate_difference():
print("Your age is: ", difference)
calculate_age_year()
After trying to import datatime into my coding, it didn't work well. I was also not looking to calculate specific days and/or time, and so I removed those part of the suggested coding, maybe that had something to do with it?
My purpose for this program is really to just calculate years, so if I'm born in 2000, I'd like the program to calculate from 2017, meaning I'd be 17 years old as of right now.
My first function is the loop to void out false inputs, the second function is to get the year the user was born in, the third function is supposed to be calculating the difference between the current date and the user's birth date, and the fourth function outputting the user's actual age.
To work with the dates in Python, you can use the module datetime.
To validate the error, a pythonic way of doing would be to use try...catch to convert the user input to a date time. Catch the possible errors and do your error management from there.
Here is a simple example:
import datetime
def print_age():
year = raw_input('Enter your age (YYYY/MM/DD): ')
try:
year = [int(i) for i in year.split('/')]
birth_data = datetime.date(year[0], year[1], year[2])
today = datetime.date.today()
time_diff = today - birth_data
print('Your age is: {} year and {} days'. format(
time_diff.days // 365, time_diff.days % 365))
except ValueError, KeyError:
# Do your error management here
print('Please use the format YYYY/MM/DD')
print_age()
With this, it should be relatively simple to return True or False and put the function in a loop.
Edit
Here is a piece of code that asks the user for his year of birth and prints the difference:
import datetime
year = None
while year is None:
try:
user_input = raw_input('Enter your date of birth (YYYY): ')
year = int(user_input)
except ValueError:
print('Your did not enter a valid year!')
print('You were born {} years ago'.format(datetime.datetime.now().year - year))
It does not check for the validity of the year though, if you enter 61241, it will not return an error.
You can add a layer of verification that check the range of the year if you wish.