如何回到循环的开始

时间:2019-11-04 17:35:01

标签: python while-loop

问题:创建一个程序,让用户猜测计算机生成的数字。玩家尝试了5次,如果他猜错了,程序将结束。

我以两种方式完成了该程序。

第一条路

import random  
import sys  

def computer_number () :
  return random.randint (1, 20) 

def user_number () :
  return int (input ("Number: "))

def number_verification () :
  w_ans = 0  # counts the number of wrong ans..
  t = 0  # counts the number of turns so far...
  while True :
    cpu_number = computer_number ()
    print (cpu_number)
    player_number = user_number ()
    if cpu_number == player_number :
      print ("Right guess.")
      sys.exit ()  # program ends when user guesses right
    else:
      w_ans += 1
      t += 1
      print ("Wrong answer.", 5 - t, " turns left.")
      if t > 4 :
        print ("Maximum tries exceded.")
        sys.exit ()
  return w_ans, t

number_verification ()

第二种方式

import sys
import random

def number_validation (cpu_number, player_number) :
    w_ans = 0 
    t = 0 
    while t < 5 :
        if cpu_number == player_number :
            print ("OK")
            sys.exit ()
        else :
            w_ans += 1
            t += 1
            print ("Wrong number", 5 - t, " turns left.")
            if t > 4 :
                print ("Maximum tries exceded.")
                sys.exit ()


cpu_number = random.randint (1, 20)
print (cpu_number)
player_number = int (input ("Number: "))
print (number_validation (cpu_number, player_number))

我基本上不了解的是,在我的两个程序中,while循环的结构相同。但是,在第二个程序中,如果我输入了错误的数字,则会得到以下输出。

1
Number: 9
Wrong number 4  turns left.
Wrong number 3  turns left.
Wrong number 2  turns left.
Wrong number 1  turns left.
Wrong number 0  turns left.
Maximum tries exceded.


为什么我的两个程序的行为方式不同。

2 个答案:

答案 0 :(得分:1)

那是因为您每次都在这里的第一个while循环中从用户那里得到输入:

while True :
  cpu_number = computer_number ()
  print (cpu_number)
  player_number = user_number ()

而在第二个while循环中,您只能在while循环之外获得它一次

cpu_number = random.randint (1, 20)
print (cpu_number)
player_number = int (input ("Number: "))
print (number_validation (cpu_number, player_number))

只需在您的while内添加以下代码行即可使其像您的第一个代码一样工作。

player_number = int (input ("Number: "))

提示:请使用调试器回溯此类混乱情况。

答案 1 :(得分:0)

问题在于输入的位置。您的第二个函数接受一个输入,并使用while循环。您需要将输入放置在while循环中:


import sys
import random

def number_validation (cpu_number) :
    w_ans = 0
    t = 0
    while t < 5 :
        player_number = int (input ("Number: "))
        if cpu_number == player_number :
            print ("OK")
            sys.exit ()
        else :
            w_ans += 1
            t += 1
            print ("Wrong number", 5 - t, " turns left.")
            if t > 4 :
                print ("Maximum tries exceded.")
                sys.exit ()


cpu_number = random.randint (1, 20)
print (cpu_number)
number_validation (cpu_number)