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:
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: ")
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
def YearType(year):
leapyear = False
year = int(year)
if year MOD 4 == 0 or year MOD 400 == 0:
leapyear = True
elif (year MOD 100 == 0):
leapyear = False
elif leapyear == True:
print("wow this year is a leap year!")
else:
print("this isnt a leap year :(")
print YearType(2000)
There are several issues here:
Algorithmic: 1900 MOD 4 == 0, but 1900 is not a leap year
Syntax: Python uses % instead of MOD
Logic: elif leapyear == True: should be if leapyear == True:
Code:
# Business Logics
if year % 400 == 0: # 1600, 2000, 2400 are leap years
leapyear = True
elif (year % 100 == 0): # 1800, 1900, 2100 are not leap years
leapyear = False
elif (year % 4 == 0): # 1996, 2004, 2008, 2012, 2020 are leap years
leapyear = True
else:
leapyear = False # 2018, 2019, 2021 are not leap years
# UI
if leapyear:
print("wow this year is a leap year!")
else:
print("this isnt a leap year :(")
Edit: If you want to implement a function, I suggest splitting it in two: business logics and UI:
def IsLeapYear(year):
if year % 400 == 0:
return True
elif (year % 100 == 0):
return False
elif (year % 4 == 0):
return True
else:
return False
def YearType(year):
if (IsLeapYear(year)):
print("wow this year is a leap year!")
else:
print("this isnt a leap year :(")
print(YearType(2000))
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.
"im fairly new to python. I want to create a program that shows the olympic games or soccer World Championship but i keep getting an error message at the first print function and i don't know what i am doing wrong here."
year = int(input("a year between 1950 and 2050: "))
if year < 1950:
print("follow instructions")
elif (year%4) == 0:
print("{0} olypic games".format(num))
elif (year%2) == 0:
print("{0} soccer World Championship ")
else:
print("{0} nothing special this year".format(num))
This is probably due to the fact that your forgot to indent the first call to print:
year = int(input("a year between 1950 and 2050: "))
if year < 1950:
# I indented here
print("follow instructions")
elif (year%4) == 0:
print("{0} olypic games".format(num))
elif (year%2) == 0:
print("{0} soccer World Championship ")
else:
print("{0} nothing special this year".format(num))
Note that you also forget to call the format method in the case year % 2 == 0:
elif (year%2) == 0:
# I added .format(num)
print("{0} soccer World Championship ".format(num))
By the way, please remember to put the Error stack trace when you're asking for help next time, it is easier to help you then!
make sure it is correctly idented:
year = int(input("a year between 1950 and 2050: "))
if year < 1950:
print("follow instructions")
elif year%4 == 0:
print("{0} olypic games".format(num))
elif year%2 == 0:
print("{0} soccer World Championship".format(num))
else:
print("{0} nothing special this year".format(num))
I recently signed up on this site because I am really stuck on the assignment in which I am required to create a program where the user inputs a month and the program displays how many days there are in that month. The user must also input the year so the program can check if it is a leap year in case the user inputs the month of february.
This is the coding I've come up with so far:
def get_year():
year = raw_input("Please enter the year: ")
return year
def get_month():
month = raw_input("Please enter the month: ")
return month
def leap_year(year):
if year % 4 == 0:
return true
else:
return false
def get_days(month):
if month == "january":
print "31 days"
elif month == "february" and leap_year == true:
print "29 days"
else:
print "28 days"
if month == "march":
print "31 days"
elif month == "april":
print "30 days"
elif month == "may":
print "31 days"
elif month == "june":
print "30 days"
elif month == "july":
print "31 days"
elif month == "august":
print "31 days"
elif month == "september":
print "30 days"
elif month == "october":
print "31 days"
elif month == "november":
print "30 days"
elif month == "december":
print "31 days"
else:
print
def main():
user_year = get_year()
user_month = get_month()
leap_year(user_year)
get_days(user_month)
main()
Anyways it's clear that there is an error in my get_days function its just I'm not sure
how to write the code so that the program knows that the user inputs a month such as
january or march. I'm guessing that the input has to be a variable and that since each
month is a string, a variable string is needed. But I could be completely wrong about this.
I'm very new to python (exactly 2 weeks now of off and on programming for school work) so I'm not too sure on many of the specifics of python programming so if anybody could assist me in the proper direction, it would be much appreciated!
You were kinda close. I made some changes which I commented. And as Raymond Hettinger points out, your get_days(month) is completely broken.
def get_year():
year = raw_input("Please enter the year: ")
return int(year) #otherwise it is a string!
def get_month():
month = raw_input("Please enter the month: ")
return month
def leap_year(year):
if year % 4 == 0:
return True
else:
return False
def get_days(month,leap_year): #leap_year must be passes to this function
#This checks for "january" and "february" with leap years
#and falls back to last option on EVERYTHING ELSE like a feb without a leap year or even a "march"
if month == "january":
print "31 days"
elif month == "february" and leap_year == True:
print "29 days"
else:
print "28 days"
#this is a separate block that runs AFTER the previous block
if month == "march":
print "31 days"
elif month == "april":
print "30 days"
elif month == "may":
print "31 days"
elif month == "june":
print "30 days"
elif month == "july":
print "31 days"
elif month == "august":
print "31 days"
elif month == "september":
print "30 days"
elif month == "october":
print "31 days"
elif month == "november":
print "30 days"
elif month == "december":
print "31 days"
else:
print "invalid input" #so that it doesnt fail silently when I enter 2
def main():
user_year = get_year()
user_month = get_month()
leap_status = leap_year(user_year) #store the leap_year status to a variable
get_days(user_month, leap_status) #and then pass it to a function
main()
The if-elif was being broken in February. The minor change is to continue with an uninterrupted pattern of if-elif logic:
def get_days(month):
if month == "january":
print "31 days"
elif month == "february" and leap_year:
print "29 days"
elif month == "february" and not leap_year:
print "28 days"
elif month == "march":
print "31 days"
elif month == "april":
print "30 days"
elif month == "may":
print "31 days"
elif month == "june":
print "30 days"
elif month == "july":
print "31 days"
elif month == "august":
print "31 days"
elif month == "september":
print "30 days"
elif month == "october":
print "31 days"
elif month == "november":
print "30 days"
elif month == "december":
print "31 days"
else:
print 'unknown month'
I would suggest you to using dictionary which a build-in data type in python.
def get_days(year, month):
"""
take year and month ,return the days in that month.
"""
#define a dictionary and the month is key which value is days
daydict = dict()
daydict = ['january'=31, 'february'=28, 'februaryinleapyear'=29,
'march'=31, 'april'=30,
'may'=31, 'june'=30,
'july'=31, 'august'=31,
'september'=30, 'october'=31,
'november'=30, 'december'=31 ]
try:
if month in daydict:
if month == 'february' and leap_year(year):
print daydict[februaryinleapyear]
else:
print daydict[month]
else:
print 'The year or month you input is invalid !'
except:
print 'error!'
n=int(input('enter no of days in a month= '))
#0=sunday
#1=moday
#2=tuesday
#3=wednesday
#4=thursday
#5=friday
#6=saturday
d=int(input('enter the starting day of month= '))
print('sun','mon','tue','wed','thu','fri','sat',sep='\t')
for j in range(d):
print (' ',end='\t')
i=1
while(i<=n):
print (i,end='\t')
if(i+d)%7==0:
print('\t')
i=i+1
This code ask for user inputs( more simple codes)
#python calendar days in month.
month= input ("Enter the month('January', ...,'December'): ") # ask for inputs from user
start=input ("Enter the start day ('Monday', ..., 'Sunday'): ")
if start== "Monday" :
num=1
elif start== "Tuesday" :
num=0
elif start== "Wednesday" :
num=-1
elif start== "Thursday" :
num=-2
elif start== "Friday" :
num=-3
elif start== "Sartday" :
num=-4
elif start=="Sunday":
num=-5
print(month)
print("Mo Tu We Th Fr Sa Su") #the header of the Calender
if month== "January" or month=="March" or month=="May" or month=="July" or month=="August" or month=="October" or month=="December" :
#for month with 31 days
for num_ in range (num,num+41,7):
for i in range(7):
if num<1:
print (' ',end="")
elif num>31:
print("",end="")
else:
print ("{0:>2}".format(num),end="")
if i<6 and num<31:
print(" ",end="")
num +=1
print()
elif month== "April" or month=="June" or month=="Septemmber" or month=="November":
#for month with 30 days
for num_ in range (num,num+41,7):
for i in range(7):
if num<1:
print (' ',end="")
elif num>30:
print("",end="")
else:
print ("{0:>2}".format(num),end="")
if i<6 and num<30:
print(" ",end="")
num +=1
print()
elif month== "February" :
# february is an exception : it has 28 days
for num_ in range (num,num+41,7):
for i in range(7):
if num<1:
print (' ',end="")
elif num>28:
print("",end="")
else:
print ("{0:>2}".format(num),end="")
if i<6 and num<28:
print(" ",end="")
num +=1
print()
else:
print("invalid entry")