Looking for a solution to combine two 'get' methods to have a single method.
The program calculate present value, future value, and future value of an annuity. Currently I have two methods "getAmount" and "getTerm", which are float and integer values respectively, that receive and validate user input. I think it is possible to combine them into a single method by evaluating them as a string. Am I on the right track?
This is my code to find the present value. The first thing I tried was to validate the input as a number but I quickly found that was not the way to go about it as I received the error float cannot be converted to int.
#Present Value
amount = getAmount("Amount to be received: ") #float value
rate = getAmount("Annual Interest Rate (6%=6): ") #float value
term = getTerm() #integer value
pv = calcPV(amount,rate,term)
df = 1 + rate) ** term
print("An amount of amount: " + amount)
print("to be received in " + str(term) + " months "
+ "with an annual cost of money of: " + rate
+ "has a value today of: " + pv)
print("That includes a discount of: " + df)
def calcPV(amount,rate,term):
monthlyRate = rate / 100 / 12
pv = amount / ((1 + monthlyRate) ** term)
return pv
def getAmount(prompt):
amt = -1
while (amt <= 0):
try:
amt = float(input(prompt))
if (amt <= 0):
print("Positive values only")
except ValueError:
print("Illegal input: the amount must be greater than 0.")
amt = -1
return amt
def getTerm():
amt = -1
while (amt <= 0):
try:
amt = int(input("Term (in month): "))
if (amt <= 0):
print("Positive values only")
except ValueError:
print("Illegal input: the amount must be greater than 0.")
amt = -1
return amt
Related
I am new to python and trying to calculate a running total while validating the user input. If the user inputs invalid data I am showing an error and asking the user to input the correct data. My issue is I am unable to determine how to calculate only the valid data input from the user instead of all values.
# This program calculates the sum of a series
# of numbers entered by the user.
#Initialize an accumulator variable.
total = 0
#Request max value from user.
max_value = int(input("Enter a value for the maximum number: "))
#Request user to enter value between 1 and max value.
number = int(input("Enter a number between 1 and " + str(max_value) + " or negative number to end: "))
#Calculate total of user input values.
while number > 0:
total = total + number
number = int(input("Enter a number between 1 and " + str(max_value) + " or negative number to end:"))
#Display error if user entered invalid value.
if number == 0 or number > max_value:
print("Number entered is invalid!")
#Print sum of valid user input data.
else:
print("Sum of all valid numbers you entered:", total)
I can see that you have added too much unnecessary code and this is a very bad practice in python. I believe that this is the answer you are looking for:
f"" = is called a formatted string and
the while loop is unnecessary
so after that, you should import sys and use the exit function under a while loop and exit under a for loop
from sys import exit as exit1
while True:
max_value = int(input("Enter a value for the maximum number: "))
if max_value<0:
break
number = int(input(f"Enter a number between 1 and {max_value} or negative number to end: "))
total = max_value + number
if number == 0 or number > max_value:
print("Number entered is invalid!")
else:
print("Sum of all valid numbers you entered:", total)
So after reevaluating the code I wrote the first time I came up with the below and it functions as I would like. For a beginner that has only learned three chapters I think it is good. Current knowledge base is Input, Processing, Output, Decision Structures, Boolean Logic, and Repetition Structures.
# This program calculates the sum of a series
# of numbers entered by the user.
#Initialize an accumulator variable.
total = 0
# Request max value from user.
max_value = int(input("Enter a value for the maximum number: "))
#Request number between 1 and max value.
number = int(input("Enter a number between 1 and " + str(max_value) + " or negative
number to end: "))
#Validate the user input is between 1 and max value
# if so accumulate the number.
while number >= 0:
if number > 0 and number <= max_value:
total = total + number
elif number == 0 or number > max_value:
print("Number entered is invalid!")
number = int(input("Enter a number between 1 and " + str(max_value) + " or negative number to end: "))
#Once user select a negative number, print total.
else:
print("Sum of all valid numbers you entered:", total)
I am trying to write a program that calculates the grades, calculates the average, and shows a error when letters are typed in. I think I am pretty much done with the code, but I am confused on how to fix "TypeError: 'float' object is not iterable" problem.
def calculate_average(total, count):
average = total / count
return average
while 1:
try:
grade = float(input("Enter a test score, or a negative number to get the average: "))
total = sum(grade)
count = len(grade)
if grade < 0:
break
average = calculate_average(total, count)
print("Total: ", total)
print("Average:", round(average))
except ValueError:
print("BRUH")
Obviously you want to user to input multiple numbers. However, in your code the user can only enter a single number and a single foat can obviously not be summed up nor has it a length.
You need a list containing all grades and after the user has entered all grades and entered a negative number you can evaluate that list and calculate the average.
Here is a working example:
def calculate_average(total, count):
average = total / count
return average
while 1:
grades = []
while 1:
inp = input("Enter a test score, or a negative number to get the average: ")
try:
inpGrade = float(inp)
if inpGrade > 0:
grades.append(inpGrade)
elif inpGrade < 0:
break
except ValueError:
print("BRUH")
total = sum(grades)
count = len(grades)
average = calculate_average(total, count)
print("Total: ", total)
print("Average:", round(average))
break
Having an issue with a certain part of the code (I am new to coding and have tried looking through StackOverflow for help):
def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = rainfall[month] + totalRain
month += 1
return totalRain
TypeError: Can't convert 'int' object to str implicitly
I've tried multiple ways of changing the code to make it a string explicitly as it still giving me various issues.
I'm also having a hard time enhancing the code to sort the array in ascending order and displays the values it contains.
The full code is here:
def main ():
rainfall = rainInput ()
totalRain = totalRainfall (rainfall)
average_Rainfall = averageRainfall (totalRain)
highestMonth, highestMonthly = highestMonthNumber (rainfall)
lowestMonth, lowestMonthly = lowestMonthNumber (rainfall)
print #this is for spacing output
print ('The total rainfall for the year was: ' +str(totalRain) + ' inche(s)')
print #this is for spacing output
print ('The average rainfall for the year was: ' +str(average_Rainfall) +\
' inche(s)')
print #this is for spacing in output
print ('The highest amount of rain was', highestMonthly, 'in' , highestMonth)
print #this is for spacing in output
print ('The lowest amount of rain was', lowestMonthly, 'in' , lowestMonth)
def rainInput ():
rainfall = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
month = 0
while month < len(rainfall):
rainfall[month] = input ('Please enter the amount for month ' + str\
(month + 1) + ': ')
month += 1
return rainfall
def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = rainfall[month] + totalRain
month += 1
return totalRain
def averageRainfall (totalRain):
average_Rainfall = totalRain / 12
return average_Rainfall
def highestMonthNumber (rainfall):
month = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
highestMonthly = 0
for m, n in enumerate(rainfall):
if n > highestMonthly:
highestMonthly = n
highestMonth = m
return month[highestMonth], highestMonthly
def lowestMonthNumber (rainfall):
month = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
lowestMonthly = 0
for m, n in enumerate(rainfall):
if n < lowestMonthly:
lowestMonthly = n
lowestMonth = m
return month[lowestMonth], lowestMonthly
main()
You have stored strings in your array rainfall, you need to convert them to ints before adding.
def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = int(rainfall[month]) + totalRain
month += 1
return totalRain
If you want the total rainfall as the sum of the numbers per month, simply use sum() on the list of ints. But as your error suggests, you have a list of strings, which you explicitly have to convert.
Something along the lines of
def totalRainfall (rainfall):
return sum([int(x) for x in rainfall])
The problem with your list being strings will continue to be problematic for you, so as a quick fix, I suggest you change this line
rainfall[month] = input ('Please enter the amount for month ' + str\
(month + 1) + ': ')
to
rainfall[month] = int(input('Please enter the amount for month ' + str\
(month + 1) + ': '))
That way your list contains only numbers and all your other comparisons will work.
You should also add this initialization in your lowestMonthNumber function to avoid UnboundLocalError: local variable 'lowestMonth' referenced before assignment:
lowestMonth = 0
Notice, that by initializing lowestMonthly to 0, you will most likely never get a correct result, since it is highly unlikely that any month has less rainfall.
This program is designed to count an unspecified amount of integers,
determines how many negative and positive values have been read,
and computes the average and total of the input values.
If the user inputs a 0, the program will end. Every time I enter a 0, I get an error stating "division by zero". The debugger says it is from the very last line.
I guess it has to to with the sum / count part. When I use negative numbers, it says the same thing, from the same line of code. Lastly, I am unsure how to display the text "You didn't enter any number". I tried doing the if else statement, but I don't think I'm doing that correctly.
data = eval(input("Enter an integer, the input ends if it is 0: "))
count = 0
sum = 0
negCount = 0
if data != 0:
while data > 0:
count = count + 1
sum = sum + data
data = eval(input("Enter an integer, the input ends if it is 0: "))
while data < 0:
negCount = count + 1
sum = sum + data
data = eval(input("Enter an integer, the input ends if it is 0: "))
while data != 0:
sum = sum + data
data = eval(input("Enter an integer, the input ends if it is 0: "))
break
else:
print("You didn't enter any number")
print("The number of positives is", count)
print("The number of negatives is", negCount)
print("The total is", sum)
print("The average is", sum / count)
output = []
while True:
data = int(input("Enter an integer, the input ends if it is 0: "))
if data == 0:
break
output.append(data)
positives = len([i for i in output if i > 0])
negatives = len(output) - positives
total = sum(output)
if len(output) != 0:
print("The number of positives is", positives)
print("The number of negatives is", negatives)
print("The total is", total)
print("The average is", total / len(output))
else:
print("You didn't enter any number")
If you enter 0, the if block is skipped (if data != 0). If the if block is skipped, count is 0. If count is 0, sum / count is undefined mathematically, and will raise a ZeroDivisionError.
Write a function that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
I am having the error " ValueError: unsupported format character 'I' (0x49) at index 28"
Here is my code so far.
def BankBalance():
InputB = 1000
return InputB
print("Your initial balance is $1000")
def Interest():
InputI = 0.05
return InputI
print("The rate of interest is 5%")
def CountNumber():
InputN = float(input("Please enter the number of times per year you would like your interest to be compounded: "))
return InputN
def Time():
InputT = float(input("Please enter the number of years you need to compund interest for:"))
return InputT
def Compount_Interest(InputB, InputI, InputT, InputN):
Cinterest = (InputB*(1+(InputI % InputN))**(InputN * InputT))
print("The compound interest for %.InputT years is %.Cinterest" %Cinterest)
B = BankBalance()
I = Interest()
N = CountNumber()
T = Time()
Compount_Interest(B, I, N, T)
Here is how you would do it.
def main():
# Getting input for Balance
balance = float(input("Balance: $ "))
# Getting input for Interest Rate
intRate = float(input("Interest Rate (%) : "))
# Getting input for Number of Years
years = int(input("Years: "))
newBalance = calcBalance(balance, intRate, years)
print ("New baance: $%.2f" %(newBalance))
def calcBalance(bal, int, yrs):
newBal = bal
for i in range(yrs):
newBal = newBal + newBal * int/100
return newBal
# Program run
main()
You are trying to use your variable as a function.
Try this instead :
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
Python, and most other programming languages, don't assume that two adjacent mathematical expressions with no operator between them means multiplication. You are missing a multiplication operator (*) between InputB and the rest of the expression:
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
# Here -------------^