How do I fix a Floating Point Calculation issue? - python

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.")

Related

Transform the ERL in python

Transform the ERL for one or more selection statements to decide whether a year is a Leap year.
The rules are:
A year is generally a Leap Year if it is divisible by 4, except that if the year is divisible by 100, it is not a Leap year, unless it is also divisible by 400.
Thus 1900 was not a Leap Year, but 2000 was a Leap year.
year = int(input ("What year would you like to assess? "))
leapYear = False #Setting a flag which will be assessed at the end
#the if statements are checking to see if the conditions #are true to assess it as a leap year
if year mod 4 == 0 then
leapYear = True
endif
if year mod 100 == 0 then
leapYear = False
end if
if year mod 400 == 0 then
leapYear = True
end if
if leapYear == True then
print("This is a leap year")
else
print("This is not a leap year")
end if

Python script for Gregorian Epact [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I want to write a script that will return the Gregorian epact.
The program asks the user to provids a year.
It checks if the input is correct (i.e. number).
It determines the number of digits of the given number (4 here).
If the user fails five to provides a correct input the scripts terminates.
Here is my script.
I think it is rather complicated. How could I simplify it?
# Program for the calculation of the Gregorian epact
import math as m # Python's basic mathematical library
print("This program calculates the Gregorian epact value of a given year.")
print("See https://fr.wikipedia.org/wiki/%C3%89pacte for further details.")
is_year_correct = False
n = 0
while (not is_year_correct) and n<=4:
year = input("Enter the year (e.g. 2020): ") # User provides a year
try:
year = int(year)
digits = int(m.log10(year))+1 # number of digits in year
except ValueError:
print("Please, try again by entering a year!")
if digits == 4:
is_year_correct = True
else:
print("Please enter a four digit number.")
n = n+1
if n<=4:
c = year // 100
epact = (8+(c//4) - c + ((8*c + 13)//25) + 11 * (year % 19)) % 30
print("The epact value is", epact, "days.")
else:
print('No more attempts!')
Wow learning about epact led me on a rabbit hole
I have minimized the code a bit however I lost some functionality...
I have a way to make sure the functionality is ensured and I will share the piece of code in a sec:
Code with comments:
# Program for the calculation of the Gregorian epact
print("This program calculates the Gregorian epact value of a given year.")
print("See https://fr.wikipedia.org/wiki/%C3%89pacte for further details.")
# Infinite loop
while True:
# Tries to convert the user's input into a number
try:
year = int(input("Enter the year (e.g. 2020): ")) # User provides a year
# All code under this will NOT be executed if user doesn't enter a number
# as the code above will raise an exception causing us to go to the
# exception area
# If year is less than 1000 we warn else we leave infinite loop
if year < 1000: print("Please enter a four digit number.")
else: break
# If user enters a letter
except ValueError:
print("Please, try again by entering a year!")
# Epact calculations
c = year // 100
epact = (8+(c//4) - c + ((8*c + 13)//25) + 11 * (year % 19)) % 30
print(f"The epact value is {epact} days.")
Code without Comments:
# Program for the calculation of the Gregorian epact
print("This program calculates the Gregorian epact value of a given year.")
print("See https://fr.wikipedia.org/wiki/%C3%89pacte for further details.")
while True:
try:
year = int(input("Enter the year (e.g. 2020): ")) # User provides a year
if year < 1000: print("Please enter a four digit number.")
else: break
except ValueError:
print("Please, try again by entering a year!")
c = year // 100
epact = (8+(c//4) - c + ((8*c + 13)//25) + 11 * (year % 19)) % 30
print(f"The epact value is {epact} days.")
All functionality
# Program for the calculation of the Gregorian epact
print("This program calculates the Gregorian epact value of a given year.")
print("See https://fr.wikipedia.org/wiki/%C3%89pacte for further details.")
for _ in range(5):
try:
year = int(input("Enter the year (e.g. 2020): ")) # User provides a year
if year < 1000: print("Please enter a four digit number.")
else: break
except ValueError:
print("Please, try again by entering a year!")
try:
c = year // 100
epact = (8+(c//4) - c + ((8*c + 13)//25) + 11 * (year % 19)) % 30
print(f"The epact value is {epact} days.")
except: print("No more tries!")

A TypeError prevents me from forming the conditionals of my function (Python)

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")

For loop - Leap year input

could anyone please help me with a current problem Im having... Its a leap year exercise.
● Write a program to input a year and a number of years.
● Then determine and display which of those years were or will be leap
years.
Example:
What year do you want to start with? - 1994
How many years do you want to check? - 8
1994 isn’t a leap year
1995 isn’t a leap year
1996 is a leap year
1997 isn’t a leap year
1998 isn’t a leap year
1999 isn’t a leap year
2000 is a leap year
2001 isn’t a leap year
I cant seem to get my years to display there own value of being a leap year or not....this is the code i have so far:
year = int(input("Please enter the year you would like to start checking leap years from."))
total_years = int(input("Please enter over how many years you would like to check."))
leap_year= 0
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
leap_year = ("this is a leap year")
else:
leap_year = ("this is not a leap year")
for a in range (0,total_years):
print(year + a, leap_year)
Any help will be greatly appreciated.
Thank you.
You need to put the logic for checking the years into the loop. For example like so:
start_year = int(input("Please select a starting year: "))
num_of_years = int(input("Please select how many years you'd like to check: "))
end_year = start_year + num_of_years
# The formula I used below to determine when a year is a leap year was copied from emrah-diril in this thread
for year in range(start_year-1, end_year):
year += 1
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print ("{}: Is a leap year".format(year))
else:
print (year)
The if-else block that checks for leap year should be inside the for loop. It's currently outside the for loop so it checks the first year you enter and the for loop simply prints the result for the first year total_years number of times.
So, to fix your code, try something like this:
year = int(input("Please enter the year you would like to start checking leap years from."))
total_years = int(input("Please enter over how many years you would like to check."))
def is_leap_year(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
for a in range (0, total_years):
if is_leap_year(year+a):
print("this is a leap year")
else:
print("this is not a leap year")
python
start_year = int(input("Please enter the year you would like to start checking leap years from: "))
total_years = int(input("Please enter over how many years you would like to check: "))
for year in range(start_year, start_year + total_years):
if year % 4 == 0:
print(f"{year} is a leap year")
else:
print (f"{year} is not a leap year")

Python Function: that replies YES or NO -something is wrong

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).

Categories

Resources