Loop until a specific user input
本问题已经有最佳答案,请猛点这里访问。
我正在尝试编写一个数字猜测程序,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | def oracle(): n = ' ' print 'Start number = 50' guess = 50 #Sets 50 as a starting number n = raw_input(" True, False or Correct?:") while True: if n == 'True': guess = guess + int(guess/5) print 'What about',guess, '?' break elif n == 'False': guess = guess - int(guess/5) print 'What about',guess, '?' break elif n == 'Correct': print 'Success!, your number is approximately equal to:', guess |
Oracle()
我现在要做的是让if/elif/else命令的序列循环,直到用户输入"correct",也就是说,当程序声明的数字大约等于用户数时,但是如果我不知道用户数,我就无法思考如何实现和if语句,并且我尝试使用"while"也不起作用。
作为@mark byers方法的替代方法,您可以使用
1 2 3 4 5 6 7 8 9 | guess = 50 # this should be outside the loop, I think while True: # infinite loop n = raw_input(" True, False or Correct?:") if n =="Correct": break # stops the loop elif n =="True": # etc. |
您的代码将不起作用,因为您在第一次使用之前没有将任何内容分配给
1 2 3 4 | def oracle(): n = None while n != 'Correct': # etc... |
一种更易读的方法是将测试移动到稍后,并使用
1 2 3 4 5 6 7 8 9 | def oracle(): guess = 50 while True: print 'Current number = {0}'.format(guess) n = raw_input("lower, higher or stop?:") if n == 'stop': break # etc... |
另外,python 2.x中的
注:在python 3.x中,