Test that the year passed is greater than or equal to 1582.
def gregyear():
try:
year =raw_input("Pick a year greater than or equal to 1582. It has to be divisible by four.)\n")
year =float(year)
leapyear = "Yes"
except:
print "please, only numbers"
else:
year =float(year)
if year >= 1582:
if year % 4:
print year
leapyear= "Yes"
else:
leapyear= "No"
else:
print "Wrong... print a year greater than 1582"
return leapyear
gregyear()
print "leapyear is "+ leapyear +"."
First, in Python, 0 is falsey, and all other numbers are truthy. So, when you do this:
if year % 4:
… that will trigger if year % 4 is anything except 0, meaning if the year is not divisible by 4. So your logic is backward.
Second, while gregyear does return a value, you ignore that return value If you want to use it, you have to store it:
leapyear = gregyear()
Third, you can't add strings to numbers, so this will raise a TypeError:
print "leapyear is "+ leapyear +"."
What you probably wanted is to either pass the strings and number to print to magically concatenate together while printing, like this:
print "leapyear is", leapyear, "."
Notice that I removed the extra spaces, because print with commas automatically puts spaces between its arguments.
However, a better way to write this is with string formatting:
print "leapyear is {}.".format(leapyear)
As a side note, you're also missing the rule that makes 1700, 1800, and 1900 not leap years (while 1600 and 2000 are).
Related
The function is supposed to receive a number representing a year, and then print if it's a leap year or not.
def isItALeapYear(year):
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
The program works, the only thing I can't get right is that it is supposed to notify you if anything that it's not a number is being used as an argument. I've tried both the isinstance() function, as well as writing what I want as year != int. And then year == None in the hopes of making it work in case anything nondefined is used as an argument.
I read this post with the exact same error: TypeError: not all arguments converted during string formatting python
But I'm not intending to format anything with the % symbol
As far as I'm concerned the % can be used as an operand to get the residue of a division.
So in this case I'm using it to figure out if a year is a leap year or not by asking if the residue is 0 when divided by 4. I'm pretty stuck, and the sad thing is the error comes up in the very first "if", so I can't really know if the last lines for excluding any non int type argument work or not. Any help would be really appreciated!
You could use the isleap() function from the standard library (module calendar):
from calendar import isleap
def isItALeapYear(year):
if not isinstance(year, int):
print("Please provide a number")
elif isleap(year):
print("That is a leap year!")
else:
print("That is not a leap year...")
I recommend to divide the functionality of checking the number from returning the output as well as from receiving the input.
def is_multiple_of_four(number: int):
if number % 4 == 0:
return True
else:
return False
if __name__ == '__main__':
user_input = ""
while not user_input.isdigit():
user_input = input("Please type in a year: ")
if is_multiple_of_four(int(user_input)):
print("That is a leap year!")
else:
print("That is not a leap year.")
Here you can see the function that checks the number does only that, it checks the number if it's modulo of 4 equals 0.
In the script outside the function you can retrieve the user input for as long as it takes to get a valid numeric and return the output in respect of the functions results.
Edit (adding clarification asked in the comments)
The first condition if __name__ == '__main__' is quiet common in python. It's not necessary for your function, but I like using it in answers if people seem to learn Python, so they don't miss out on it. Here is a question with a good answer: What does if __name__ == "__main__": do?
The short answer in the accepted answer is enough to understand why you might want to use it.
The second condition
user_input = ""
while not user_input.isdigit():
first defines a variable user_input with an arbitrary non-digit String value and than uses the negated isdigit() method of the String class on it as condition. Therefor the while loop gets entered in the beginning, as the arbitrary value is not an digit. From then on the value will be re-assigned with user input until it holds an actual digit. This digit is still a String however.
First thing while loop in the function makes no sense you can remove it(If you want).
There are multiple ways to do that I will show.
First One.
def isItALeapYear(year):
if type(year) != int:
return # here return to exit the function
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
Another is.
def isItALeapYear(year):
try:
int(year)
except ValueError: # this line of code executes when the year is not the int
return # here return to exit the function
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
I know there are more ways to do that but these are the best ones (I Think).
Your function is not accurate then you can use this one.
def isItALeapYear(year):
if type(year) != int:
return
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print(f"{year} is a Leap Year")
else:
print(f"{year} is Not the Leap Year")
Edit For Quetioner
def isItALeapYear(year):
if type(year) != int:
return
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print(f"{year} is a Leap Year")
else:
print(f"{year} is Not the Leap Year")
try:
isItALeapYear(asdasd)
except NameError:
print("You give the wrong Value")
So, last week, I got some work sent to me for Python 3, and one of the questions goes as follows: "Write (a) program which inputs the year. Your program should output whether it is a leap year or not. To work out if it is a leap year, test whether it is exactly divisible by 4."
This is what I've got so far:
yearStr = input("Please input a year: ")
year = float(yearStr)
calculation = year / 4
print(calculation)
if calculation == .0:
print("This is a leap year.")
else:
print("This is not a leap year.")
When I run the program, the IF statement doesn't work as intended. Could you help me, please?
Division does not yield zero if the number is evenly divisible, so this method cannot work.
Rather, use the modulo (%) operator to get the remainder of the division:
year = int(yearStr)
calculation = year % 4
if calculation == 0: # leap year
...
And note that strictly speaking, leap year determination is a bit more complex than just being divisible by four. But it'll do for the next 79 years.
Your problem is the performance of the code. To check if the year is leap, you have to put different conditions. You can now use this code:
year = int(input("Please input a year: "))
if ((year%400 == 0) or ((year%4 == 0) and (year%100 != 0))):
print("This is a leap year.")
else:
print("This is not a leap year.")
You are comparing calculation with 0, which is true only if the year was 0. You can check if integer value is equal to number itself.
calculation = year / 4
print(calculation)
if int(calculation) == calculation:
print("This is a leap year.")
else:
print("This is not a leap year.")
Still, this is not a good way to solve this problem, there is a remainder operation - %. For example 5 % 2 = 1. You can use it this way:
yearStr = input("Please input a year: ")
year = float(yearStr)
print(calculation)
if calculation % 4 == 0:
print("This is a leap year.")
else:
print("This is not a leap year.")
Simple code but a a bit of an odd issue. Python tends to print the brackets and coma in the print function. This only happens in row 5 and row 7 but not for the last row. Any idea what's wrong?
e.g. output for each row:
(2016, is a leap year)
(2015, is not a leap year)
Invalid year.
year_str = input("Please enter a numerical year: ")
year = float(year_str)
if year == int(year) and year > 0:
if (year/4)==int(year/4) and (year/100)!=int(year/100) or (year/400)==int(year/400):
print(year_str, " is a leap year.")
else:
print(year_str, "is not a leap year.")
else:
print("Invalid year.")
Your problem is you're using code written for python 3, where print is a function:
>>> import sys; sys.version_info.major
3
>>> print('a', 'b')
a b
but running it in python 2, where it is a statement:
>>> import sys; sys.version_info.major
2
>>> print ('a', 'b')
('a', 'b')
If you're writing code that you want to print the same way in both python 2 and python 3, you can use
from __future__ import print_function
print('a', 'b') # works as expected in both versions of python
use:
from __future__ import print_function
as the first line in your script. Then python 2.7 print is compatible with python 3 print
Since you're using python 2.7, print is a statement (not a function) so it takes no arguments and is called without parentheses (thanks to bruno for pointing this out in the comments). So in the first two print statements, you're just printing a tuple. In the last instance the parentheses are grouping a single element and so do nothing.
print('a', 'b') # print tuple
print ('a', 'b') # print tuple, but whitespace makes it more clear what's happening
print('a') # print string
print ('a') # print string, but whitespace makes it more clear what's happening
Use correct formatting when printing text:
year_str = input("Please enter a numerical year: ")
year = float(year_str)
if year == int(year) and year > 0:
if (year/4)==int(year/4) and (year/100)!=int(year/100) or (year/400)==int(year/400):
print("%s is a leap year." % year_str)
else:
print("%s is not a leap year." % year_str)
else:
print("Invalid year.")
print isn't a method in Python2, it's a statement. You should skip using parenthesis unless you want to print a tuple.
year_str = input("Please enter a numerical year: ")
year = float(year_str)
if year == int(year) and year > 0:
if (year/4)==int(year/4) and (year/100)!=int(year/100) or (year/400)==int(year/400):
print str(year_str) +" is a leap year."
else:
print str(year_str) +" is not a leap year."
else:
print "Invalid year."
def age_20():
user_age= int(input("enter the age: "))
if user_age >= 20:
user_age= user_age - 20
return (user_age, "20 years difference from now" )
if user_age < 20:
user_age= user_age + 20
return (user_age, "20 years difference from now")
print(age_20())
Return value shows:
(5, '20 years difference from now')
how can i avoid single quotation mark and parentheses?
as it stands, you are returning a tuple containing an int and a string. If you want a single return you could use something like this instead:
return (str(user_age) + "20 years difference from now")
print(age_20()[1])
Since you're returning a tuple, and assuming you only want to print the string. If you want to still print both,
age = age_20()
print(age[0],", ",age[1])
I am trying to create a function that accepts a users input and tries to figure out whether the year is a leap year and later also accept the users day of year (i.e. 355) and turns it into which day of the year it is (and output December, 10 2018). But for now I am not sure why it will not output whether the year is True or False. I tried to use the int parameter to change the user input from a string to a number but I am not sure if that is where I went wrong.
user_year = input('Enter year: ')
val = int(user_year)
def leap_year(val):
if val % 400 == 0:
print ("True")
if val % 100 == 0:
print ("False")
if val % 4 == 0:
print ("True")
else:
print ("False")
You're only defining the function leap_year but you're never calling it, below is an example where it actually gets called:
user_year = input('Enter year: ')
val = int(user_year)
def leap_year(val):
if val % 400 == 0:
print ("True")
if val % 100 == 0:
print ("False")
if val % 4 == 0:
print ("True")
else:
print ("False")
leap_year(val)
Also your indentation is a bit off, which causes it to not compile in the first place, but that could also be an error while copying to Stackoverflow.