How do I check if the year is valid entered by user? - python

I want to be able to check the year entered by user is valid:
Only a positive integer
Between the range 1998-current year
If no year is mentioned, then use the current year
Is there a more efficient way to do this?
from datetime import datetime
current_year = datetime.now().year
input_year = int(input("Enter Year Here >>"))
if input_year is None:
input_year = current_year
elif (1998 > input_year) or (input_year > current_year):
print("Please specify a date between 1998 to {}".format(current_year))
else:

If the entered year is empty int(input("Enter Year Here >>")) will fail since you are trying to convert an empty string, so you need to take input in as a string, and check if string is None, if it is, then assign current_year to input year, otherwise convert input string to int
Other optimiziation you can do is chained comparison
from datetime import datetime
current_year = datetime.now().year
#Take input as string
input_year = input("Enter Year Here >>")
#If input is None, use current year, else convert input to int
if not input_year:
input_year = current_year
else:
input_year = int(input_year)
#Use chained comparison
if not 1998 < input_year < current_year:
print("Please specify a date between 1998 to {}".format(current_year))
else:
print("You are good")
Possible outputs are
Enter Year Here >>
Please specify a date between 1998 to 2019
Enter Year Here >>1990
Please specify a date between 1998 to 2019
Enter Year Here >>2020
Please specify a date between 1998 to 2019
Enter Year Here >>-1000
Please specify a date between 1998 to 2019
Enter Year Here >>2010
You are good
To keep checking for input, just wrap the code in a while true loop
while True:
current_year = datetime.now().year
#Take input as string
input_year = input("Enter Year Here >>")
#If input is None, use current year, else convert input to int
if not input_year:
input_year = current_year
else:
input_year = int(input_year)
#Use chained comparison
if not 1998 < input_year < current_year:
print("Please specify a date between 1998 to {}".format(current_year))
else:
print("You are good")
Furthermore, you are use a string like quit to break your loop, and perhaps do your empty string check and input year assignment in a single line as well!
from datetime import datetime
while True:
current_year = datetime.now().year
input_year = input("Enter Year Here! Type quit to stop >>")
if input_year.lower() == 'quit':
break
input_year = int(input_year) if input_year else current_year
if 1998 < input_year < current_year:
print('You are good')
else:
print("Please specify a date between 1998 to {}".format(current_year))
If you want to check if user inputs a string or a float, you can do try/except and rely on ValueError to check if the string can be cast to an int or not! If string can be cast as int, it won't throw a ValueError, otherwise it will
def check_int(s):
is_int = False
try:
int(s)
is_int = True
except ValueError:
pass
return is_int
print(check_int('a'))
print(check_int('4.0'))
print(check_int(5))
The output will be
False
False
True
Finally, combining all of them we get
from datetime import datetime
def check_int(s):
is_int = False
try:
int(s)
is_int = True
except ValueError:
pass
return is_int
while True:
current_year = datetime.now().year
input_year = input("Enter Year Here! Type quit to stop >>")
if input_year.lower() == 'quit':
break
if not input_year:
input_year = current_year
elif check_int(input_year):
input_year = int(input_year)
else:
print('Provide a number as year')
continue
if 1998 < input_year < current_year:
print('You are good')
else:
print("Please specify a date between 1998 to {}".format(current_year))
The outputs will be
Enter Year Here! Type quit to stop >>
Please specify a date between 1998 to 2019
Enter Year Here! Type quit to stop >>hello
Provide a number as year
Enter Year Here! Type quit to stop >>-1234
Please specify a date between 1998 to 2019
Enter Year Here! Type quit to stop >>2000
You are good
Enter Year Here! Type quit to stop >>quit

Related

Check if the input value is valid in list using python

The programm is check if input value is valid in list.
below is my code. could you please help?thanks
while True:
try:
count = 0
Day_list = []
days = int(input("Enter number : "))
except ValueError:
print("Please input the integer")
else:
for i in range(days):
Day_list.append(float(input("Enter the day "+str(i+1)+ ": " )))
if( 0<= Day_list[i] <=10):
print('good' )
else:
print('Amount cant be negative, try again')
break
i would like check the value one by one
eg.
Enter the day 1 : -1
then output : Amount cant be negative, try again
return Enter the day 1 : 1
Enter the day 2 :
but i dont have idea where is mistake,thanks
here you are:
while True:
try:
count = 0
Day_list = []
days = int(input("Enter number : "))
except ValueError:
print("Please input the integer")
else:
if days >= 0:
for i in range(days):
valid = False
while not valid:
try:
Day_list.append(float(input("Enter the day "+str(i+1)+ ": " )))
if( Day_list[i] >= 0 and Day_list[i] <=10):
print('good' )
valid = True
except ValueError:
print ('input is not valid')
break
else:
print('Amount cant be negative, try again')

Finding Minutes Between Years

can you please check my code? I think something is wrong somewhere.
import datetime
this_year = datetime.datetime.today().year
def age_in_minutes(b_year: int):
d1 = datetime.datetime.strptime(f'{this_year}', '%Y')
d2 = datetime.datetime.strptime(f'{b_year}', '%Y')
age = (d1-d2).days * 24 * 60
return f"{age:,}"
while True:
birth_year = input("Enter you birth year: ")
try:
if int(birth_year) == this_year:
print("Please enter year less than this year...")
elif int(birth_year) > this_year:
print("Please enter year less than this year...")
elif len(birth_year) < 4 or len(birth_year) > 5:
print("PLease enter a valid year...")
elif int(birth_year) <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(int(birth_year))
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")
I'm tackling a challenge. It said if I enter 1930, I should get "48,355,200". But I'm getting "48,388,320". I'm new to Python.
You could try this code
I found it somewhere in 2021 but I don't know the source
current_year = 2022
year = int(input("Please enter a year: "))
if year == current_year:
print("There are 0 minutes from", year, "to present.")
elif year < current_year:
print("There are", (current_year - year) * 525600, "minutes from", year, "to present.")
else:
print("There are", (year - current_year) * 525600, "minutes from present to", year)
try this:
import datetime
this_year = datetime.datetime.today().year
print(this_year)
def age_in_minutes(b_year: int):
d1 = datetime.datetime.strptime(f'{this_year}', '%Y')
d2 = datetime.datetime.strptime(f'{b_year}', '%Y')
age = (d1-d2).days * 24 * 60
return f"{age:,}"
while True:
birth_year = int(input("Enter you birth year: "))
try:
if birth_year == this_year:
print("Please enter year less than this year...")
elif birth_year > this_year:
print("Please enter year less than this year...")
elif len(str(birth_year)) < 4 or len(str(birth_year)) > 5:
print("PLease enter a valid year...")
elif birth_year <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(birth_year)
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")
Output:
Enter you birth year: 1930
You are 48,388,320 minutes old.
I don't do any exceptional but change your type casting, and it can give me a desire result.
You haven't calculated leap year. You can follow this:
import datetime
this_year = datetime.datetime.today().year
def age_in_minutes(b_year: int):
leap_year = 0
non_leap_year = 0
for year in range(b_year, this_year+1):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
leap_year += 1
else:
non_leap_year += 1
leap_year_in_days = leap_year * 366
non_leap_year_in_days = non_leap_year * 365
age = (leap_year_in_days + non_leap_year_in_days) * 24 * 60
return f"{age:,}"
while True:
birth_year = input("Enter you birth year: ")
try:
if int(birth_year) == this_year:
print("Please enter year less than this year...")
elif int(birth_year) > this_year:
print("Please enter year less than this year...")
elif len(birth_year) < 4 or len(birth_year) > 5:
print("PLease enter a valid year...")
elif int(birth_year) <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(int(birth_year))
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")

Python: How do I include a function in another function?

I'm just starting to study programming and I have a question about functions. I defined the function leapyear as follows:
def leapyear(n):
# Given a year, decide if it is a leap year or not.
if n%4==0:
if n%100==0:
if n%400==0:
return "It is a leap year."
else:
return "It is not a leap year"
else:
return "It is a leap year"
else:
return "It is not a leap year"
Now I want to use it in another function, which is going to tell me if I wrote a valid date or not (for example, 02/28/2021 is valid, but 02/29/2021 is not). What I did is this:
def valid_date():
day = int(input("Day: "))
month = input("Month: ")
year = int(input("Year: "))
if month=="January":
if day<=31:
print("Valid date")
else:
print("Not a valid date")
if month=="February":
if year%4==0:
if year%100==0:
if year%400==0:
if day<=29:
print("Valid date")
else:
print("Not a valid date")
else:
if day<=28:
print("Valid date")
else:
print("Not a valid date")
else:
if day<=29:
print("Valid date")
else:
print("Not a valid date")
else:
if day<=28:
print("Fecha válida")
else:
print("Fecha no válida")
if month=="March":
if day<=31:
print("Valid date")
else:
print("Not a valid date")
It actually gets to December, but it doesn't really matter because it is basically the same.
The code works, but I was thinking to use the leapyear function instead of writing the whole code again. How can I do that?
Thanks!
First, your function should just return True or False; let the caller decide if a string representation like "It's a leap year" is warranted.
def leapyear(n):
# Given a year, decide if it is a leap year or not.
if n%4==0:
if n%100==0:
if n%400==0:
return True
else:
return False
else:
return True
else:
return False
Inside your valid_date function, you can call leapyear and use its result to determine if February can have a 29th in that year.
def valid_date():
day = int(input("Day: "))
month = input("Month: ")
year = int(input("Year: "))
if month=="January":
if day<=31:
print("Valid date")
else:
print("Not a valid date")
if month=="February":
if leapyear(year):
last_day = 29
else:
last_day = 28
if day <= last_day:
print("Valid date")
else:
print("Not a valid date")
if month=="March":
if day<=31:
print("Valid date")
else:
print("Not a valid date")
Let your fingers be lazy. Shorter programs are generally easier to read.
def leapyear( y):
return (y%4==0 and y%100!=0) or y%400==0
def valid_date( year, month, day):
if (day <= 0) or (month <= 0) or (year < 1582): return False
last = [31,29 if leapyear( year) else 28,31,30,31,30,31,31,30,31,30,31]
return (month <= 12) and (day <= last[month-1])
year, month, day = input( "Enter date (yyyy-mm-dd):").split( '-')
if valid_date( int( year), int( month), int( day)):
print( "Fecha válida")
else: print( "Fecha no válida")
The leapyear() code is only valid for years starting in 1582 (pope Grégoire). You can add some logic to validate earlier dates.
Your program should also include some validation of user input. For example, alphabetic characters will crash the program.

How do I find the len() of multiple strings?

I need to find the len() of multiple strings.
current_year = input ("What year is it?")
current_year = int(current_year)
birth_year = input ("What year were you born in?")
birth_year = str(birth_year)
if len(birth_year) != 4:
print ("Please make your year of birth 4 digits long.")
else:
birth_year = int(birth_year)
print("You are " + str(current_year - birth_year) + " years old.")
I would like to include the len() of birth_year.
Use an elif statement to check the current year input.
current_year = input ("What year is it?")
birth_year = input ("What year were you born in?")
if len(birth_year) != 4:
print ("Please make your year of birth 4 digits long.")
elif len(current_year) != 4:
print ("Please make the current year 4 digits long.")
else:
birth_year = int(birth_year)
current_year = int(current_year)
print("You are " + str(current_year - birth_year) + " years old.")
There's no need for birth_year = str(birth_year), since input() always returns a string.
You should probably include try/except code around the calls to int(), so you can print an error if they enter a year that isn't actually a number.
Here is a way to get what you want that is somewhat more dynamic. With this basic function, if a user inputs an inappropriate string, they will be asked to retry. You could even add a line to check if the year was after the current year.
Note that there is a loop in here with an exit that doesn't have a constraint. If you were going to implement this, I'd add a counter as well which would kill the process to prevent infinite loops.
def get_year(input_string):
# Set loop control Variable
err = True
# while loop control variable = true
while err == True:
# get input
input_year = input(input_string + ' ')
# Ensure format is correct
try:
# Check length
if len(input_year) == 4:
# Check Data type
input_year = int(input_year)
# if everything works, exit loop by changing variable
err = False
# if there was an error, re-enter the loop
except:
pass
# return integer version of input for math
return input_year
# set variables = function output
birth_year = get_year('What year were you born? Please use a YYYY format!\n')
current_year = get_year('What is the current year? Please use a YYYY format!\n')
# print output displaying age
print("You are " + str(current_year - birth_year) + " years old.")

How would I make this code run completely without error so that age is assigned correctly according to the date they enter?

from random import randint
def main():
dob = int(input("Please enter the year you were born"))
if dob > (2005):
main()
elif dob < (2004):
main()
else:
def mob():
if dob == (2004):
month = input("Please enter the first three letters of the month you were born")
if month == ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul"):
age = 12
elif month == ("Aug","AUG","aug"):
day = int(input("Please input the day you were born"))
if day < 28:
age = 12
elif day == ("29","30","31"):
age = 11
else:
age = 12
else:
age = 11
if dob == (2005):
age = 11
mob()
main()
If I were to enter 2004 and then 'aug', it would not ask the day of birth.The code would stop. I also want the code to run so that if I were to enter 2005, it would assign age to 11
Something like this does what you need, I think, though you could tidy it further to give the actual age, by using datetime.
def main():
yob = int(input("Please enter the year you were born"))
if yob > 2005:
return "Under 11"
elif yob < 2004:
return "Over 12"
elif yob == 2004:
return 12
else:
mob = input("Enter a three letter abbreviation for your month of birth: "
if mob.lower() in ("jan", "feb", "mar", "apr", "may", "jun", "jul"):
return 12
elif mob.lower() == "aug":
dob = int(input("Enter your day of birth"))
if dob < 28:
return 12
elif dob > 28:
return 11
else:
return 11
age = main()
Better alternative, covers most eventualities I think
from datetime import datetime
def give_age():
today = datetime.today()
dob = input("Enter your date of birth (DD/MM/YYYY): ")
try:
dob_datetime = datetime.strptime(dob, "%d/%m/%Y")
age = (today - dob_datetime).days / 365
return age
except ValueError:
print("Your date of birth was not in the required format")
give_age()
age = give_age()

Categories

Resources