Skip to main content
 首页 » 编程设计

Python float 及正确使用

2024年11月01日10kuangbin

我正在为我的类(class)输入一个程序,这个问题的措辞很奇怪,但是我已经输入了我的代码来解决这个问题,我是否正确地将数字声明为 float ? 简单的问题,但我对其他做事方式持开放态度。

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 

请您参考如下方法:

你的花车没问题。

你需要使用 raw_input 来获取字符串。

input("Enter a number") 等同于 eval(raw_input("Enter a number"))。目前,代码尝试将输入作为代码进行评估(作为 Python 表达式运行)。

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 

其他评论:

  1. 对于顶部的多行横幅,将字符串声明为多行字符串并打印它。
  2. 检查以确保范围对输入有意义(验证)。当然,如果这是一个类,你可能还没有达到这一点(Seen if/else?)
  3. 明确你的常量,使它们 float ,以确保它不会默认为整数除法

稍微清理一下表格:

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