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)
Related
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.
how_many_number = int(input("How many number do you want to print? "))
for take_number in how_many_number:
take_number = int(input("Enter number: "))
sum = 0
sum = sum + take_number
print(sum)
Here you go. To take user input we can use a for loop and for each iteration we can add it to our sum using += operator. You can read through the following code to understand it well enough.
number_of_inputs = int(input("How many number to sum: ")
sum = 0 # Initialize the sum variable
for x in range(number_of_inputs): # Repeat the number of inputs times
sum += int(input("Enter Value: ")) # Take a input and add it to the sum
print("Sum is", sum) # print out the sum after completing
You can also compress it into a List Comprehension, like this...
how_many_number = int(input("How many number do you want to print? "))
print(sum([int(input("Enter number: ")) for i in range(how_many_number)]))
i would use the following, note: error handle is not yet incorporated.
num_list = []
### create a function that adds all the numbers entered by a user
### and returns the total sum, max 3 numbers
### return functions returns the entered variables
def add_nums():
while len(num_list) < 3:
user_num = int(input('please enter a number to add:'))
num_list.append(user_num)
print('You have entered the following numbers: ',num_list)
total_num_sum = 0
for x in num_list:
total_num_sum += x
print('total sum of numbers = ',total_num_sum)
add_nums()
Also, please follow the StackOverFlow post guidelines; have your post title as a problem question, it has to be interesting for other devs, and add more emphasis on why you want to add numbers entered by user vs running calc on a existing or new data-frame, need more meat.
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
How to manage that placeholder will start counting from 1. For example, if the input is 3, how can I display "enter the number 1", "enter the number 2" and "enter the number3"
numbers = int(input("how many numbers do you want? "))
for i in range(numbers):
x = int(input("enter the number " + "%d" % ()))
For this simple case, forego the placeholder and just append the string
numbers = int(input("how many numbers do you want? "))
for i in range(numbers):
x = int(input("enter the number " + str(i+1)))
Otherwise, you can look at using f-strings
I'm not old enough to comment, so have to put this as an answer..
As per your code, you will be ended with 'x' having only the last number, to avoid this, you can probably define x as a list and keep appending to it so that you also capture the previous entries.
numbers = int(input("how many numbers do you want? "))
x = []
for i in range(numbers):
x.append(int(input("enter the number " + str(i+1))))
Not entirely sure why this is something you would like but if you need more help, just ask!
numbers = int(input("how many numbers do you want? "))
for i in range(1, numbers+1):
cur = input(f"enter the number {i}: ")
x = int(cur)
# Do something with x?
I recommend using fstrings as below:
numbers = int(input("how many numbers do you want? "))
for i in range(numbers):
x = int(input(f"enter the number {i+1}"))
(you should use i+1 if you want to start from 1)
I have this code for a program that should manipulate certain inputs the user enters.
I'm not sure how to only get x number of ouputs (x is specified by the user at the start of the program).
numOfFloats = int(input("Enter the number of floating point inputs: "))
numOfInts = int(input("Enter the number of integer inputs: "))
numOfStrings = int(input("Enter the number of string inputs: "))
for num in range(numOfStrings,0,-1):
print()
ffloats = float(input("Enter a real number: "))
iints = int(input("Enter an integer: "))
string = input("Enter a string: ")
print()
print("float: ", ffloats**(1/10))
print("int: ", iints**10)
print("string: ", (string + string))
I get all three requests each time, even though I have specified in the beginning that I only want 1 float, 2 ints, and 3 strings. I get asked for 3 floats, 3 ints, and 3 strings. I do realize what my code does, but I'm not sure how to get it to where I want it. I have a feeling something is wrong in the for loop conditions.
Any help is appreciated!
ffloats = []
for num in range(numOfFloats):
ffloats.append(float(input("\nEnter a real number: "))
iints = []
for num in range(numOfFloats):
iints.append(int(input("\nEnter an integer: "))
sstrings = []
for num in range(numOfFloats):
sstrings.append(input("\nEnter a real number: ")
print("Floats:", [f**(1/10) for f in ffloats])
print("Ints:", [i**10 for i in iints])
print("Strings:", [s + s for s in sstrings])
If you want them in order, then you'll have to:
for v in range(max([numOfFloats, numOfInts, numOfStrings])):
if v < numOfFloats:
ffloats.append(float(input("\nEnter a real number: "))
if v < numOfInts:
iints.append(int(input("\nEnter an integer: "))
if v < numOfStrings:
sstrings.append(input("\nEnter a string: ")
The program did exactly what you told it to do: given the number of strings -- 3 -- get that many int-float-string sets. You never used the other two quantities to control their loops. You need three separate loops; here's the one for strings, with all the int and float stuff removed.
numOfStrings = int(input("Enter the number of string inputs: "))
for num in range(numOfStrings,0,-1):
print()
string = input("Enter a string: ")
print()
print("string: ", (string + string))
Now just do likewise for ints and floats, and I think you'll have what you want.
Yes, you can do it in one loop, but it's inelegant. You have to find the max of all three numbers and use that as the loop's upper limit. Within the loop, check "num" against the int, float, and string limits, each in turn.
This code would be less readable, harder to maintain, and slower. Do you have some personal vendetta against loops? :-)
If your really want just a single loop, then I would suggest you use a while loop rather than a for loop, as you need to keep looping until all values have been entered.
numOfFloats = int(input("Enter the number of floating point inputs: "))
numOfInts = int(input("Enter the number of integer inputs: "))
numOfStrings = int(input("Enter the number of string inputs: "))
while numOfFloats + numOfInts + numOfStrings:
print()
if numOfFloats:
ffloats = float(input("Enter a real number: "))
if numOfInts:
iints = int(input("Enter an integer: "))
if numOfStrings:
string = input("Enter a string: ")
print()
if numOfFloats:
print("float: ", ffloats**(1/10))
numOfFloats -= 1
if numOfInts:
print("int: ", iints**10)
numOfInts -= 1
if numOfStrings:
print("string: ", (string + string))
numOfStrings -= 1
So for example:
Enter the number of floating point inputs: 1
Enter the number of integer inputs: 2
Enter the number of string inputs: 3
Enter a real number: 1.5
Enter an integer: 2
Enter a string: three
float: 1.0413797439924106
int: 1024
string: threethree
Enter an integer: 2
Enter a string: hello
int: 1024
string: hellohello
Enter a string: world
string: worldworld