Alaa KM
Alaa KM

Reputation: 41

How to exit the program when the user write "exit"?

i'm writing a program asking the user to guess number which already generated automatically. the think that as per below code the user should to enter int number but what if the user enter "exit" to exit the program it will show an error due "exit" is string not int, how to solve this issue since i tried to find the solution but i did not find the proper answer

import random
import sys

def GuessedNumber():

    while(True):
        Generate = random.randint(1,9)

        GuessNumber = int(input("Dear user kidnly guess a number between 1-9: "))

        if GuessNumber == Generate:
            print("You guessed right number")

        elif GuessNumber > Generate:
            print("Guessed number is too high")

        elif GuessNumber < Generate:
            print("Guessed number is too low")



GuessedNumber()

Upvotes: 0

Views: 78

Answers (2)

LordOfThunder
LordOfThunder

Reputation: 310

You can check the input is in valid range 1-9 or not. If the input is in the range then do what you were doing, else if the input is exit then exit the game otherwise say him to enter valid input and continue the loop. Here is the code:

import random

def GuessedNumber():
    while(True):
        Generate = random.randint(1,9)
        GuessNumber = input("Dear user kidnly guess a number between 1-9: ")
        if GuessNumber in list('123456789'):
            GuessNumber = int(GuessNumber)
            if GuessNumber == Generate:
                print("You guessed right number")
            elif GuessNumber > Generate:
                print("Guessed number is too high")
            elif GuessNumber < Generate:
                print("Guessed number is too low")
        else:
            if GuessNumber == 'exit':
                print('Good bye!')
                break
            else: # for any other non invalid input
                print('Please enter a valid input')
                continue

GuessedNumber()

Upvotes: 1

Markus
Markus

Reputation: 3317

Assign the input to a string, then check for exit, and only if it doesn't match then proceed with the conversion to an integer variable.

Upvotes: 2

Related Questions