Casting User-Provided Numbers to Integers and Floats in Python - python

I'm trying to create a change return program that takes in a cost of an item and the money given and returns the proper change in terms of notes, quarters, dimes, etc.
I'm fairly new to programming and I'm stuck on trying to split it up. I've looked on StackOverflow and found the method math.modf(x) to be relevant. However, I am having a hard time implementing it.
Can you please let me know why change and y is not defined?
Thanks
import math
def changereturn():
quarter = 0.25
dime = 0.1
nickel = 0.05
penny = 0.01
cost = float(raw_input('Please enter the cost of the item in USD: '))
money = float(raw_input('Please enter the amount of money given in USD: '))
change = money - cost
y = math.modf(change)
return change
return y

A function (def) can only return one time, but python allows you to return tuples for result.
This implementation may be what you need:
import math
def changereturn():
quarter = 0.25
dime = 0.1
nickel = 0.05
penny = 0.01
cost = float(input('Please enter the cost of the item in USD: '))
money = float(input('Please enter the amount of money given in USD: '))
change = money - cost
y = math.modf(change)
return change, y
print(changereturn())

First issue is you never run your changereturn() function. Second issue is the two return lines in the changereturn() function. The second function which sends the y will never be run. You can return (change, y) and run your program as:
change, y = changereturn()
print change
print y
You need to put this at the very bottom without indenting. Personally, I don't like returning multiple things from a function. Normally I'd suggest catching it as a tuple and then printing each portion. Your question feels a bit like an assignment for a Comp Sci first year student so I don't want to 1)solve it for you and 2) make it overly complex.

Related

How to use the user’s input in an equation in python

I'm new to comp sci and really need your help!
My assignment is to code for a dessert shop. We had to create two functions, one to get the cost of a cake and the other to get the order of the client and print out how much it will be. My function for the cake cost works perfectly on it’s own, however when I try to run my customer_order function I get an error message. The cake_cost function should return a float as stated in the assignment. This is the code:
def cake_cost(diameter, height): ###returns cost as a float rounded
x=0
for i in range(1, base_diameter + 1): ##error message highlights this line
x += get_pizza_area(i) #Total Area
x = x * height_per_level #Volume
return round(x * CAKE_COST_PER_CM_CUBED,2)#Price where CAKE_COST_PER_CM_CUBED is a global variable of 4.0
#for example, cake_cost(8, 1.0) would be 640.88
def customer_order(): ##ask for order and prints out cost
cake_or_cookie = str(input("Would you like the cake or the cookie? "))
x = str(input("What diameter? "))
base_diameter = float(x)
y = str(input("What height? "))
height = float(y)
s_ingredient = str(input("Do you want the secret ingredient? "))
if cake_or_cookie.lower() == 'cake':
if s_ingredient == "yes" or s_ingredient == "y":
return float(round(cake_cost(base_diameter, height) + SECRET_INGREDIENT, 2)) ##where SECRET_INGREDIENT is a global variable of 19.99
else:
return float(round(cake_cost(base_diameter, height), 2))
else:
print(“ew, get out of my store.”)
##for example customer_orders()
Would you like the cake or cookie? cake
What diameter? 2
What height? 1
Do you want the super secret ingredient? yes
The cost is $35.7
I get an error message saying that ‘float’ object cannot be interpreted as an integer. How do I solve this? How can I get the user input and plug that into the original function simply by calling my customer_order function? Is there any way? Thank you so much! :)
P.s so sorry if the indentations look a little weird..
Congrats on starting your compsci journey! Your code mostly works, I just had to make a few modifications for it to work fully.
The parameters you're passing into the cake_cost function aren't being used. Rename diameter to base_diameter in the function parameters. You'll also need to rename height to height_per_level in the same function.
get_pizza_area isn't a defined function, implement that. Or if you already have the code, it would be useful posting it so we can get some more context / help you out a little more.
The reason why your code is erroring out on line 3 is because the range function only takes in integers. You can round the input of base_diameter to an integer so that you can loop from 1 until base_diameter + 1. For example, if base_diameter is 4, you will loop through an array of [1,2,3,4]. You can read a bit more about the range function here.
I added in the global variables you had in your comments :D
In terms of code cleanliness, we could condense the following 4 lines:
x = str(input("What diameter? "))
base_diameter = int(x)
y = str(input("What height? "))
height = float(y)
The input() function takes in a string by default. There's no point casting a string to a string and then casting it to an integer or a float. Instead, you can do the following:
base_diameter = int(input("What diameter? "))
height = float(input("What height? "))
SECRET_INGREDIENT = 19.99
CAKE_COST_PER_CM_CUBED = 4.0
def cake_cost(base_diameter, height_per_level): ###returns cost as a float rounded
x=0
for i in range(1, base_diameter + 1):
x += get_pizza_area(i) #Total Area
x = x * height_per_level #Volume
return round(x * CAKE_COST_PER_CM_CUBED,2)#Price where CAKE_COST_PER_CM_CUBED is a global variable of 4.0
#for example, cake_cost(8, 1.0) would be 640.88
def get_pizza_area(i):
return i
def customer_order(): ##ask for order and prints out cost
cake_or_cookie = str(input("Would you like the cake or the cookie? "))
base_diameter = int(input("What diameter? "))
height = float(input("What height? "))
s_ingredient = str(input("Do you want the secret ingredient? "))
if cake_or_cookie.lower() == 'cake':
if s_ingredient == "yes" or s_ingredient == "y":
print(float(round(cake_cost(base_diameter, height) + SECRET_INGREDIENT, 2))) ##where SECRET_INGREDIENT is a global variable of 19.99
else:
print(float(round(cake_cost(base_diameter, height), 2)))
else:
print("ew, get out of my store.”")
customer_order()
If I run the code snippet, I get something like this
Would you like the cake or the cookie? cake
What diameter? 2
What height? 1
Do you want the secret ingredient? yes
31.99
Change the conflicting line to
for i in range(1, int(diameter + 1))
and don't forget to rename base_diameter diameter and height_per_level height.
The arguments to the range constructor must be integers.
Change the float function to an int function on base_diameter.
The input() function returns a string, so you don't need to wrap it inside the str() function.

Riemann sum python

I need to make a python function where i can find the surface with the riemann sum. This is what i have , and with the feedback of my teacher i am very close to it, but it does not work as properly as i want. the teacher said also something about try-catch what means that i need to make an extra code to control the answer (if im not wrong) To find the surface the uppper and the lower limits are asked and how many rectangles you want under the line like in the program.
(edit) I have made a new program , could you guys check if this is correct.
import math
def f(x): return math.sqrt(x) #Function in the left!
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
n = int(input("How many division intervals do you want?:"))
dx = (b-a)/n;
xi = 0;
sum = 0;
for i in range(n):
xi = xi+dx;
sum = sum + f(xi)
print("The surface under the line is ", (sum*dx))
#einde programma!
import math
def f(x):
return math.sqrt(x) #Function in the left!
def positiveinput(message):
while True:
try:
c = int(input(message))
if c <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?: ")
b = positiveinput("What is the upperlimit?: ")
c = positiveinput("How many division intervals do you want?: ")
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
c = int(input("How many division intervals do you want?:"))
dx = float((b-a)/c)
xi = a
Sum = dx
for i in range(0,c):
xi = a - dx
Sum = Sum + f(xi)
print("The surface under the line is ", (sum*dx))
There are a few issues with the code above:
1) Most importantly, You don't actually calculate the correct answer because you are assuming that the lower limit is equal to 0. Instead of writing xi=0 you should be writing xi=a!!! (Note that this will use the far end of each rectangle to calculate the height - if you want to use the lower end, and don't want to change any other code you will need to write xi = a - dx so you start on a. (Having said that, I wouldn't do it this way, but this is how to fix this without changing anything else).
2) Validation errors: There are a few things you should check:
That the values of a, b are valid numbers (note they shouldn't really have to be integers, just numbers). You can use float() to convert something to a number, just as you would use int() to convert to an integer.
that n is an integer and is not equal to 0, as that will raise an error, when you try and divide by n,
that n is not negative, as this will result in you getting the wrong value (with the code as it is).
Having said that, I would not write the code as it is. Using a for-loop and then incrementing your value is not a very pythonic thing to do. You might be interested to learn you can actually specify a lower bound and an upper bound using the range function. Experiment with:
for i in range(3,11,0.5):
print(i)
See what happens. I'm not going to give you a full solution, as this is a homework assignment, and it will benefit you most to work it out yourself, but hopefully this points you these things will point you in the right direction.
As #Sadap said, you can try something like this:
def positiveinput(message):
while True:
try:
n = int(input(message))
if n <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?:")
b = positiveinput("What is the upperlimit?:")
n = positiveinput("How many division intervals do you want?:")
Having this code as a guide, you can complete the list of errors verification that #tim-mccurrach have written in an answer to this post. Also you can check out this link where they make the Riemann Sum in a different way. For documentation about try-catch you can enter this link.

How can I improve formatting of floats output from my tax calculator?

I didn't have any problems writing this much, but the output numbers are a little wonky. Sometimes I'll get something like 83.78812, for example, and I'd rather round it up to 83.79.
Here's the code itself:
#This is a simple tax calculator based on Missouri's tax rate.
while True:
tax = 0.076
cost = float(raw_input("How much does the item cost? $"))
taxAmount = tax * cost
final = taxAmount + cost
if cost > 0:
print "Taxes are $" + str(taxAmount) + "."
print "The total cost is $" + str(final) + "."
else:
print 'Not a valid number. Please try again.'
I've seen people mention that I should be using ints instead of floats, but my tax-rate is over three characters past the decimal. Furthermore, typing in a string results in an error that crashes the program, but I'd rather it simply give an error message and loop back to the beginning. I don't know how to fix either of these things.
"typing in a string results in an error that crashes the program, but I'd rather it simply give an error message and loop back to the beginning."
To do this, you can use a while loop with try & catch That will keep on prompting for the item cost until it gets appropriate value
Use round() method to round up your value. It takes two parameters, first one is the value and second one is the position where to round up.
Format your result with python string formatting using the placeholder %.2f (2 digits after decimal point)
tax = 0.076
cost = 0
parsed = False
while not parsed:
try:
cost = float(raw_input("How much does the item cost? $"))
parsed = True
except ValueError:
print 'Invalid value!'
taxAmount = tax * cost
final = taxAmount + cost
if cost > 0:
print "Taxes are $%.2f." % round(taxAmount, 2)
print "The total cost is $%.2f." % round(final, 2)
else:
print 'Not a valid number. Please try again.'
You should use round:
round(final,2)

How to call nested functions?

Pointers on how to fix my code? This code asks for user input on the number of tickets sold, and returns the income generated using functions
I am not sure about what how to call each function
secA = 20
secB = 15
secC = 10
def main():
print("The income generated from all sections is: ", total)
def getTickets(A,B,C):
sectionA = int(input("Please enter the number of tickets sold in section A: ")
sectionB = int(input("Please enter the number of tickets sold in section B: ")
sectionC = int(input("Please enter the number of tickets sold in section C: ")
def ticketsValid():
while sectionA > 300:
print("ERROR: Section A has a limit of 300 seats")
while sectionB > 500:
print("ERROR: Section B has a limit of 500 seats")
while sectionC > 200:
print("ERROR: Section C has a limit of 200 seats")
def calcIncome():
total = secA * sectionA + secB * sectionB + secC * sectionC
print("The income generated is $", format(total, '.2f'))
main()
To answer your first question: to call all of the functions you need to put the names of your functions into the main() function. But, you had several other errors so I have decided to walk you through the program, step-by-step.
First, we set the prices:
secA = 20
secB = 15
secC = 10
Here is the first function, getTickets()
def getTickets():
global A
A = int(input("Please enter the number of tickets sold in section A: "))
global B
B =int(input("Please enter the number of tickets sold in section B: "))
global C
C =int(input("Please enter the number of tickets sold in section C: "))
Notice the word global before I use the variable. This tells the computer that this variable can be used everywhere. Next, notice the double parentheses - since both int() and input() are functions, so we need to show that by doing that.
I fixed your code for the ticketsValid() function. Usually, it isn't a good idea to nest functions, so this is at the same indentation level as the above code.
def ticketsValid(A,B,C):
while A > 300 or A < 0:
print("ERROR: Section A has a limit of 300 seats\n")
A = int(input("Please enter the number of tickets sold in section A: "))
while B > 500 or B < 0:
print("ERROR: Section B has a limit of 500 seats")
B =int(input("Please enter the number of tickets sold in section B: "))
while C > 200 or C < 0:
print("ERROR: Section C has a limit of 200 seats")
C =int(input("Please enter the number of tickets sold in section C: "))
This gets the variables from above, and checks to see if they are valid. Notice that I added a check for negative numbers - you can't sell negative tickets.
Then we come to calcIncome(A,B,C):
def calcIncome(A, B, C):
total = A * secA + B * secB + C * secC
print ("The income generated is $%d" % (total))
First, we multiply the sections by the set prices to calculate the total. Then, we print it.
Lastly, we need to call the functions. I used your idea for a main() function, which uses the other functions. It looks like this.
def main():
getTickets()
ticketsValid(A,B,C)
calcIncome(A, B, C)
It simply calls the other functions, in the correct order, when run.
Lastly, we call the main() function by typing:
main()
I hope that this answered your question. If not, feel free to comment. If so, please check the green check mark next to my answer.
If you only want to know how to use a nested function:
def f():
def g(): #this defines a function but does not call it
print "run g"
g() # this calls g.
Typically, nested functions should not be available outside its parent function. Since the point of using a nested function is that the function only helps its parent function to do things. If you want it outside, consider define it as a new function.
In your case, you need to consider how to break up your code into parts.
If I were you, I would use getTickets() to get tickets.
The ticketsValid is fine, though I would let it return a boolean.
calcIncome would return the total income.
So the general design is like:
def main():
(A, B, C) = getTickets()
if(ticketsValid(A, B, C)):
income = calcIncome(A, B, C)
print("The income generated from all sections is: ", income)
def getTickets():......
def ticketsValid(A, B, C):......
def calcIncome(A, B, C):......
I think this would be a better design.

Python for loop with adding to an equation?

I need some help in this program. I need help figuring out how to make it calculate interest for a period over ten years (including the first one). This is as far as i have gotten on my own. I would greatly appreciate some insight to this problem.
Thanks.
*The "print() is just for spacing so that the program looks cleaner.
p= int(input(" Intial Amount? "))
print()
r= float(input(" Rate? (Decimal) "))
print()
n= int(input(" Number Of Times Compunded? (Yearly) "))
print()
t= float(input(" Number Of Years? "))
A= p*(1+r/n)**(n*t)
print()
print( " Interest At Final Year","$",format(A, ',.2f'))
print()
for i in range (10):
print(format(i+1, '3')," Year","Interest","$",format(A,',.2f'))
In the body of your loop, you are not updating the values of any of the variables. You need to update A at every iteration or store the intermediate results in some other variable. As an example, see the following:
def compound_interest(r, n, initial):
current_value = initial
for i in range(n):
current_value *= (1 + r)
print(current_value)
I use the current_value variable to save the intermediate results of the loop. If I had simply done initial * (1 + r) at every iteration then the value of initial would never change; the result of the calculation must be saved if you want to keep using it.
At the very end of the program it will count 1-10 but it will have the same amount as the first calculation.
Yes, that's because the only thing that happens in that loop is the print call. You're just calculating A all at once, before you get into the loop, and then using the same A over and over again.
I need help making it add the new values to add up while the "n" and the "p" are changing.
Well, you aren't changing n or p, and I don't think you need to. But you do need to change something. If you want to print a different value of A each time through the loop, you have to recalculate next year's A based on the previous year's A, or whatever else goes into determining the right value.
For example:
for year in range (10):
jan1balance = p
for period in range(n):
p = p * (1 + r)
print(format(year+1, '3')," Year","Interest","$",format(p - jan1balance,',.2f'))
Or:
for year in range (10):
yearlyinterest = 0
for period in range(n):
periodinterest = p * r
yearlyinterest += periodinterest
p += periodinterest
print(format(year+1, '3')," Year","Interest","$",format(yearlyinterest,',.2f'))

Categories