Newbie
Newbie

Reputation: 25

Error while performing python try-except part

Python number guessing game.

from random import randint

ran_no = randint(1,10)
print(ran_no)#for checking the output


try:
    guess = int(input('\nYour guess between 1 to 10:- '))
except ValueError:
    print("\n\tPlease enter numbers only\n")
    quit

if type(guess) == int:
    if guess == ran_no:
        print("\n\t\tWhola, Your guess is correct!\n")
    elif guess > 10:
        print("\n\t\tUghh, Your guess is above limit!\n")
    elif guess < 1:
        print("\n\t\tUghh, Your guess is below limit!\n")
    else:
        print("\n\t\tUghh, Try again...\n")
else:
    print("\n\tPlease enter numbers only\n")

When i use try-except when except condition occurs i don't know know how should i end code, please help

Upvotes: 0

Views: 79

Answers (3)

Subasri sridhar
Subasri sridhar

Reputation: 831

See if this helps:

from random import randint

ran_no = randint(1,10)
print(ran_no)#for checking the output


try:
    guess = input('\nYour guess between 1 to 10:- ')
    if type(int(guess)) == int:
        guess =(int(guess)) 
        if guess == ran_no:
            print("\n\t\tWhola, Your guess is correct!\n")
        elif guess > 10:
            print("\n\t\tUghh, Your guess is above limit!\n")
        elif guess < 1:
            print("\n\t\tUghh, Your guess is below limit!\n")
        else:
            print("\n\t\tUghh, Try again...\n")
    else:
        print("\n\tPlease enter numbers only\n")
except ValueError:
    print("\n\tPlease enter numbers only\n")
    quit()

Sample output 1:

enter image description here

Sample output 2:

enter image description here

Upvotes: 0

Ahmed Elgammudi
Ahmed Elgammudi

Reputation: 746

i think you need to add () after quit

from random import randint

ran_no = randint(1,10)
print(ran_no)#for checking the output


try:
    guess = int(input('\nYour guess between 1 to 10:- '))
except ValueError:
    print("\n\tPlease enter numbers only\n")
    quit()

if type(guess) == int:
    if guess == ran_no:
        print("\n\t\tWhola, Your guess is correct!\n")
    elif guess > 10:
        print("\n\t\tUghh, Your guess is above limit!\n")
    elif guess < 1:
        print("\n\t\tUghh, Your guess is below limit!\n")
    else:
        print("\n\t\tUghh, Try again...\n")
else:
    print("\n\tPlease enter numbers only\n")

Upvotes: 1

Wazaa
Wazaa

Reputation: 146

you could use "exit(0)" instead of quit

Upvotes: 0

Related Questions