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.
Related
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: ")
I am confused here that two codes are showing different outputs.
Can anyone help me to figure out that what's wrong with 1st code...
First Code:
It's is showing the wrong output
print("Welcome to Leap Year Finder!")
year = int(input("Write a year to check..\n"))
div4by = year % 4
div100by = year % 100
div400by = year % 400
if(div4by == 0 and div100by == 0 and div400by == 0):
print(f"Year {year} {div4by} {div100by} {div400by} is Leap Year!")
else:
print(f"Year {year} {div4by} {div100by} {div400by} is Not Leap Year!")
Second Code:
It's working fine.
if div4by == 0:
if div100by == 0:
if div400by == 0:
print("Leap year.")
else:
print("Not leap year.")
else:
print("Leap year.")
else:
print("Not leap year.")
The correct condition is
if div400by == 0 or div100by != 0 and div4by == 0:
#A 0-50 Units is multiplied by $0.59 (multiply by 0.59)
#B Up to 150 Units (minus 50 and multiply remaning by 0.65)
#C Greater than 150 Units(minus 150(first 150 = $94.50) and multiply remaining by 0.68)
#D All Residential charges are fixed # $13.00(always add $13)
print (" * SKELEC Electricity Bill Calculator * ")
def main():
while True:
try:
prev_month = float(input("Enter the meter reading for the previous month\n"))
break
except ValueError:
print("Invalid value entered. Please try again.")
continue
if prev_month < 0:
print("Please enter a valid reading.")
main()
while True:
try:
pres_month = float(input("Enter the meter reading for the current month\n"))
break
except ValueError:
print("Invalid value entered. Please try again.")
continue
if pres_month < 0:
print("Please enter a valid reading.")
main()
if pres_month < prev_month:
print("Present month value is lower than previous month value")
main()
units_kwh = pres_month - prev_month #Variable for the subtraction of present month and previous month
print("Usage = ", units_kwh,"kw/h")
if units_kwh <= 50: #Argument for 0-50 kwh units
Energy_charge = units_kwh * 0.59
print("Your charge for the month is, $", Energy_charge)
elif units_kwh > 50 and units_kwh <= 150: #Argument for units up to 150kwh
units_fifty = units_kwh - 50
Energy_charge = (units_fifty * 0.65 + 29.50) + 13.00
print("Your charge for the month is, $", Energy_charge)
elif units_kwh > 150: #Argument for units over 150kwh
Energy_charge = ((units_kwh - 150) * 0.68 + 94.50) + 13.00
print("Your charge for the month is, $", Energy_charge)
print("Residential Charge of $13.00 added")
main()
Everything works well, but if an incorrect value is entered at first(such as characters), the code unwantedly loops once it gives the final result. I've tried moving the try/catch blocks outside of the loop, double checking my conditional statements and proofreading to see how the code could loop in such a way. I'm convinced the problem lays in the try/catch blocks, but I'm fairly new to coding with Python so I am unsure of how to fix this?
You can make a couple changes to improve the code:
If the user enters a negative number, raise an exception
Add an outer while loop for the pres_month < prev_month condition
Try this code:
def main():
while True: # pres_month < prev_month
while True:
try:
prev_month = float(input("Enter the meter reading for the previous month\n"))
if prev_month < 0: raise ValueError()
break
except ValueError:
print("Invalid value entered. Please try again.")
while True:
try:
pres_month = float(input("Enter the meter reading for the current month\n"))
if pres_month < 0: raise ValueError()
break
except ValueError:
print("Invalid value entered. Please try again.")
if pres_month < prev_month:
print("Present month value is lower than previous month value")
else:
break # data is valid
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
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.")