我是python和编码的新手,对于学校项目我必须打印一张简单的收据。我正在使用一些功能,其中一个功能要求购买物品的价格,使用While Not Loop。输入循环,直到用户输入' 0'。
问题在于,如果我输入带有三位或更多小数位的购买商品价格(例如19.999)。当它们在输入错误后输入0时,Return命令似乎卡在了While Not Loop中。当代码到达Return命令时,执行跳转到While Not循环并再次返回,然后在While Not循环中途跳转到价格= str(价格)'并继续正常。结果是我们无法以预期的方式退出程序,使用' 0'。
这是功能。
def shop_list(): #this definition asks for the prices of the items, adds the input to a list and loops, until 0 is entered, which stops the loop.
while True:
try:
prices = float(input("Please input a value. Enter 0 to print receipt: ")) # the input that allows the customer to enter their prices
zero_check.append(prices)
if prices == 0:
if len(zero_check) == 1:
if zero_check[0] == 0:
exit_ask()
else:
'do nothing' #this is a place holder line, something must be here but we dont need anything here
else:
'do nothing'
else:
'do nothing'
except ValueError: #if the input creates an error, do the below
print("\nERROR, please enter a valid number.\n") #this error message will come up if you input anything other than a number
continue #loops the back to the 'try'
else:
break #breaks the While True loop
if prices != 0:
number = None
while not number:
prices = str(prices) #converting the price to a string so we can split it
string_number = prices.split(".") #splitting the price at the decimal point
if len(string_number[1]) > 2: #if there is more than two decimal points, print an error
print ("\nERROR: Too many decimal places!\n")
prices = float(prices)
shop_list()
else:
number = float(prices)
prices = str(prices)
price_lnth = len(prices)
if price_lnth > 15:
print ('\nERROR, too many numbers.\n')
shop_list()
else:
prices = float(prices)
if prices > 0: #if the input was valid then this will run
shopplist.append(prices) #this is what adds a price into a list
shop_list() # loops back to the start of this definition
elif prices < 0:
print('\nERROR, no negative numbers.\n')
shop_list() # loops back to the start of this definition
else:
'do nothing'
return
答案 0 :(得分:0)
当出现错误时(在正常逻辑中),您递归调用backgroundReadFile
。然后输入0时,第二次调用返回,但原始的调用继续执行。我建议只使用循环,而不是递归,或者只是递归(但请记住,递归会占用堆栈空间)。