Combining inputs and math - python

I am trying to build a future value calculator using inputs but running into trouble with the math. Can someone please advise on a solution? Also, how could I convert the responses into integers or floats before calculating?
present= input("What is the present value?")
rate = input("What is the rate of return?")
periods = input("What is the number of periods?")
answer = {present} * (1 + {rate} ** {periods})
print(f"The future value is", int(answer))

Just put float around them (a decimal number)
present= float(input("What is the present value?"))
rate = float(input("What is the rate of return?"))
periods = float(input("What is the number of periods?"))
answer = present * (1 + rate ** periods)
print(f"The future value is", str(answer))

You need to convert your inputs to numbers (either float or int) before doing math on them. The curly-brace syntax isn't needed when you're doing math operations (in that context it's interpreted as a set literal, which is not what you want here), but it is used within f-strings to format variables as strings.
present= float(input("What is the present value?"))
rate = float(input("What is the rate of return?"))
periods = int(input("What is the number of periods?"))
answer = present * (1 + rate) ** periods
print(f"The future value is {answer}")
(edit) also, I think you want to raise (1 + rate) to the power of periods rather than the way you had the parentheses.

you can use int() to convert input into integer.
present= int(input("What is the present value?"))
rate =float( input("What is the rate of return?"))
periods = int( input("What is the number of periods?"))
answer = present * (1 + rate ** periods)
print(f"The future value is", int(answer))

The first thing to note is that your formula for future value is incorrect. It should be pv*(1+r)^n, rather than pv*(1+r^n). This is assuming your rate (r) corresponds to the rate for each period.
Here some quick code that does what you are probably looking for:
pv = float(input("what is the pv? "))
r = float(input("what is the rate? "))
n = float(input("how many periods? "))
print("The future value is {}".format(pv*(1+r)**n))
Output:
what is the pv? 1
what is the rate? 0.05
how many periods? 10
The future value is 1.628894626777442

Related

my simple_interest function is returning 0 and i'm not sure why even though i think my math is correct

i'm trying to make a program that calculates simple interest and the function i made to calculate the interest returns 0 when i run it and i don't know what the problem is
`year = int(input("Enter years: "))
month = int(input("Enter months: "))
days = int(input("Enter days: "))
totalYears = float()
interest = float()
def get_time():
totalYears = round(year + (month * 31 + days)/365,1)
print("total time in years is",totalYears,"years")
principal = float(input("Enter principal: "))
rate = float(input("Enter rate (in %): "))
def simple_interest():
interest = round(principal * rate/100 * totalYears,2)
print("Total interest earned is $",interest)
get_time()
simple_interest()`
i tried intializing the principal and rate at the start even though i know it's unnecessary since it's intialized when i ask for the input, i assume the problem is with the variables but i can't find it if it is.
The variable TotalYears in the get_time function is not the same as the variable TotalYears referenced outside the function. When you want to assign a value to TotalYears in get_time, you need to declare "Global" to let python know that you are referencing the variable outside the scope of the get_time function.
year = int(input("Enter years: "))
month = int(input("Enter months: "))
days = int(input("Enter days: "))
totalYears = float()
interest = float()
principal = float(input("Enter principal: "))
rate = float(input("Enter rate (in %): "))
def get_time():
global totalYears
totalYears = round(year + (month * 31 + days)/365,1)
print("total time in years is",totalYears,"years")
def simple_interest():
interest = round(principal * (rate/100) * totalYears,2)
print("Total interest earned is $",interest)
get_time()
simple_interest()
When you initialise totalYears as float(), it gets defined in the global variable scope. When you then define totalYears by calling the function get_time(), that version of totalYears gets defined inside the scope of the get_time() function call. When that function call ends, the value of totalYears is extinguished - and never gets returned for use by any other function.
So the version of totalYears that's available to your next function call - simple_interest is 0.0 - the original version you initialised in the global scope, not the version you defined in the scope of get_time().
If you want totalYears to be defined inside get_time(), and then be available for use by simple_interest(), I would suggest something like this:
year = int(input("Enter years: "))
month = int(input("Enter months: "))
days = int(input("Enter days: "))
totalYears = float()
interest = float()
def get_time():
totalYears = round(year + (month * 31 + days)/365,1)
print("total time in years is",totalYears,"years")
return totalYears
principal = float(input("Enter principal: "))
rate = float(input("Enter rate (in %): "))
def simple_interest(totalYears):
interest = principal * rate/100 * totalYears
print(f'Total interest earned is ${round(interest, 2)}')
totalYears = get_time()
simple_interest(totalYears)
If I call run your script with 5 years, 3 months, 2 days, $1000 in principal and a rate of 2%, I get the following output:
Enter years: 5
Enter months: 3
Enter days: 2
Enter principal: 1000
Enter rate (in %): 2
total time in years is 5.3 years
Total interest earned is $106.0
That addresses your immediate question - but a couple of points to note:
First: You don't have to define totalYears and interest as empty floats. You could delete totalYears = float() and interest = float() from your script and make no difference to how it runs.
Second: It's a lot easier to manage/analyse/debug your code if you try to keep your functions pure - with inputs and outputs passed into and returned from those functions. An example of how your code might be refactored to reflect this approach below:
def get_inputs():
year = int(input("Enter years: "))
month = int(input("Enter months: "))
days = int(input("Enter days: "))
principal = float(input("Enter principal: "))
rate = float(input("Enter rate (in %): "))
return year, month, days, principal, rate
get_inputs gets inputs from the user and returns these inputs as five clearly named variables. This function is not "pure" - i.e. it interacts with other things (i.e. the user).
def get_time(year, month, days):
totalYears = round(year + (month * 31 + days)/365,1)
return totalYears
def simple_interest(principal, rate, totalYears):
interest = principal * rate/100 * totalYears
return interest
get_time and simple_interest are pure - in that their behaviour depends ONLY on the inputs provided to them - they have no "side effects", they don't print anything to the screen, they don't modify anything outside the scope of the function call. Their behaviour is entirely predictable and stable.
def print_outputs(totalYears, interest):
print(f'total time in years is {totalYears} years')
print(f'Total interest earned is ${round(interest, 2)}')
print_outputs like get_inputs is not pure - but it IS predictable - it takes in two inputs, and the resulting behaviour is an always predictable, repeatable output to the screen. It doesn't mutate any variables not explicitly passed to it.
We then call these functions:
year, month, days, principal, rate = get_inputs()
totalYears = get_time(year, month, days)
interest = simple_interest(principal, rate, totalYears)
print_outputs(totalYears, interest)
This produces exactly the same behaviour as before, but this approach makes very clear what variables are being passed into and out of various function calls, without creating any "globally" accessible variables whose names/meanings could become ambiguous. There are of course ways to define global variables in Python, but personally, I tend to run scared of doing that if at all avoidable.
The problem is that get_time() is not updating the value of your global totalYears since you're not returning it. And simple_interest() won't update interest for the same reason.
You can check this by printing totalYears inside simple_interest():
def simple_interest():
interest = round(principal * rate/100 * totalYears,2)
#This should return 0:
print(totalYears)
print("Total interest earned is $",interest)
One easy way is just returning totalYears and interest:
def get_time():
totalYears = round(year + (month * 31 + days)/365,1)
print("total time in years is",totalYears,"years")
return totalYears
def simple_interest():
interest = round(principal * rate/100 * totalYears,2)
print("Total interest earned is $",interest)
return interest
year = int(input("Enter years: "))
month = int(input("Enter months: "))
days = int(input("Enter days: "))
principal = float(input("Enter principal: "))
rate = float(input("Enter rate (in %): "))
totalYears = get_time()
interest = simple_interest()
I hope this helps :)

How to create a tipping function in python

trying to fix this code for tipping.
Let's add a tipping function. I've created the bare-bones of the function, which will take in the cost of the meal, and ask for a percentage to tip on the meal. You do the rest!
def tip(cost):
percentage = input("What percent would you like to tip? ")
tip = round(cost * percentage, 2)
print("The tip amount of", percentage, "% is ", tip)
return tip
the first part does not seem to work
after that, I run
cost, items = order(menu)
print("Your order is", items)
cost = round(cost + tax("vt", cost, tax_rate), 2)
cost = round(cost + tip(cost), 2)
print("Your total cost is", cost)
You have to convert the input to float in order to perform mathmatical operation . Otherwise it will multiply the string with number and return a repeated string.
def tip(cost):
percentage = float(input("What percent would you like to tip? "))
tip = round(cost * percentage, 2)
print("The tip amount of", percentage, "% is ", tip)
return tip

I wrote a simple atm machine program, but some inputs cause a 0.01 difference. What's wrong with the code? (Beginner) [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 2 years ago.
banknotes = [200,100,50,20,10,5,1,0.50,0.25,0.10,0.05,0.01]
amount = float(input("Enter an amount: "))
for i in range (0,len(banknotes)):
if banknotes[i] <= amount:
banknote = int(amount // banknotes[i])
amount = amount - banknote*(banknotes[i])
print(banknotes[i],"banknotes:",banknote)
For example when I input 86.74, program acts like its 86.73. But somehow when I input 386.74 or almost any other number, it works correctly. I really can't see where the problem is, and I tried online python compiler to see if my IDE is bugged, same thing happened.
As the comment points out, float comparisons aren't always accurate. if you were to use integers by multiplying by 100 (treat everything as cents and use integer math), this does not become a problem anymore:
banknotes = [20000,10000,5000,2000,1000,500,100,50,25,10,5,1]
# read a floating point into an int, could also just do int(float(input()) * 100)
def parse_input(input_str):
split = input_str.strip().split(".")
if len(split) == 2:
return int(split[0]) * 100 + int(split[1])
else:
return int(split[0]) * 100
amount = parse_input(input("Enter an amount: "))
for i in range (0,len(banknotes)):
if banknotes[i] <= amount:
banknote = int(amount // banknotes[i])
amount = amount - banknote*(banknotes[i])
print("% .2f" % (banknotes[i] / 100,),"banknotes:",banknote)

Subtract a tuple from an int

I keep getting a error that tuple cant be subtracted from a integer. I am trying to add all inputs to a list, then add all contents together and subtract it from the total monthly cash flow.
def budget_50_total():
list=[]
monthly = int(input("How much is your monthly cash flow "))
essential = budget_50(monthly)
print(essential)
# Do calculation for 50%
print("Please enter your essential expenses! ")
house = int(input("How much is your housing for month: "))
utilities = int(input("How much is your utilities this month 'gas, power, etc': "))
grocery = int(input("How much is your groceries for month "))
health = int(input("How much is your health insurance for the month "))
car = int(input("How much is your car payment"))
for i in range(1):
data = house, utilities,grocery,health,car
list.append(data)
print(list)
total = sum(list)
print(total)
total2 = essential - total
print(total2)
This line creates a tuple:
data = house, utilities,grocery,health,car
Then you add the tuple to the list in the next line. You won't be able to sum a list of tuple. You could however do
data = house, utilities,grocery,health,car
print(data)
total = sum(data)
However, your error "tuple cant be subtracted from a integer" is likely caused by your calculation for total2 as that is your only subtraction in the code shown. It's impossible to say what the issue is here without knowing what essential is.
You can use a for loop to add the sum of each tuple in list to the total:
total = 0
for x in list:
total += sum(x)

How can I add a 0. before an variable in python

Im making an python application to calculate percentages and I wanted to know how I can add an "0." in front of a variable to multiply it by the "percentOf" variable (would output the answer, but doesn't).
I've tried this:
import sys
percent = input("Enter percent:")
ofNumber = input("Enter number:")
percent2 = percent++0.
answer = percent2 * ofNumber
print(answer)
but it won't work :(
There are two changes needed to make this work.
Converting input() result to numbers:
input() retrieves input from the user as text (a "string"), not as a number. To use the inputs as numbers, you'll want to convert them into integers using the builtin conversion function int():
percent = int(input("Enter percent:"))
ofNumber = int(input("Enter number:"))
(In practice, you would also want to use try/catch to handle the case where the user typed something that wasn't a valid number, but we'll ignore that for now)
Converting a Percentage Into a Decimal:
This is the part you asked about. You can do this by dividing by 100, as stated in the comment above:
percent2 = percent / 100
Final Code:
With both of those changes:
percent = int(input("Enter percent:"))
ofNumber = int(input("Enter number:"))
percent2 = percent / 100
answer = percent2 * ofNumber
print(answer)
Sample output:
> Enter percent:20
> Enter number:100
> 20.0
I have found an alternative solotion!
It works by multiplying the percent by the percentOf and then dividing that by 100.
The code is this:
import sys
percent = input("Enter percent (%):")
ofNumber = input("Enter number:")
var1 = ofNumber * percent
answer = var1 / 100
print(answer)

Categories