如何在 n 次迭代后停止 while 循环?

How to stop a while loop after n iterations?

我正在学习 python 并且我正在尝试创建具有两个难度级别的猜谜游戏:简单(尝试 10 次)和困难(尝试 5 次)。我的代码运行良好,但我需要强制 while 循环在困难级别尝试 5 次和简单级别尝试 10 次后停止询问猜测。但是,使用我的代码我没有达到我的目标,因为 while 循环在 n 变量 < 5 或 10 之后不会停止。我如何使用下面的代码达到这个目标:

from random import *

def levels():
  user_level=input('Type E for easy level and D for difficult level: ')
  if user_level=='e':
    easy_level()
  else:
    difficult_level()

number=randint(1,100)

def difficult_level():
  n= 0
  while n < 5:
    user_number=int(input('Guess the number: '))
    if user_number > number:
      print('Too high')
    elif user_number < number:
      print('Too low')
    elif user_number == number:
      print(f'You guessed the number {number}! Congratulations!')
      play_again=input('Would you like to play again? type y for yes or n for no: ')
      if play_again =='y':
        levels()
      else:
        print('Bye')
        break
  print('Sorry, no more attempts :(')


def easy_level():
  n= 0
  while n < 10:
    user_number=int(input('Guess the number: '))
    if user_number > number:
      print('Too high')
    elif user_number < number:
      print('Too low')
    elif user_number == number:
      print(f'You guessed the number {number}! Congratulations!')
      play_again=input('Would you like to play again? type y for yes or n for no: ')
      if play_again =='y':
        levels()
      else:
        print('Bye')
         break
  print('Sorry, no more attempts :(')


levels()

您似乎忘记在循环中递增 n,因此 n 始终 = 0。 通常你在循环开始或循环结束时增加你的“tracker”变量。 python 的递增可以用 n += 1.

完成

您需要在每次迭代后递增 n,方法是重新分配 n(例如 n = n + 1),或使用 += 运算符,如下所示:

from random import *

def levels():
  user_level=input('Type E for easy level and D for difficult level: ')
  if user_level=='e':
    easy_level()
  else:
    difficult_level()

number=randint(1,100)

def difficult_level():
  n= 0
  while n < 5:
    user_number=int(input('Guess the number: '))
    if user_number > number:
      print('Too high')
    elif user_number < number:
      print('Too low')
    elif user_number == number:
      print(f'You guessed the number {number}! Congratulations!')
      play_again=input('Would you like to play again? type y for yes or n for no: ')
      if play_again =='y':
        levels()
      else:
        print('Bye')
        break

    n += 1 # increment n after each iteration

  print('Sorry, no more attempts :(')


def easy_level():
  n= 0
  while n < 10:
    user_number=int(input('Guess the number: '))
    if user_number > number:
      print('Too high')
    elif user_number < number:
      print('Too low')
    elif user_number == number:
      print(f'You guessed the number {number}! Congratulations!')
      play_again=input('Would you like to play again? type y for yes or n for no: ')
      if play_again =='y':
        levels()
      else:
        print('Bye')
         break

    n += 1 # increment n after each iteration

  print('Sorry, no more attempts :(')


levels()

像这样使用 for 循环可能更容易:

def levels():
  easy_turns = 5
  hard_turns = 10
  user_level=input('Type E for easy level and D for difficult level: ')
  if user_level=='e':
    play(easy_turns)
  else:
    play(hard_turns)

def play(turns):
  for _ in range(turns):
    user_number=int(input('Guess the number: '))
    if user_number > number:
      print('Too high')
    elif user_number < number:
      print('Too low')
    elif user_number == number:
      print(f'You guessed the number {number}! Congratulations!')
      play_again=input('Would you like to play again? type y for yes or n for no: ')
      if play_again =='y':
        levels()
      else:
        print('Bye')
         break
  print('Sorry, no more attempts :(')

一个好的经验法则是,如果您两次使用相同的代码,请将其放入一个函数中。随着时间的推移,它肯定会失去同步,然后你会想知道为什么“简单”有效,而“困难”却做了一些奇怪的事情(或一些变体)。

简短的回答是您需要在 while 循环中添加一个 n += 1,例如:

def easy_level():
  n= 0
  while n < 10:
    user_number=int(input('Guess the number: '))
    if user_number > number:
      print('Too high')
    elif user_number < number:
      print('Too low')
    elif user_number == number:
      print(f'You guessed the number {number}! Congratulations!')
      play_again=input('Would you like to play again? type y for yes or n for no: ')
      if play_again =='y':
        levels()
      else:
        print('Bye')
         break

    n += 1

  print('Sorry, no more attempts :(')

长话短说,您真的应该考虑使用 for 循环,下面是一个如何做到这一点的示例:

def easy_level():
  for i in range(10)
    user_number=int(input('Guess the number: '))
    if user_number > number:
      print('Too high')
    elif user_number < number:
      print('Too low')
    elif user_number == number:
      print(f'You guessed the number {number}! Congratulations!')
      play_again=input('Would you like to play again? type y for yes or n for no: ')
      if play_again =='y':
        levels()
      else:
        print('Bye')
         break

  print('Sorry, no more attempts :(')

并且您应该通过删除像这样的重复代码来使您的脚本更清晰:

from random import *

def chooseLevel():
  user_level=input('Type E for easy level and D for difficult level: ')
  if user_level=='e':
    return 10
  else:
    return 5

number = randint(1,100)
for i in range(chooseLevel()):
    user_number = int(input('Guess the number: '))
    if user_number > number:
      print('Too high')
    elif user_number < number:
      print('Too low')
    elif user_number == number:
      print(f'You guessed the number {number}! Congratulations!')
      play_again = input('Would you like to play again? type y for yes or n for no: ')
      if play_again =='y':
        levels()
      else:
        print('Bye')
         break

  print('Sorry, no more attempts :(')

在这里,我删除了您拥有的两个函数,我做了一个循环,使代码更清晰,我还将 levels() 函数名称更改为 chooseLevel()为了更清楚地说明函数的作用,我还在 = 之间添加了空格,这让事情看起来更清晰。

我也是这样使用for循环的for i in range(chooseLevel()) 这意味着如果 chooseLevel() 函数返回一个 5 就好像我写了 for i in range(5) 并且如果 chooseLevel() 函数 returns 一个 10就好像我写了 for i in range(10)

谢谢。