Go back to start or repeat raw input a number of times
本问题已经有最佳答案,请猛点这里访问。
我已经写了一个代码,它可以工作了,因为代码中有变量,我想在最后问这个人是否想退出/继续,他们说继续,它可以一直回到第一个问题。还有一种方法可以从一开始就问这个问题要重复多少次。抱歉,无法上传代码,因为它超过150行助教灰色D
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | i = 0 def code_to_repeat(): # whatever is your code print"I was repeated :" + str(i) +" times" while(True): print"Do you want to run the code (Y/N) :" stri = raw_input() print" " if stri=="Y": i += 1 code_to_repeat() elif stri=="N" print"exiting " break; else: print"Please Answer Y/N only. " |
在您的情况下,while循环应该有效。
1 2 | while(raw_input("to exit enter n")[0] != 'n'): print("Doing some work in the loop, until user enters an 'n'.") |
是请求用户输入的好方法,允许您插入提示,例如
请记住,您应该检查是否超过"n",如用户按回车键。此外,对数据执行简单的分析可能是有意义的,所以你可以做的不仅仅是回应是否有人输入n。
在Python中,while循环应该允许您完成您的目标。您可以使用这样的例子来解决您的问题:
1 2 | while(raw_input()[0] != 'n'): print 'to exit print n' |
如果我正确理解你的问题,这样的事情可能会奏效。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | def dostuff(): ABC = raw_input("Enter Number (q exits):") if(ABC.lower() == 'q'): #Allow the user to enter q at this point to exit return False Product = int(raw_input("Enter Product:")) #do stuff to print out the cost of these items. #We could forgo the next lines and always return True here assuming the user #has more input if they didn't input 'q' for 'ABC'. That's up to you. #return True print"Do you have more purchases [Y/N]?" answer=raw_input() return answer.upper() == 'Y' while dostuff(): pass #same as: #while True: # if(not dostuff()): # break |