简体   繁体   English

如何在不使用最流行的函数的情况下跳出我的 while 循环?(sys.exit、break 等)

[英]How do I break out of my while loop without using the most popular functions?(sys.exit,break,etc.)

I am making a program that generates a random number and asks you to guess the number out of the range 1-100.我正在制作一个生成随机数的程序,并要求您猜测 1-100 范围之外的数字。 Once you put in a number, it will generate a response based on the number.输入数字后,它会根据该数字生成响应。 In this case, it is Too high , Too low , Correct , or Quit too soon if the input is 0, which ends the program(simplified, but basically the same thing).在这种情况下,如果输入为 0,则Too highToo lowCorrectQuit too soon结束程序(简化,但基本相同)。

It counts the number of attempts based on how many times you had to do the input function, and it uses a while loop to keep asking for the number until you get it correct.它根据您必须输入 function 的次数来计算尝试次数,并使用 while 循环不断询问数字,直到您输入正确为止。 The problem that I am facing is that I have to make it break out of the while loop once the guess is either equal to the random number or 0 .我面临的问题是,一旦猜测等于随机数或0 ,我就必须让它跳出 while 循环。 This normally isn't an issue, because you could use sys.exit() or some other function, but according to the instructions I can't use break , quit , exit , sys.exit , or continue .这通常不是问题,因为您可以使用sys.exit()或其他一些 function,但根据说明我不能使用breakquitexitsys.exitcontinue The problem is most of the solutions I've found for breaking the while loop implement break , sys.exit , or something similar and I can't use those.问题是我找到的大多数解决方案都是为了打破 while 循环实现breaksys.exit或类似的东西,但我不能使用它们。 I used sys.exit() as a placeholder, though, so that it would run the rest of the code, but now I need to figure out a way to break the loop without using it.不过,我使用sys.exit()作为占位符,以便它运行代码的 rest,但现在我需要找出一种不使用它来中断循环的方法。 This is my code:这是我的代码:

import random
import sys

def main():
    global attempts
    attempts = 0
    guess(attempts)
    keep_playing(attempts)
    
def guess(attempts):
    number = random.randint(1,100)
    guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
    while guess != 0: 
        if guess != number:
            if guess < number:
                print("Too low, try again")
                attempts += 1
                guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
            elif guess > number:
                print("Too high, try again")
                attempts += 1
                guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
        else:
            print()
            print("Congratulations! You guessed the right number!")
            print("There were", attempts,"attempts")
            print()
            #Ask if they want to play again
            sys.exit()#<---- using sys.exit as a placeholder currently
    else:
        print()
        print("You quit too early")
        print("The number was ",number,sep='')
        #Ask if they want to play again
        sys.exit()#<----- using sys.exit as a placeholder currently
    
    

def keep_playing(attempts):
    keep_playing = 'y'
    if keep_playing == 'y' or keep_playing == 'n':
        if keep_playing == 'y':
            guess(attempts)
            keep_playing = input("Another game (y to continue)? ")
        elif keep_playing == 'n':
            print()
            print("You quit too early")
            print("Number of attempts", attempts)
main()

If anyone has any suggestions or solutions for how to fix this, please let me know.如果有人对如何解决此问题有任何建议或解决方案,请告诉我。

Try to implement this solution to your code:尝试对您的代码实施此解决方案:

is_playing = True

while is_playing:
    if guess == 0:
        is_playing = False
        your code...
    else:
        if guess == number:
            is_playing = False
            your code...
        else:
            your code...

Does not use any break etc. and It does breaks out of your loop as the loop will continue only while is_playing is True.不使用任何 break 等,它确实会跳出循环,因为只有在 is_playing 为 True 时循环才会继续。 This way you will break out of the loop when the guess is 0 (your simple exit way) or when the number is guessed correctly.这样,当猜测为 0(您的简单退出方式)或猜对数字时,您将跳出循环。 Hope that helps.希望有所帮助。

I am not a fan of global variables but here it's your code with my solution implemented:我不是全局变量的粉丝,但这是您实现我的解决方案的代码:

import random

def main() -> None:
    attempts = 0
    global is_playing
    is_playing = True
    while is_playing:
        guess(attempts)
        keep_playing()
    
def guess(attempts: int) -> None:
    number = random.randint(1,100)
    print(number)
    is_guessing = True
    while is_guessing:
        attempts += 1
        guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
        if guess == 0:
            is_guessing = False
            print("\nYou quit too early.")
            print("The number was ", number,sep='')
        else:
            if guess == number:
                is_guessing = False
                print("\nCongratulations! You guessed the right number!")
                print("There were", attempts, "attempts")
            else:
                if guess < number:
                    print("Too low, try again.")
                elif guess > number:
                    print("Too high, try again.")
                
def keep_playing() -> None:
    keep_playing = input('Do you want to play again? Y/N ')
    if keep_playing.lower() == 'n':
        global is_playing
        is_playing = False

main()

TIP: instead "There were", attempts, "attempts" do: f'There were {attempts} attempts.'提示:而不是"There were", attempts, "attempts"做: f'There were {attempts} attempts.'

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

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