4 回答

TA貢獻2051條經驗 獲得超10個贊
我清理了輸出并利用反饋使其工作得更好?,F在,如果人們有關于簡化代碼的建議,那就太好了。我想確保我以 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))

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))
就這樣!希望你明白為什么...

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))

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))
添加回答
舉報