简体   繁体   中英

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. 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).

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. 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 . 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 . 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. 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. 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. 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. 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.'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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