我已經在下面編寫了Python代碼(實際上它是我在第24頁的「在24小時內自學Python」練習的解決方案)。如何在循環內發出警告並要求輸入raw_input
想法是:餐桌周圍有4個座位,服務員知道每個座位的訂購量,輸入這4個數量並獲得總數。
如果提供的raw_input不是一個數字(而是一個字符串),我的代碼會將這個人踢出去。但是,目標是給出錯誤消息(「此條目無效」)並再次詢問輸入 - 直到它爲數字。但是,我無法弄清楚如何再次詢問用戶的原始輸入 - 因爲我已經在循環中了。
非常感謝您的建議!
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
break
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
非常感謝 - 這個解決方案非常棒! – user3245256