I've been trying to work out a way to accomplish what's in the title, without using any imported calendar/datetime libs from Python. There's little function at the top for checking whether or not the year is a leap year, which I want to be able to reference when printing the number of days in a given February, however I'm not too sure how to do so. (I've guessed with something like output. bla bla)
So far I've come up with something like this, which should make clear what I want to do, but I'm still a bit new to Python, so I would love a few tips/help on fixing up my code for the task.
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
# You should complete the definition of this function:
def days_in_month(month, year):
if month == 'September' or month == 'April' or month == 'June' or month == 'November'
print 30
elseif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October'\
or month== 'December'
print 31
elseif month == 'February' and output.is_leap_year = True
print 29
elseif month == 'February' and output.is_leap_year = False
print 28
else print 'Blank'
Ok I've fixed up my code, and it seems to output the correct data for every month but February:
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
# You should complete the definition of this function:
def days_in_month(month, year):
if month in ['September', 'April', 'June', 'November']:
print 30
elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
print 31
elif month == 'February' and is_leap_year == True:
print 29
elif month == 'February' and is_leap_year == False:
print 28
Any hints to fix up outputting for February?
EDIT: Just needed to add the argument year when referencing the first function. Here is the 100% working code for future reference:
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year(year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
# You should complete the definition of this function:
def days_in_month(month, year):
if month in ['September', 'April', 'June', 'November']:
print 30
elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
print 31
elif month == 'February' and is_leap_year(year) == True:
print 29
elif month == 'February' and is_leap_year(year) == False:
print 28
else:
return None
A more pythonic approach would be to define the mapping in a dictionary, then simply retrieve the values from the dictionary.
Try it out:
days_in_month_dict = {"January": 31, "February": 28,
"March": 31, "April": 30,
"May": 31, "June": 30,
"July": 31, "August": 31,
"September": 30, "October": 31,
"November": 30, "December": 31}
def is_leap_year(year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
def days_in_month(year, month):
if is_leap_year(year) and month == "February":
return 28
try:
#attempt to get value from dictionary
return days_in_month_dict[month]
except KeyError:
#key does not exist, so we caught the error
return None
Some syntax error in your code:
There should be no space before def days_in_month(month,year). Python use indentation to separate code blocks. This is the error you given in comment.
There is no elseif in python, it should be elif
output.is_leap_year = True, it should be is_leap_year(year) == True. The False part should be changed too.
after if statement and else there should be a :, like
if month == 'September' or month == 'April' or month == 'June' or month == 'November':
print 30
elif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October' or month== 'December':
print 31
elif month == 'February' and is_leap_year(year) == True:
print 29
elif month == 'February' and is_leap_year(year) == False:
print 28
else:
print 'Blank'
"""
Takes the year and month as input and returns the no. of days
"""
def is_leap_year (year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
def days_in_month(month, year):
if month == 'September' or month == 'April' or month == 'June' or month == 'November':
result=30
elif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October'or month== 'December':
result=31
elif month == 'February' and output.is_leap_year ==True:
result=29
elif month == 'February' and output.is_leap_year == False:
result=28
return result
print(is_leap_year(2016))
print(days_in_month('September',2016))
month = int (input ('month (1-12): '))
if month < 13:
if month == 2:
year = int (input ('year: '))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print ('29')
else:
print ('28')
else:
print ('29')
else:
print ('28')
elif month >= 8:
if month % 2 == 0:
print ('31')
else:
print ('30')
elif month % 2 == 0:
print ('30')
else:
print ('31')
else:
print ('Only 1-12 accepted')
month=input("month")
year=int(input("year"))
if year%4==0:
year=('leap year')
if month in ['September', 'April', 'June', 'November']:
print ("30")
elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
print ("31")
elif month == 'February' and year == "leap year":
print ("29")
elif month == 'February' and year != "leap year":
print ("28")
else:
print("none")
*# Write a function that determines how many days there are in a particular month.
Your function will have two parameters: The month as an integer between 1 and 12,
and the year as a four digit integer.
Ensure that your function reports the correct number of days in February for leap years.*
def year():
a = int(input("insert your year"))
def month():
z = int(input("enter month 1-12 "))
if z==9 or z==4 or z ==6 or z==11:
return print(30)
elif z==1 or z==3 or z==5 or z==7 or z==10 or z==12:
return print(31)
elif z ==2 and a % 4==0:
return print("29 its a leap year")
elif z ==2 and a % 4==1:
return print(28)
month()
year()
Related
This is my first question here so please forgive and educate on any formatting errors. I am new to Python and going through automate the boring stuff. Decided to expand the date detection project by using the clipboard and formatting some things also. The problem I have is in any operation taken on the year part of the REGEX.
I have commented out my last attempt to validate the year and gave up and changed the REGEX to only find dates from 1000 to 2999 and skipped code validation of the dates.
I now need to validate leap years but I'm back to having to work with the year variable, but once again no operation has any effect.
Basically the problem is I can extract the year value and display it but I cannot modify it or do checks against it.
#! python3
#! detect dates in a block of text
import pyperclip
import re
#!import numpy as np
text = str(pyperclip.paste())
def datedetection(text):
dateRegex = re.compile(
r"""(
(\d|\d\d) #! match day
(/{1}) #! match /
(\d|\d\d) #! match month
(/{1}) #! match /
([1|2][0-9][0-9][0-9]) #! match year
)""",
re.VERBOSE,
)
matches = []
for groups in dateRegex.findall(text):
day = str(groups[1])
slash1 = str(groups[2])
month = str(groups[3])
slash2 = str(groups[4])
year = str(groups[5])
month_range_30 = ["04", "06", "09", "11"]
month_range_31 = ["01", "03", "05", "07", "08", "10", "12"]
month_range_Feb = ["02"]
#!year_range = np.arange(1000, 3000, 1).tolist()
if len(day) == 1:
day = "0" + day
else:
day = day
if len(month) == 1:
month = "0" + month
else:
month = month
if month in month_range_31:
if int(day) > 31:
day = "Too many days in a month with only 31 days."
slash1 = month = slash2 = year = ""
elif month in month_range_30:
if int(day) > 30:
day = "Too many days in a month with only 30 days."
slash1 = month = slash2 = year = ""
elif month in month_range_Feb:
if int(day) > 29:
day = "Too many days in February."
slash1 = month = slash2 = year = ""
elif int(month) > 12:
day = "Found an invalid month."
slash1 = month = slash2 = year = ""
elif month in month_range_Feb:
if (
int(day) == 29
and (int(year) % 4 == 0)
and (int(year) % 400 == 0)
and (int(year) % 100 == 0)
):
day = day
elif month in month_range_Feb:
if (
int(day) == 29
and (int(year) % 4 == 0)
and (int(year) % 100 != 0)
):
day = "Found an invalid leap year."
slash1 = month = slash2 = year = ""
#!elif year not in year_range:
#!day = "Year is out of range."
#!slash1 = month = slash2 = year = ""
dates = "".join([day, slash1, month, slash2, year])
matches.append(dates)
if len(matches) > 0:
pyperclip.copy("\n".join(matches))
print("Copied to clipboard:")
print("\n".join(matches))
else:
print("No dates found.")
datedetection(text)
In my approach to this project, I considered validating the days, months, and year ranges as part of the regular expression. I then defined functions to check for the leap year, and validate the number of days according to the months.
I found that way simpler and easier to understand and follow. As below:
dateRegex = re.compile(r'([0-3][0-9])/([0-1][0-9])/([1-2][0-9]{3})')
def is_leap_year(year):
year = int(year)
if year % 4 == 0:
if year % 100 == 0:
return year % 400 == 0
else:
return True
else:
return False
def is_valid_date(day, month, year):
if month == '02':
if is_leap_year(year):
return int(day) <= 29
else:
return int(day) <= 28
elif month in ['04', '06', '09', '11']:
return int(day) <= 30
else:
return int(day) <= 31
You can find the rest of my code below.
https://gist.github.com/alialbusaidi/f56e4c9342f622434f8bff0549f94884
The problem was the operations before the year operations. The day and month operations were overwriting the year values. Not entirely sure how or why at this point, but moving the year code above the day and month code has started to fix the issue.
hay guys i need to write a program that i give a date and then i give numbers of days and then i get a new date ( the numbers of days can be + or - ). i will be happy if someone help me. (about the first and second line , i just need them in the output)
specific_date =input('Enter a date:')
numofdays=input("Enter number of days:")
from datetime import datetime, timedelta
specific_date = datetime(day/month/year)
new_date = specific_date + timedelta(numofdays)
if (year % 400 == 0):
leap_year = True
elif (year % 100 == 0):
leap_year = False
elif (year % 4 == 0):
leap_year = True
else:
leap_year = False
month=['1','2','3','4','5','6','7','8','9','10','11','12']
if month in (1, 3, 5, 7, 8, 10, 12):
day in [1,31]
elif month == 2:
if leap_year:
day in[1,29]
else:
day in[1,28]
if month in (4,6,9,11):
day in [1,30]
I cannot for the life of me solve this challenge on Hackerrank. The closest I got it was to 4/6 passes.
Rules:
In the Gregorian calendar three criteria must be taken into account to identify leap years:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
Code:
def is_leap(year):
leap = False
# Write your logic here
if year%400==0 :
leap = True
elif year%4 == 0 and year%100 != 0:
leap = True
return leap
year = int(input())
print(is_leap(year))
You forgot the ==0 or !=0 which will help understand the conditions better. You don't have to use them, but then it can cause confusion maintaining the code.
def is_leap(year):
leap = False
if (year % 4 == 0) and (year % 100 != 0):
# Note that in your code the condition will be true if it is not..
leap = True
elif (year % 100 == 0) and (year % 400 != 0):
leap = False
elif (year % 400 == 0):
# For some reason here you had False twice
leap = True
else:
leap = False
return leap
a shorter version would be:
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
You can try this
def is_leap():
leap = False
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
leap = True
return leap
This code might be easy for some of the people to wrap their head around
def is_leap(year):
leap = False
# Write your logic here
if year%4==0:
leap=True
if year%100==0:
leap=False
if year%400==0:
leap=True
return leap
year = int(input())
print(is_leap(year))
If we split the question point by point.
Actual question:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
Explaining it : If a year is divided by 4, then its a leap year.
If this is divided by 100 but not 400 after being divisible by 4,
then its not a leap year.
If this is divisible by 4, 100 ,400 , then its a leap year.
Basically, nested if
if(year % 4 == 0):
if(year % 100 == 0):
if(year % 400 == 0):
leap =True
else:
leap=False
else:
leap=True
else:
leap=False
return leap
def is_leap(year):
leap=False
check =lambda year : year :year%4==0 and (year%400==0 or year%100!=0)
leap=check(year)
return leap
year =int(input())
print(is_leap(year))
def is_leap(year):
leap = False
if year%4 == 0:
if(year%100 != 0 or year%400 == 0):
leap = True
return leap
def is_leap(year):
leap = False
# Write your logic here
if year % 4 == 0 and year % 100 != 0:
leap = True
elif year % 100 == 0 and year % 400 != 0:
leap = False
elif year % 400 == 0:
leap = True
elif year % 4 != 0:
leap = False
return leap
year = int(raw_input())
print is_leap(year)
def is_leap(year):
leap = False
if(year%4==0):
#century year check
if(year%100==0):
#century leap year check
if(year%400==0):
leap=True
else:
leap=True
return leap
if year%4==0 and year%100==0 and year%400==0:
return True
elif year%4==0 and year%100!=0 and year%400!=0:
return True
else:
return False
n = [int(input("Enter a year in four digit: "))]
a = list(map(lambda x: "is a Leap year" if x%4 == 0 or ( x % 100 != 0 or x % 400 == 0) else "is not a Leap year" , n))
print(f"{n[0]} {a[0]}")
def is_leap(year):
leap = False
if year % 4 == 0 and year % 100 != 0:
leap = True
elif year % 400 == 0 and year % 100 == 0:
leap = True
return leap
I just try with this:
def is_leap(year):
leap = False
# Write your logic here
if (year%4 ==0 and year%100 !=0) or year%400 ==0:
leap = True
else:
leap = False
return leap
year = int(input())
print(is_leap(year))
if year can be evenly divided by 4 and 400 is True but if it can be evenly divided by 100 is False
#simplest solution for beginner
n = int(input('Enter year to check if it is leap year.'))
if n % 4 == 0 and n%100 != 0:
leap = 'True'
elif n % 100 == 0 and n%400==0:
leap = 'True'
else:
leap = 'False'
print('the entered year is,'+leap)
This would be my solution for the problem. We want the number to be divisible with 4 no matter what. So year % 4 will need to be true for the output to be bool True as well. Then we have to consider if the number which is divisible with 4 can be divided to 400. If the number is divisible to 100 but not 400 it should give us bool False. That is why we should check divisibility to 400 and non-divisibility to 100 together and use or statement.
def is_leap(year):
leap = False
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return not leap
else:
return leap
year = int(input())
print(is_leap(year))
def is_leap(year):
leap = False
# Write your logic here
if (year%4 ==0):
if (year%100 == 0) and (year%400 ==0):
leap = True
elif(year%100 == 0) and (year%400 !=0):
leap = False
else:
leap = True
else:
leap = False
return leap
year = int(input())
HackerRank Problem - An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.
In the Gregorian calendar, three conditions are used to identify leap years:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap years.
Solution is the below Python Code.
def is_leap(year):
leap = False
# Write your logic here
if (year % 4 == 0) and (year % 100 != 0):
# Note that in your code the condition will be true if it is not..
leap = True
elif (year % 100 == 0) and (year % 400 != 0):
leap = False
elif (year % 400 == 0):
# For some reason here you had False twice
leap = True
else:
leap = False
return leap
year = int(input())
print(is_leap(year))
Try this #Charles Thompson, this passed all test cases for me.
def is_leap(year):
leap = False
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
leap = True
else:
leap = False
else:
leap = True
return leap
def is_leap(year):
leap = False
if year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
return True
elif year %4 == 0 and year % 100! = 0 and year % 400!= 0:
return True
else:
return False
year = int(raw_input())
print is_leap(year)
def is_leap(year):
leap = False
# Write your logic here
if year%4==0:
leap= True
if year%100 ==0 and year%400==0:
leap = True
if (year%100 == 0) and (year%400 != 0):
leap = False
return leap
year = int(input())
print(is_leap(year))
def is_leap(year):
leap = False
d4 = year%4
d100 = year%100
d400 = year%400
if d4 == 0 :
if d100 != 0 or d400 == 0 :
leap = True
else :
leap = False
return leap
year = int(input())
print(is_leap(year))
Hey I'm having an issue getting the last bit of my code to run.
I am unable to get the values at the end and believe it may have to do with my formatting, although I'm not entirely sure. Instead of stabbing in the dark I thought I'd ask around here as the fastest way to improve is with help from the more experienced.
I'm new, and not seasoned. Haven't been programming for a full 2 months yet.
import math
def month():
month = input(' # of month born ')
if month == '1':
print ("January")
return "January"
elif month == '2':
print ("February")
return "February"
elif month == '3':
print ("March")
return "March"
elif month == '4':
print ("April")
return "April"
elif month == '5':
print ("May")
return "May"
elif month == '6':
print("June")
return ("June")
elif month == '7':
print ("July")
return "July"
elif month == '8':
print("August")
return "August"
elif month == '9':
print("september")
return "September"
elif month == '10':
print("October")
return "October"
elif month == '11':
print ("November")
return "November"
elif month == '12':
return "December"
print ("December")
else:
return month()
month()
print('day born')
day=input(' input day # ')
print ('{}'.format (day))
if month==1 and day<20:
print ('Capricorn')
elif month ==1 and day>22:
print ('aquarius')
It does everything fine except return aquarious or capricorn.
How may I format it correctly so it prints these values?
You run the function month(), right after the definition of it, but you do not store the return value. You should do this:
m = month()
if m == "October":
# ...
But instead, you're comparing the function month to 1, which will result to False.
def month(): pass # month is a function
month == 1 # is month equal to 1? no! this is False
Also, the function month actually returns string by your design, so you should not compare it to 1, but to "January", for example. Also, there's a very handy builtin package for this, you can use datetime here, see https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior.
In [3]: import datetime
In [4]: datetime.datetime(2000, 1, 1).strftime('%B')
Out[4]: 'January'
In [5]: datetime.datetime(2000, 12, 1).strftime('%B')
Out[5]: 'December'
So in a function:
def convert_number_to_month_name(i):
return datetime.datetime(2000, i, 1).strftime('%B')
I have to write a program where I enter a number and the program replies whether the number is a leap year or not. I'm new to python so I am unsure of where to start. So far, I know that a leap year is any number divisible by 4, but not by 100 (unless it is also divisible by 400).
Use the built-in calendar.isleap:
import calendar
calendar.isleap(2020)
#=> True
I am also a python beginner. I tried my best, see if this works.
def isLeap(year):
tyear = year
if tyear % 4 == 0:
tyear = year
if tyear % 100 == 0:
tyear = year
if tyear % 400 == 0:
print('Leap Year')
else:
print('Not a Leap Year')
else:
print('Leap Year')
else:
print('Not a Leap Year')
isLeap(2004) # Returns Leap Year
isLeap(2005) # Returns Not a Leap Year
Maybe this could help.
year = int(input("Input year: "))
if year % 4 == 0:
print("Year is leap.")
if year % 100 == 0 and year % 400 != 0:
print("Year is common.")
else:
print("Year is common.")
Most previous answers are correct here is another way to skin a cat:
The math logic is based on this full credit
year = 2024
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
Here is test case
def checkit(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
x = range(2013,2027)
for n in x:
print(n,checkit(n))
This is how to do leap years :)
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(year, "is leap!")
else:
print(year, "is not leap!")