How to use the user’s input in an equation in python - 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.

Related

How can I add a menu at the start of a code to choose which part of code the use wants to use in Python?

I have 2 codes. I want to put both of them together into one code where I can then choose which code I want to use. For example, when you run the code: "Press 1 if you wish to find the volume that the bore will produce, press 2 if you wish to find the volume by giving length and radius: " Something like that.
import math
pi = math.pi
a = float(input("What is the minimum volume that is required? (cubic meters): "))
b = float(input("How long do you need the tunnel to be? (metres): "))
r2 = a/(pi)/b
r = math.sqrt(r2)
rrounded = (round(r*4)/(4))
if rrounded < r:
new_radius = (rrounded+0.25)
print("Bore radius size required: " + str(new_radius))
else:
new_radius=rrounded
print(str(new_radius))
total_volume = ((pi)*(new_radius**2)*(b))
total_volume1 = str(round(total_volume, 2))
print("Exact volume produced (with bore-size above and the tunnel length specified): " +
(str(total_volume1)))
import math
pi = math.pi
h = float(input('How long does the tunnel need to be?(meters) '))
r = float(input('What is the radius of the tunnel? '))
volume = pi*r**2*h
volume_ = str(round(volume, 2))
print(volume_)
I apologise for my terrible attempts at trying to make indents, I still haven't quite figured out how to ask questions on here properly. As I said before, I want to use a code that gives the user the option to choose what they want to do when the code runs. Thanks!
Define the functions you want in the menu and do something like this
def menu():
print('The options are bellow:\n\
1. ..\n\
2. ..\n\n')
menu = input('Choose the option:\n')
if menu == '1':
return function1()
if menu == '2':
return function2()
else:
print('error')
return menu()

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)

Casting User-Provided Numbers to Integers and Floats in 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.

Regarding passing variables to an argument

I am working in python 2.7.8.
I'm currently learning about parameters and methods. What I'm trying to accomplish is have a user enter two different variables then pass them to an argument within different methods, sum() and difference().
My following code is something like this:
def computeSum(x, t):
x = int(raw_input('Please enter an integer: '))
t = int(raw_input('Please enter a second integer: '))
x+t
return Sum
def computeDif(y, j):
y = int(raw_input('Please enter an integer: '))
j = int(raw_input('Please enter a second integer: '))
y+j
return Dif
def main():
raw_input('Would you like to find the sum of two numbers or the difference of two numbers?: ')
answer = 'sum'
while True:
computeSum()
else:
computeDif()
For some reason my compiler (pyScriptor) isn't running and I cannot see any output nor error messages, its just blank. Can anyone possibly help me with any syntax/logic errors?
There are a few problems with your code
Your indentation is way off
computeSum and computeDif expect the two numbers as parameters, but then also ask for them from the terminal
You return the variables Sum and Dif, but never assign values to them
You call either computeSum or computeDif, but never do anything with the returned value
You never call main. Do you know that you don't need a main function? You can just put the code in line after the function definitions
This is probably a little closer to what you had in mind
def computeSum(x, t):
return x + t
def computeDif(y, j):
return y - j
def main():
while True:
answer = raw_input('Would you like to find the "sum" of two numbers or the "dif"ference of two numbers? ')
a = int(raw_input('Please enter an integer: '))
b = int(raw_input('Please enter a second integer: '))
if answer == 'sum':
print(computeSum(a, b))
elif answer == 'dif':
print(computeDif(a, b))
else:
print('Please enter "sum" or "dif"')
main()
The problem is that you don't need a main() function. Just put the code, unindented, by itself, and it will run when you run the program.

Python try except problems

So im having a little trouble with a project im working on. I'm not an expert with Python nor am I an idiot when it comes to coding. This problem may have a very simple answer but I cant seem to get it right. My entire code asks a user to answer questions using a random choice from a list.
import turtle
import random
turtle.speed("fastest")
pi = 3
minNumber = 5
maxNumber = 10
score = 0
listNmbers = []
a = [1,3,5,7,9]
red = random.random()
green = random.random()
blue = random.random()
num1 = random.choice(a)
def drawSquare():
for i in range(4):
turtle.begin_fill()
turtle.pendown()
turtle.forward(50)
turtle.left(90)
turtle.end_fill()
turtle.right(360/userAnswer)
turtle.penup()
turtle.setpos(-700,-200)
turtle.fillcolor("green")
print("Welcome! What is your name??")
name = str(input())
print("Hello", name,"you need to calculate the circumference of a circle when given a diameter. To calculate the circumference, use the equasion; Pi x Diameter (Pi = 3")
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
def getNumbers(numbers):
try:
badInput = False
while not (badInput):
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
numbers = int(num)
badInput = (numbers >= 4) or (numbers >= maxNumber)
if badInput == False:
print ("Please input an integer between 5 and 10 please")
badInput = False
except:
print("Please input an integer between 5 and 10")
numbers= 0;
numbers = getNumbers(numbers)
numbers= 0;
numbers = getNumbers(numbers)
for i in range(int(num)):
red = random.random()
green = random.random()
blue = random.random()
num1 = random.choice(a)
turtle.color(red,green,blue)
correct = num1 * 3
print("What is the cirumference of the circle if", num1,"is the diameter and Pi is 3?")
userAnswer = int(input())
if userAnswer == correct:
print("That's Correct! Well Done")
score = score + 1
for k in range(correct):
turtle.color(red,green,blue)
drawSquare()
turtle.penup()
turtle.forward(150)
else:
print("sorry thats is incorrect")
in this bit of code, it asks the user how many questions they want to ask (as an integer). My code works well when a number within the parameters are given, but as soon as a number such as 19 is given, it continues when it should not. Also if a string is given, it works well and asks again for an integer, but if an integer is given after being asked, it crashes. The error read:
for i in range(int(num)):`ValueError: invalid literal for int() with base 10: 'test'`
All help would appreciated so much. thank you all
And you're hidding too much code within a generic try..except (try to Ctrl+C while input is required... nope!). I would write that function in that way:
def getNumbers():
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
try:
number = int(num)
except:
print("Not a number!")
return getNumbers()
goodInput = minNumber < number < maxNumber
if not goodInput:
print ("Please input an integer between 5 and 10 please")
return getNumbers()
else:
return number
number = getNumbers()
getNumbers() doesn't return any value. Thus, it implicitly returns None, which you assign to numbers, here:
numbers = getNumbers(numbers)
Make sure that wherever you exit the getNumbers() function, you return numbers (probably at the end:
def getNumbers(numbers):
....
return numbers
EDIT: #see xbello answer to have a working answer. My "poisoned" code isn't working as expected ;)
First of all I must say that your code isn't really nice to read... But here are some fixes that should do the trick
maxNumber = 10
print("Hello", name,"you need to calculate the circumference of a circle when given a diameter. To calculate the circumference, use the equasion; Pi x Diameter (Pi = 3")
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
def getNumbers(numbers):
try:
goodInput = False
while not (goodInput):
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
numbers = int(num)
# Here was a bad condition having a look at your comments
goodInput = (numbers > 4) and (numbers <= maxNumber)
if goodInput == False:
print ("Please input an integer between 5 and 10 please")
# goodInput is already False, no need to set it again
# Here is the missing return
return numbers
except:
print("Please input an integer between 5 and 10")
numbers= 0;
numbers = getNumbers(numbers)
numbers= 0;
numbers = getNumbers(numbers)
for i in range(numbers):
#Do stuff
You can see that I added a return value to your function (that returned None by default) and that I take this return value to push it into "numbers" afterwards. That "numbers" value can then be pushed into a range() function to make a nice for loop.

Categories