Link to home
Start Free TrialLog in
Avatar of snhandle
snhandle

asked on

Python - creating message

In the below script I like to add if someone guess number less than 0 or more than 20 then it should give message and terminate the program. How I can do that? thanks

import random
n = random.randint(1, 20)
guess = int(input("Enter an integer from 1 to 20: "))
while n != "guess":
    print
    if guess < n:
        print ("guess is low")
        guess = int(input("Enter an integer from 1 to 20: "))
    elif guess > n:
        print ("guess is high")
        guess = int(input("Enter an integer from 1 to 20: "))
    else:
        print ("you guessed it!")
        break
    print
Avatar of gelonida
gelonida
Flag of France image

the command you're looking for is  `break`, which breaks out of a while or for loop.



if n < 0 or n > 20:
    break

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Subodh Tiwari (Neeraj)
Subodh Tiwari (Neeraj)
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Of course, this would be the most Pythonic form.
    if Not (1 <= guess <= 20):
        break

Open in new window

Avatar of snhandle
snhandle

ASKER

Very helpful!!