Transform the ERL in python - 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

Related

How do I fix a Floating Point Calculation issue?

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

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 leap year calculator (between two years selected by the user)

I can't find the correct loops to use to make this code work!
I tried to use a while loop and I could get Python to show all the leap years between the two years selected by the user but not in the formatting that I was asked to use.
start = int(input("Enter start year: "))
end = int(input("Enter end year: "))
if start < end:
print ("Here is a list of leap years between " + str(start) + " and " + str(end) + ":")
while start < end:
if start % 4 == 0 and start % 100 != 0:
print(start)
if start % 100 == 0 and start % 400 == 0:
print(start)
start += 1
if start >= end:
print("Check your year input again.")
Problem description: A year is a leap year if it is divisible by four, except that any year divisible by 100 is
a leap year only if it is also divisible by 400. Write a program which works out the
leap years between two years given by the user. The program should list 10 leap
years per line, with commas between each year listed and a full stop at the end, as
in the following example input/output:
Enter start year: 1000
Enter end year: 1200
Here is a list of leap years between 1000 and 1200:
1004, 1008, 1012, 1016, 1020, 1024, 1028, 1032, 1036, 1040,
1044, 1048, 1052, 1056, 1060, 1064, 1068, 1072, 1076, 1080,
1084, 1088, 1092, 1096, 1104, 1108, 1112, 1116, 1120, 1124,
1128, 1132, 1136, 1140, 1144, 1148, 1152, 1156, 1160, 1164,
1168, 1172, 1176, 1180, 1184, 1188, 1192, 1196, 1200.
Hints: the answer uses a for loop to work through all the years from the start year to the
end year, an extra variable as a leap year counter, and various if and if-else statements
inside the loop to check if the year is a leap year, if a comma is needed, and if a new line
is needed.
The condition should be different -
if (start % 4 == 0 and start % 100 != 0) or (start % 4 == 0 and start % 400 == 0):
Also in order to include the end year in the range the loop condition should be -
while start <= end:
obtaining leap years:
start = int(input("Enter start year: "))
end = int(input("Enter end year: "))
list(range(start + (4 - start % 4), end + 1, 4))
I'm afraid I disagree with the hint that you use a counter to determine whether to print a comma or a full stop followed by a newline. It makes for a very complicated loop. The problem arises with the last line, which might have fewer than 10 year numbers in it. I reckon you still want a full stop not a comma at the end of that line.
Instead of printing your line inside a loop, build a table of years and format it afterwards. I've changed your solution as little as possible. One change that you did not ask for involved fixing the input validation.
start = int(input("Enter start year: "))
end = int(input("Enter end year: "))
while start >= end:
print("Check your year input again.")
start = int(input("Enter start year: "))
end = int(input("Enter end year: "))
print ("Here is a list of leap years between {0} and {1}:".format(start,end))
leap_years = []
while start <= end:
if start % 4 == 0 and start % 100 != 0:
leap_years.append(str(start))
if start % 100 == 0 and start % 400 == 0:
leap_years.append(str(start))
start += 1
for line in range(0, len(leap_years), 10):
print ("{0}.".format(", ".join(leap_years[line:line+10])))
Here is an elegant solution I thought might help you out:
start = int(input("Enter start year: "))
end = int(input("Enter end year: "))
if start <= end:
leap_years = [str(x + start) for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
leap_years[-1] += "."
print(f"Here is a list of leap years between {start} and {end}:\n{(', '.join(leap_years))}")
else:
print("Check your input years again!")
An explanation for this? Essentially it makes a range between your start and end year and loops over it to see if it's divisible by 4 and NOT divisible by 400, if so; it adds it to an array that we can join using , and then add a period at the end and display this to the user using f-strings.
As the hint says, use a counter.
This counter should count the number of leap years you have printed. Every tenth leap year, you end the output with a newline, otherwise with comma and space.
To get the numbers right, just add a variable leap_year_counter and check if ==10 and reset or %10, then you can also output how many you found at the end.
To actually print with the correct ending, use the end keyword argument of the print function (print(value, end=<end you want>).
The for loop part of the hint probably expects you to use for year in range(start, stop) instead of the while loop.
start = int(input("Enter start year: "))
end = int(input("Enter end year: "))
if start > end:
print("Check your year input again.")
else:
print ("Here is a list of leap years between " + str(start) + " and " + str(end) + ":")
while(start <= end):
if start % 100 == 0 and start % 400 == 0:
print(start)
start += 1
if start % 4 == 0 and start % 100 != 0:
print(start)
start += 1
else:
start += 1
You need to add else part. Because program can't do anything when there is not a leap year.
Try it:
while start < end:
if start % 4 == 0:
if start % 100 == 0:
if start % 400 == 0:
print("{} is a leap year".format(start))
else:
print("{} is not a leap year".format(start))
else:
print("{} is a leap year".format(start))
else:
print("{} is not a leap year".format(start))
start += 1
Out:
Enter start year: 2000
Enter end year: 2020
2000 is a leap year
2001 is not a leap year
2002 is not a leap year
2003 is not a leap year
2004 is a leap year
2005 is not a leap year
2006 is not a leap year
2007 is not a leap year
2008 is a leap year
2009 is not a leap year
2010 is not a leap year
2011 is not a leap year
2012 is a leap year
2013 is not a leap year
2014 is not a leap year
2015 is not a leap year
2016 is a leap year
2017 is not a leap year
2018 is not a leap year
2019 is not a leap year
[NOTE]:
You could also use for start in range(start, end) instead of the while start < end and start += 1
for yr in range(399, 510):
if (yr%4==0):
if(yr%100==0):
if (yr%400==0):
print(f" leap year {yr}")
else:
print(f" leap year {yr}")
i think this is most easy way to print out all the leaps yrs in given range
y = int(input("Enter year: "))
count=0
if y < 1600 :
print("check your year input again")
for i in range(1600,y):
if i % 400 == 0 and i % 100 != 0:
print(i, "is a Leap Year")
elif i % 4 == 0 :
count += 1
print(i, "is a Leap Year.")
print("Total leap year: {}".format(count))

dictionary problem in python with index error

I am writing the program to get two dictionaries, dict1 with names as keys and the number of wins as values, dict 2 with years as keys and the number of times won as values. My question is when I try to get the current year inside the for loop which need for the dict 1, it's always giving me and "index error: list index out of range"
and the problem is here as it shows "year_team[year]=winners[year-1903]".
def main():
dfile=open('worldserieswinners.txt','r')
winners=dfile.read().splitlines()
team_wins={}
year_team={}
for team in winners:
if team not in team_wins:
team_wins[team]=1
else:
team_wins[team]+=1
for year in range(1903, 2010):
if year != 1904 and year != 1994:
year_team[year]=winners[year-1903]
year=int(input('Enter a year between 1903 and 2009 or 0 to quit: '))
while year!= 0:
if year == 1904 or year == 1994:
print('Not played in this year')
elif 1903>year or year>2009:
print('Invalid choice')
else:
team=year_team[year]
wins=team_wins[team]
print('The winning team in',year,'was the',team)
print('The',team,'won',wins,'times between 1903 and 2009.')
year= int(input('Enter a year between 1903 and 2009 or 0 to quit: '))
dfile.close()
main()
Presumably your 'worldserieswinners.txt' file has less than 107 (2010 − 1903) lines, so that the index year-1903 gets out of range.

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