简体   繁体   English

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

[英]How to stop a while loop after n iterations?

I'm learning python and I am trying to create the guess game with two levels of difficulty: easy (10 tries) and difficult (5 tries).我正在学习 python 并且我正在尝试创建具有两个难度级别的猜谜游戏:简单(10 次尝试)和困难(5 次尝试)。 My code works well, but I need to force the while loop to stop asking for the guess after 5 tries in the difficult level and 10 tries in the easy level.我的代码运行良好,但我需要强制 while 循环在困难级别尝试 5 次和简单级别尝试 10 次后停止询问猜测。 However, with my code I did not reach my goal as the while loop does not stop after n variable < 5 or 10. How can I reach this goal this using the code below:但是,使用我的代码我没有达到我的目标,因为 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()

Looks like you forgot to increment n in your loops, so n is always = 0. Usually you increment your "tracker" variable at the start of the loop or the end of the loop.看起来您忘记在循环中递增n ,因此n始终 = 0。通常您在循环开始或循环结束时递增“tracker”变量。 Incrementing in python can be done with n += 1 .递增 python 可以用n += 1完成。

The short answer is that you need to add a n += 1 in the while loops, like that:简短的回答是你需要在 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 :(')

Long answer is that you should really consider using a for loop instead, here is an example of how you can do that:长答案是你真的应该考虑使用 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 :(')

And you should make your script a lot cleaner by removing the repetitive code like this:你应该通过删除像这样的重复代码来使你的脚本更清晰:

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 :(')

Here I removed the two functions that you had and I made it so that there is only one loop which makes the code a lot cleaner, I also changed the levels() function name to chooseLevel() to make it clearer on what the function does and I also added spaces between the = which makes things look cleaner.在这里,我删除了你拥有的两个函数,我做了它,以便只有一个循环使代码更清晰,我还将levels() function 名称更改为chooseLevel()以使其更清楚 function 的作用我还在=之间添加了空格,这让事情看起来更干净。

I also used the for loop like this for i in range(chooseLevel()) Which means that if the chooseLevel() function returned a 5 it will be as if I wrote for i in range(5) and if the chooseLevel() function returns a 10 it will be as if I wrote for i in range(10)我还使用了这样的 for 循环for i in range(chooseLevel())这意味着如果chooseLevel() function 返回5就好像我for i in range(5)如果chooseLevel() function返回10就好像我写了for i in range(10)

Thanks.谢谢。

You need to increment n after each iteration, by either reassigning n (ex. n = n + 1 ), or using the += operator like this:您需要在每次迭代后递增 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()

Probably easier to use a for loop like so:像这样使用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 :(')

A good rule of thumb is if you are using the same code twice put it in a function. It's sure to get out of sync over time then you'll be wondering why "easy" works but "hard" does something odd (or some variation of that).一个好的经验法则是,如果您两次使用相同的代码,请将其放入 function。随着时间的推移,它肯定会不同步,那么您会想知道为什么“简单”有效,但“困难”却做了一些奇怪的事情(或一些的变化)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM