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!")
Related
I'm writing a program that asks a user to input a number of years. and then asks the user to input a yearly tax amount until the specified number of years is met. Then the program needs to output the maximum yearly income tax based on those user inputs. All of my program is working except for the maximum part. It keeps giving me a random number whenever I try to output a maximum value.
Is anyone able to tell me where I'm going wrong?
Below is my code:
`enter code here`
years = int(input('Number of years: '))
if years == 0:
print('Could not calculate maximum tax given.')
exit()
for i in range(years):
tax = input("Income tax given for year " +str(i+1)+ "($): ")
maximum = 0
for x in range(int(tax)):
if (maximum==0 or maximum<x):
maximum = x
print('Maximum tax given in a year($): ' + str(maximum))
You should add the tax input to a list, otherwise it will be overwritten. to get the max number you can use max().
years = int(input('Number of years: '))
if years == 0:
print('Could not calculate maximum tax given.')
exit()
tax=[]
for i in range(years):
tax.append(int(input("Income tax given for year " +str(i+1)+ "($): ")))
maximum = 0
for x in tax:
if (maximum==0 or maximum<x):
maximum = x
print('Maximum tax given in a year($): ' + str(maximum))
print('Maximum tax given in a year($): (using max()) ' + str(max(tax)))
The answer Kilian gave is spot on, just one suggestion though.
Python print of integers or Numbers should be like this:
print('Maximum tax given in a year($): (using max()) %d' %max(tax))
I need the loop to stop at 12 months and not count all the way up to how many months it takes to reach the goal. I just need it to print how many months it takes to reach the goal but not count all the way to it. I only need it to go up to 12 months. For example if I input an original deposit for 1000, 4.5 interest rate, 12 months, and 1200 goal amount then I want it to only show it counting to 12 months not 49. I still need it to print out how many months it takes to reach the goal at the end but I do not need it to show it counting all the way up to 49. I am sorry if this sounds confusing.
#Keep asking until the user puts in a positive numeric value using loops
fDeposit = 0
while fDeposit <= 0:
try:
fDeposit = float(input('What is the original deposit (positive value): '))
if fDeposit <= 0:
print("Input must be a positive numerical value: ")
except ValueError:
print("Input must be a numeric value")
fInterest = 0
while fInterest <= 0:
try:
fInterest = float(input('What is the Interest Rate (positive value): '))
if fInterest <= 0:
print("Input must be a positive numerical value: ")
except ValueError:
print("Input must be a numeric value")
iMonths = 0
while iMonths <= 0:
try:
iMonths = int(input('What is the number of months (positive value): '))
if iMonths <= 0:
print("Input must be a positive numerical value: ")
except ValueError:
print("Input must be a numeric value")
fGoal = None
while fGoal == None:
try:
fGoal = float(input('What is the goal amount (Can enter 0 but not negative): '))
if fGoal < 0:
print("Input must be a positive numerical value: ")
fGoal = None
except ValueError:
print("Input must be a numeric value")
# Calculate Interest. First convert the variable to a decimal by dividing by 100 then divide
that by 12
fMonthlyInterest= (fInterest/100/12)
#Output the number of months the user has supplied and get account balance
i = 1
fAccountBalance = fDeposit
while i <= fAccountBalance:
if fAccountBalance >= fGoal:
break
fInterestForMonth = (fAccountBalance * fMonthlyInterest)
#Add the interest for the month to the deposit to get the new Account Balance
fAccountBalance += fInterestForMonth
print('Month: ',i, 'Account Balance is: $',format(fAccountBalance, ",.2f"))
i += 1
# Calculate how many months it will take of compounding to reach the goal amount
GoalFormatted = "{:.2f}".format(fGoal)
CompoundedSavingsAccountBalance = fMonthlyInterest + fAccountBalance
while CompoundedSavingsAccountBalance < fGoal:
iMonths += 1
print('It will take: ',i-1, 'months to reach the goal of $', GoalFormatted)
to solve your problem, add "if i < 12:" after line 52, and indent the next line where you printing the month & the account balance. The completed section is below.
i = 1
fAccountBalance = fDeposit
while i <= fAccountBalance:
if fAccountBalance >= fGoal:
break
fInterestForMonth = (fAccountBalance * fMonthlyInterest)
#Add the interest for the month to the deposit to get the new Account Balance
fAccountBalance += fInterestForMonth
if i <= 12:
print('Month: ',i, 'Account Balance is: $',format(fAccountBalance, ",.2f"))
i += 1
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.")
This question already has answers here:
Python: How to keep repeating a program until a specific input is obtained? [duplicate]
(4 answers)
Closed 5 years ago.
I am fairly new to Python and I'm trying to create a simple program to calculate, then print, how much a vacation rental is based on the number of weeks a user has inputted (so long as the number of weeks is greater than 4, but less than 16). I have that part of the code down just fine, but what I am having trouble with is getting the program to repeat the question if a user does enter a number that is not in range. Any help would be greatly appreciated. Here is my code:
weeks = 0
total = 0
while True:
try:
weeks = int(input("How many weeks do you plan on vacationing? "))
break
except ValueError:
print("Please enter a number.")
if weeks < 4:
print("Not in range.")
elif weeks <= 6:
total = weeks*3080
print("Rental cost: $",total)
elif weeks <= 10:
total = weeks*2650
print("Rental cost: $", total)
elif weeks <=16:
total = weeks*2090
print("Rental cost: $", total)
else:
print("Not in range.")
Update:
weeks = 0
total = 0
while True:
try:
weeks = int(input("How many weeks do you plan on vacationing? "))
if weeks < 4:
print("Not in range.")
continue
elif weeks <= 6:
total = weeks*3080
print("Rental cost: $",total)
break
elif weeks <= 10:
total = weeks*2650
print("Rental cost: $", total)
break
elif weeks <=16:
total = weeks*2090
print("Rental cost: $", total)
break
else:
print("Not in range.")
except ValueError:
print("Please enter a number.")
Validate weeks in the try block and raise ValueError before the break if out of range.
Trying to do a Boolean test loop where the user needs to enter a number between 10 and 1000 including 10 and 1000, they need to stay in this loop until they enter the correct number once they do then I will finish the else statement.
I tried this:
while (num_years < 10) and (num_years > 1000): # boolean test , note == (= will give you an error!)
print("Your input must be 10 and 1000")
input("Enter number of years to simulate (currently " + str(num_years) + "): ")
else:
print()
AND this:
while (num_years == range(10, 1000)): # boolean test , note == (= will give you an error!)
print("Your input must be 10 and 1000")
input("Enter number of years to simulate (currently " + str(num_years) + "): ")
else:
print()
You could try something like this as it also checks if the user inputs a valid number:
while True:
number = input("Enter number of years to simulate (10-1000): ")
try:
years = int(number)
if years >= 10 and years <= 1000:
break
else:
print("Your input must be between 10 and 1000 inclusive")
except ValueError:
print("That's not an int!")
print("Simulating %d years..." % years)
Example Usage:
Enter number of years to simulate (10-1000): asd
That's not an int!
Enter number of years to simulate (10-1000): 5
Your input must be between 10 and 1000 inclusive
Enter number of years to simulate (10-1000): 245
Simulating 245 years...
Try it here!
You are never changing the value of num_years so the condition will never change. Fixing your boolean logic:
num_years = 0
while (num_years < 10) or (num_years > 1000):
print("Your input must be 10 and 1000")
num_years = int(input("Enter number of years to simulate (currently {}): ".format(num_years)))
else:
print()
However, this assumes someone is entering a number if you need to cover a non-numeric value then use a try: except: pass block:
try:
num_years = int(input("Enter number of years to simulate (currently {}): ".format(num_years)))
except ValueError:
pass
Note: = is assignment not an equality test. Use in to test if a value is in a list or range.
Okay, first of all:
(num_years < 10) and (num_years > 1000)
this is always False since one number cannot be less than 10 and more than 1000 at the same time.
Second of all
num_years == range(10, 1000)
will never work since you have (probably) integer on the left and generator on the right.
However you might try something like that:
possible_years = range(10,101)
num_years = 50
while num_years in possible_years: # or 9 < num_years < 100
print("Your input must be 10 and 1000")
entered_years = input("Enter number of years to simulate (currently " + str(num_years) + "): ")
num_years = int(entered_years) # remeber to check if entered_years is int before this line!
else:
print()
However there is still a catch, you need to check if user entered an integer.
What you need to do is a while loop to check whether the input is valid. If it's not, it will loop again. Also you never assign the input to a variable.
n = None
while n is None or not 10 <= n <= 1000:
if n is not None: # Only happens if it's not the first input
print('Invalid number, please try again')
try:
n = int( input('Enter number of years to simulate (10-1000): ') ) # Convert the
# string to an int
except:
pass
print( 'Simulating {} years...'.format(n) )
It will continue and say simulating once a valid number is input because
not 10 <= n <= 1000
will evaluate to false.
You can try it at this link: https://repl.it/FftK/0
n = None
while n is None or not 10 <= n <= 1000:
if n is not None: # Only happens if it's not the first input
print('Invalid number, please try again')
try:
n = int( input('Enter number of years to simulate (10-1000): ') ) # Convert the
# string to an int
except:
pass
print( 'Simulating {} years...'.format(n) )