I am typing a program for my class, the problem is worded very odd, but I have put in my code for the problem, am I declaring the numbers as float correctly?
Simple question but I'm keeping my mind open to other ways of doing things.
print " This program will calculate the unit price (price per oz) of store items,"
print " you will input the weight in lbs and oz, the name and cost."
item_name = (input("Please enter the name of the item. "))
item_lb_price = float(input("Please enter the price per pound of your item "))
item_lbs = float(input("please enter the pounds of your item. "))
item_oz = float(input("plese enter the ounces of your item. "))
unit_price = item_lb_price / 16
total_price = item_lb_price * (item_lbs + item_oz / 16)
print "the total price per oz is", unit_price
print "the total price for", item_name, "is a total of", total_price
Your floats are fine.
You need to use raw_input though to get a string back.
input("Enter a number") is equivalent to eval(raw_input("Enter a number")). Currently the code tries to evaluate the input as code (run as a python expression).
15:10:21 ~$ python so18967752.py
This program will calculate the unit price (price per oz) of store items,
you will input the weight in lbs and oz, the name and cost.
Please enter the name of the item. Apple
Traceback (most recent call last):
File "so18967752.py", line 6, in <module>
item_name = (input("Please enter the name of the item. "))
File "<string>", line 1, in <module>
NameError: name 'Apple' is not defined
Other comments:
For your multiline banner at the top, declare the string as a multiline string and print that.
Check to make sure the ranges make sense for the inputs (validate). Of course, if this is for a class you may not have reached this point (Seen if/else?)
Be explicit with your constants to make them floats to make sure it doesn't default to integer division
Slightly cleaned up form:
banner = '''
This program will calculate the unit price (price per oz) of store items.
You will input the weight in lbs and oz, the name and cost.
'''
print banner
item_name = raw_input("Please enter the name of the item. ")
item_lb_price = float(raw_input("Please enter the price per pound of your item."))
item_lbs = float(raw_input("Please enter the pounds of your item."))
item_oz = float(raw_input("plese enter the ounces of your item."))
unit_price = item_lb_price / 16.0
total_price = item_lb_price * (item_lbs + (item_oz / 16.0))
print "The total price per oz is", unit_price
print "The total price for", item_name, "is a total of", total_price
if it is python 2 you should be using raw_input instead of input.
if it is python 3 you should be enclosing the values you want to print in parentheses.
yes you are using the float function correctly but are not verifying that the input is correct. it is liable and even likely to throw errors.
besides the program is not correct for python 2 because of the input() and not correct for python 3 because of the use of the print statement.
And you should devide by a float: 16.0 instead 16.
Division in python is per default using integers, so if you want a floating point result you should divide by 16.0
unit_price = item_lb_price / 16.0
Related
I am trying to get a clean percentage from this line of code. For example, 50.00% or 61.37%. From this line, I am getting 5000.00% and so on. I have an idea that it has to do with how I am using format, but I'm not sure how it is doing this. I tried using int and got the desired number, just without the .00 and the % sign.
class_males = float(input('Please enter the number of male students registered:')) #Asks for user input of males
class_females = float(input('Please enter the number of female students registered:'))#Asks for user input of females
class_total = int(class_males) + int(class_females) #class total by combining user inputs
m_perc = int(class_males)/int(class_total)* 100 #divide user input of males by class total then multiply by 100 for %
f_perc = int(class_females)/int(class_total)* 100 #divide user input of females by class total then multiply by 100 for %
male_perc = "{:.2%}".format(m_perc) #adds "%" sign after number total
female_perc = "{:.2%}".format(f_perc) #adds "%" sign after number total
print('Percentage of males registered:', (male_perc)) #display percent of males
print('Percentage of females registered:',(female_perc)) #display percent of females
If it isn't already clear, I am a beginner. Thank you for any help provided.
You are multiplying by 100 twice because the % format specifier already does that for you, but you also do it yourself, resulting in a multiplication by 10,000 at the end.
See docs:
Type
Meaning
'%'
Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.
(Emphasis mine.)
The solution resulting in the leanest code is therefore to remove your own multiplication by 100 and just pass the ratio value directly:
m_ratio = int(class_males) / int(class_total) # divide user input of males by class total
f_ratio = int(class_females) / int(class_total) # divide user input of females by class total
male_perc = "{:.2%}".format(m_ratio) # multiplies by 100 and adds "%" sign after number total
female_perc = "{:.2%}".format(f_ratio) # multiplies by 100 and adds "%" sign after number total
Alternatively, you could switch to formatting as float using f as explained in Claudio's answer.
Small typo: you have placed the % character in the wrong place in the format specification. Put it as follows:
"{:6.2f}%" ( instead of "{:.2%}" )
You are getting the wrong result because the '%' sign used as format directive within {} formats a number to %-value by multiplication with 100, adding the % sign at its end.
Alternatively, you could switch to changing your m_perc,f_perc values to m_ratio and f_ratio as explained in CherryDTs answer.
The problem is not with how you are using format (from my testing, although I am also fairly new), but if you stop multiplying by 100 after, it should give proper results.
class_males = float(input('Please enter the number of male students registered:')) #Asks for user input of males
class_females = float(input('Please enter the number of female students registered:'))#Asks for user input of females
class_total = int(class_males) + int(class_females) #class total by combining user inputs
m_perc = int(class_males)/int(class_total) #divide user input of males by class total for %
f_perc = int(class_females)/int(class_total)#divide user input of females by class total for %
male_perc = "{:.2%}".format(m_perc) #adds "%" sign after number total
female_perc = "{:.2%}".format(f_perc) #adds "%" sign after number total
print('Percentage of males registered:', (male_perc)) #display percent of males
print('Percentage of females registered:',(female_perc)) #display percent of females
## Better to replace your code to this.
male_perc = "{:.2f}%".format(m_perc)
female_perc = "{:.2f}%".format(f_perc)
I'm practicing on my format statements, but i'm not quite understanding how it works. I am specifically trying to understand the format command using the ".2f" command this is the code i currently have, the second line runs before it returns and error:
salesTax = 0.08
salesAmount = str(input('Enter the sales amount: '))
print ('The sales amount is', format('$'+salesAmount,
'.2f'))
print ('The sales tax is', format("$"+'.2f'))
print('The total sale is', format("$"+totalSales*salesTax,
'.2f'))
input("\nRun complete. Press the Enter key to exit.")
I am trying to make a script, that displays the output of the following sample run:
//Sample run:
Enter the sales amount: 1234
The sales amount is $ 1,234.00
The sales tax is $ 98.72
The total sale is $ 1,332.72
Run complete. Press the Enter key to exit
TL;DR
print('The sales amount is $', format(salesAmount, '.2f'))
Breaking it down:
Convert the number to string formatted as 2 decimal places (.2 portion) with floating point representation (f portion).
format(salesAmount, '.2f')
Now that you have a string, you join it with either pass to print or you could join to previous code with + or whatever.
'The sales amount is $' + the_formatted_number
.2f should be outside of the format method.
eg try print("{:.2f}".format(12.345678))
format is a built-in function that takes two arguments: value and format_spec.
format('$' + salesAmount, '.2f')
Will give you an error because it is expecting a number or a string representation of a number as value to apply the format you have provided. You will get an error:
ValueError: Unknown format code 'f' for object of type 'str'
format(salesAmount, '.2f')
This will work properly.
Note: If you are using Python 3.6+ you can also use an f-string:
f"{12.345678:.2f}"
The syntax is
format(value, format_spec)
When you use a .2f format, the value should be a float, not a string, so you need to convert the input to float (input() returns a string, there's no need to use str() on the result. And you can't concatenate $ to the value before formatting it, you need to concatenate that to the result.
You also used a nonexistent variable totalSales in your print() calls, it should be salesAmount.
salesTax = 0.08
salesAmount = float(input('Enter the sales amount: '))
print ('The sales amount is', '$' + format(salesAmount, '.2f'))
print ('The sales tax is', '$' + format(salesTax*salesAmount, '.2f'))
print('The total sale is', '$' + format(salesAmount + salesAmount*salesTax, '.2f'))
input("\nRun complete. Press the Enter key to exit.")
That said, this use of the format() function is not common these days. It's easier to use an f-string or str.format(), which allows you to embed the format spec in a string with the plain text, and format multiple values together, e.g.
print("The sales amount is ${.2f}".format(salesAmount))
The following is what the output should look like:
Enter price 1: 10.0
Enter price 2: 20.0
The 'two-for' price is $24.0
The code I entered is:
price_one = float(input('Enter price 1: '))
print(price_one)
price_two = float(input('Enter price 2: '))
print(price_two)
two_for_price = (price_one + price_two)-((price_one + price_two)*(20/100))
print("The 'two-for' price is $",two_for_price)
(The inputs are 10.0 and 20.0 respectively.)
But the output I am getting is:
Enter price 1: 10.0
Enter price 2: 20.0
The 'two-for' price is $ 24.0
In the last line I need:
The 'two-for' price is $24.0
Please help me out!!
If i'm reading this correctly you just need to remove a space from your output.
Change your last line to this:
print("The 'two-for' price is ${0}".format(two_for_price))
Your underlying problem is that the print function behavior, given a list of items, is to print each item, separated by a space. This is often convenient for quick-and-dirty print-outs, but you want something more refined.
What you need to do is create a string with the proper spacing and then print that string out.
So you could do this:
print("The 'two-for' price is $" + str(two_for_price) + ".")
The problems are (a) that's kind of clumsy and unreadable and (b) it does not format properly, it's "$2.6" instead of "$2.60".
You can use either of two formatting mechanisms offered by Python, either explicit, like this:
print("The 'two-for' price is ${0}".format(two_for_price))
or implicit, like this
print("The 'two-for' price is $%f" % two_for_price)
Both of them look a little better, but the formatting errors are the same and worse ("$2.600000"!) respectively. Fortunately, both offer nice customizable formatting:
print("The 'two-for' price is ${0:.2f}".format(two_for_price))
and
print("The 'two-for' price is $%0.2f" % two_for_price)
Both of which look reasonably clean and display perfectly.
So, I'm kind of new to programming and have been trying Python. I'm doing a really simple program that converts usd to euroes.
This is the text of the problem that I'm trying to solve
You are going to travel to France. You will need to convert dollars to euros (the
currency of the European Union). There are two currency exchange booths. Each has
a display that shows CR: their conversion rate as euros per dollar and their fee as a
percentage. The fee is taken before your money is converted. Which booth will give
you the most euros for your dollars, how many euros, and how much is the difference.
Example 1:
Dollars: 200
CR1: 0.78
Fee: 1 (amount 152.88 euros)
CR2: 0.80
Fee: 3 (amount 155.2 euros)
Answer: 2 is the best; difference is 2.32 euros; 155.2 euros
And here is my code
from __future__ import division
usd = int(input("How much in USD? "))
cr1 = int(input("What is the convertion rate of the first one? "))
fee1 = int(input("What is the fee of the first one? "))
cr2 = int(input("What is the convertion rate of the second one? "))
fee2 = int(input("What is the fee of the second one? "))
def convertion (usd, cr, fee):
usdwfee = usd - fee
convert = usdwfee * cr
return convert
first = convertion(usd, cr1, fee1)
second = convertion(usd, cr2, fee2)
fs = first - second
sf = second - first
def ifstatements (first,second,fs,sf):
if first < second:
print "1 is the best; difference is ",fs," euroes. 2 converts to ",first," euroes."
elif first > second:
print "2 is the best; difference is",sf," euroes. 2 converts to", second," euroes."
ifstatements(first, second, fs, sf)
The problem is that when I run the program it won't print out. It just takes my input and doesn't output anything.
Check your logic more.
cr1 = int(input("What is the convertion rate of the first one? "))
Your conversion rate is in int. As in Integer which means it can't have a floating point (a decimal "CR1: 0.78" from your example). Your cr1 will become 0 if you cast it into an int. Also change your dollar and fees to accept floats too since I'm assuming you want to deal with cents too
So change:
usd = float(input("How much in USD? "))
cr1 = float(input("What is the convertion rate of the first one? "))
fee1 = float(input("What is the fee of the first one? "))
cr2 = float(input("What is the convertion rate of the second one? "))
fee2 = float(input("What is the fee of the second one? "))
And it should work.
This question already has answers here:
Assigning variables from inputs in FOR loop in python
(2 answers)
Closed 9 years ago.
I'm doing a Python programming course and I've been trying to wrap my head around how I can make it happen. I've written some code and I'm trying to fix any errors that pop up but I'm getting confused and not solving anything which is why I turn to you guys. I would appreciate any ideas and suggestions that pop up when you see what I've managed to write so far. I'm especially having trouble figuring out how to do the last part where I have to get the value that is above or below $2.
I'm doing this exercise:
Create a change-counting game that gets the user to enter the number of coins necessary to make exactly two dollars. Implement a Python program that prompts the user to enter a number of 5c coins, 10c coins, 20c coins, 50c coins, $1 coins and $2 coins. If the total value of those coins entered is equal to two dollars, then the program should congratulate the user for winning the game. Otherwise the program should display a message advising that the total was NOT exactly two dollars, and showing how much the value was above or below two dollars.
Update: I made a few changes to the last function and it worked perfectly fine.
#Global Variables
v_five = float(0.05)
v_ten = float(0.10)
v_twenty = float(0.20)
v_fifty = float(0.50)
v_one_dollar = int(1)
v_two_dollar = int(2)
dollar = 0
def main():
"""The main function defines the variables that are needed by taking input
from the user. The main() function is calling all the other functions one
by one to execute their intended commands and give the results"""
intro() #Displays the rules of the game
#Takes input from the user. One input per denomination
five=float(input(" Enter number of FIVE CENT coins: "))
ten=float(input(" Enter number of TEN CENT coins: "))
twenty=float(input(" Enter number of TWNETY CENT coins: "))
fifty=float(input(" Enter the number of FIFTY CENT coins: "))
one_dollar=int(input(" Enter the number of ONE DOLLAR coins: "))
two_dollar=int(input(" Enter the number of TWO DOLLAR coins: "))
#Shows what the user entered
show_change(five,ten,twenty,fifty,one_dollar,two_dollar)
#Converts the value of the total into dollars and cents from
#what the user has entered
calculate_value(five,ten,twenty,fifty,one_dollar,two_dollar)
#Calculates and Prints the total along with what the final number
#was
#CalculateAndPrint(five,ten,twenty,fifty,one_dollar,two_dollar)
CalculateAndPrint(dollar)
def intro():
"""This function simply prints out the instructions for the user"""
print("")
print(" Welcome to the Coin Change game!")
print(" Enter a number for each denomination below")
print(" Your total should be $2 and no more.")
print(" Good Luck!\n")
def show_change(five,ten,twenty,fifty,one_dollar,two_dollar):
"""This function shows what the user has entered after taking input from
the user"""
print("")
print(" You entered: \n\n {} five cent(s) \n {} ten cent(s) \n {} twenty cent(s) \n {} fifty cent(s) \n {} one dollar \n {} two dollar coins".format(five,ten,twenty,fifty,one_dollar,two_dollar))
def calculate_value(five,ten,twenty,fifty,one_dollar,two_dollar):
"""This function will convert the entered values into cents so that they
can be calculated and checked if they exceed the $2 amount."""
fiveAmount = v_five * five
tenAmount = v_ten * ten
twentyAmount = v_twenty * twenty
fiftyAmount = v_fifty * fifty
oneAmount = v_one_dollar * one_dollar
twoAmount = v_two_dollar * two_dollar
global dollar
dollar = fiveAmount + tenAmount + twentyAmount + fiftyAmount + oneAmount + twoAmount
"""This function checks whether the total was over or under $2 and displays a
win or loose message for the user. Also shows the total that the user entered"""
def CalculateAndPrint(dollar):
if dollar == 2.00:#Checks if the dollar value being passed from the previous function
#is 2 or not
print(" \n Congratulations! You've hit a perfect 2!")
print("")
else:
if dollar < 2.00:
print(" \n Oops! You were a little under 2!")
print("")
print(" Your total was: ", dollar)
else:
if dollar > 2.00:
print(" \n Oh no! You went over 2!")
print("")
print(" Your total was: ",dollar)
main()
well, actually there're a couple of errors:
the function calculate_value does return a value but it's not assigned at all
return_dollar = calculate_value(five,ten,twenty,fifty,one_dollar,two_dollar)
and you have to pass that value to CalculateAndPrint.
CalculateAndPrint(return_dollar)
you have also to change the definition of CalculateAndPrint:
def CalculateAndPrint(dollar):
i don't have python 3.0 installed on this PC so i cannot test all your program, but those are two problem i can see right now.
Just as a matter of style, why don't you put all your coins in a list:
coin_list = [five, ten, twenty, fifty, one_dollar, two_dollar]
show_change(coin_list)
calculate_value(coin_list)
CalculateAndPrint(coin_list)
Note: you'll need to change the def's of the above functions.