4 回答
![?](http://img1.sycdn.imooc.com/5458464a00013eb602200220-100-100.jpg)
TA贡献2051条经验 获得超10个赞
我清理了输出并利用反馈使其工作得更好。现在,如果人们有关于简化代码的建议,那就太好了。我想确保我以 Python 的方式编写东西,并且从内存使用和代码空间的角度来看也是高效的。
感谢大家迄今为止提供的所有帮助!
# define variables
new = []
items = float()
subtotal = float()
tax = float()
final = float()
# welcome and set rules of entering numbers
print("Welcome! Sales tax is 7%. Enter your five items, one (1) at a time.")
# gathering input for items
for _ in range(5):
# define condition to continue gathering input
test = True
while test: # test1 will verify integer or float entered for item1
items = input("\nEnter the price of item without the $: ")
try:
val = float(items)
print("Input amount is :", "$"+"{0:.2f}".format(val))
test = False
except ValueError:
try:
val = float(items)
print("Input amount is :", "$"+"{0:.2f}".format(val))
test = False
except ValueError:
print("That is not a number")
# append items to the list defined as new
new.append(items)
# define calculations
subtotal += float(items)
tax = subtotal * .07
print("Cost Subtotal: ", "$" + "{0:.2f}".format(subtotal), " & Tax Subtotal: ", "$" + "{0:.2f}".format(tax))
_ += 1
# define calculations
final = subtotal + tax
# items tax & subtotal
print("\n Final list of item cost:")
new_list = [float(item) for item in new] # fixed this too
for i in new_list:
print("- $"+"{0:.2f}".format(i))
print("\n Final Pretax Total: ", "$"+"{0:.2f}".format(subtotal))
print(" Final Tax: ", "$"+"{0:.2f}".format(tax))
print("\n Tare: ", "$"+"{0:.2f}".format(final))
![?](http://img1.sycdn.imooc.com/54584cde0001d19202200220-100-100.jpg)
TA贡献1891条经验 获得超3个赞
所以问题出在你的while循环上。
在伪装中,您的while循环while True:永远保持这种状态,直到用户输入一些分支到 的文本或字符串except,但之后又会这样吗?我很确定它except会工作,因为你的代码正在执行except两次,即使它分支
try:
val = float(items)
print("Input amount is :", "$"+"{0:.2f}".format(val))
test1 = False
except ValueError:
try:
val = float(items)
print("Input amount is :", "$"+"{0:.2f}".format(val))
test = False
您可能不需要整个第二个 try 语句并将其替换为print("That is not a number")andtest = False
您控制 ( _) 没有在代码中的任何地方使用,所以我只需删除_ += 1
我的理解
现在我认为你想要做的是从用户那里获取 5 个项目,如果用户的输入不是正确的浮点数,它会再次询问,直到用户有 5 个输入正确为止。
您的for循环可以替换为:
首先确保您有一个计数器变量,例如vorc并将其分配给0。
我们希望从用户那里获得while计数器变量小于 5(范围为0,1,2,3,4(5 倍))的输入。
如果用户输入正确,您可以将计数器加 1,但如果不正确,您不执行任何操作,我们continue
在try语句中,第一行可以是您想要测试的任何内容,在这种情况下,float(input("............."))如果输入正确并且没有错误被抛出,那么在这些行下方您可以添加您想要做的事情,在我们的例子中,它将增加计数器加一 ( v += 1) 并将其附加到new. 现在,如果用户输入不正确并抛出一个在我们的例子中是 to 的情况,except我们要做的就是。当抛出错误时,直接跳转到,不执行下一行。ValueErrorcontinueexcept
这是获取用户输入的最终循环:
v = 0
while v < 5:
items = input("...........")
try:
float(items)
v += 1
new.append(items)
except ValueError:
continue
其余的代码可以是相同的!
#defining variables
v = 0
new = []
items = float()
tax = float()
final = float()
subtotal = float()
#gathering input from items
while v < 5:
items = input("Enter the price of item without the $: ")
try:
float(items)
v += 1
print("Input amount is :", "$"+"{0:.2f}".format(float(items)))
new.append(float(items))
except ValueError:
continue
# define calculations
subtotal = sum(new)
tax = subtotal * .07
final = subtotal + tax
# tax & subtotal
print("Subtotal: ", "$"+"{0:.2f}".format(subtotal))
print("Tax: ", "$"+"{0:.2f}".format(tax))
print("Tare: ", "$"+"{0:.2f}".format(final))
就这样!希望你明白为什么...
![?](http://img1.sycdn.imooc.com/54584d1300016b9b02200220-100-100.jpg)
TA贡献1900条经验 获得超5个赞
您无法在结束时获得最终计算的原因是循环实际上并未终止。此外,您的列表中还填充了 的字符串new.append(items)。你会想要new.append(val)这样它会添加这些值。
这是一个使用 @Green Cloak Guy 的 while 循环建议来解决这个问题的版本。我这样做是为了它会添加任意数量的值,并具有明确的“END”条件,用户输入“end”即可退出并获得总计。 items.upper()将所有字母变为大写,因此您可以与“END”进行比较,并且仍然捕获“end”、“End”或“eNd”。
#!/usr/bin/python3
# define variables
# you do not have to declare variables in python, but we do have to
# state that new is an empty list for new.append() to work later
new = []
# welcome and set rules of entering numbers
print("Welcome! Sales tax is 7%. Enter your five items, one (1) at a time.")
print('Type "end" to stop and total items')
# gathering input for items
while True:
items = input("Enter the price of item without the $: ")
if items.upper() == 'END':
break
try:
val = float(items)
except ValueError:
print("Not a valid number. Try again, or 'end' to stop")
new.append(val)
# define calculations
subtotal = sum(new)
tax = subtotal * .07
final = subtotal + tax
# tax & subtotal
print("Subtotal: ", "$"+"{0:.2f}".format(subtotal))
print("Tax: ", "$"+"{0:.2f}".format(tax))
print("Tare: ", "$"+"{0:.2f}".format(final))
![?](http://img1.sycdn.imooc.com/54584ed2000152a202200220-100-100.jpg)
TA贡献1869条经验 获得超4个赞
试试这个方法:
new = []
items = float()
tax = float()
final = float()
subtotal = float()
# welcome and set rules of entering numbers
print("Welcome! Sales tax is 7%. Enter your five items, one (1) at a time.")
try:
new = list(map(lambda x: float(x), list(map(input, range(5)))))
except:
print("Some values are not a number")
# define calculations
subtotal = sum(new)
tax = subtotal * .07
final = subtotal + tax
# tax & subtotal
print("Subtotal: ", "$"+"{0:.2f}".format(subtotal))
print("Tax: ", "$"+"{0:.2f}".format(tax))
print("Tare: ", "$"+"{0:.2f}".format(final))
添加回答
举报