We help IT Professionals succeed at work.

Python - creating message

snhandle
snhandle asked
on
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
Comment
Watch Question

CERTIFIED EXPERT

Commented:

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



if n < 0 or n > 20:
    break
Excel & VBA Expert
CERTIFIED EXPERT
Most Valuable Expert 2018
Awarded 2015
Commented:

Like this...


import random
n = random.randint(1, 20)
guess = int(input("Enter an integer from 1 to 20: "))

while n != "guess":
    if guess <=0 or guess > 20:
        break
    elif 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
CERTIFIED EXPERT
Top Expert 2014
Commented:
Two recommendations:
1. remove the quotes around guess
while n != guess:

Open in new window


2. Slight tweak on Neeraj. I find that it is easier to see the inequalities if written this way.
while n != guess:
    if guess < 1 or 20 < guess:
        break
    elif 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

Open in new window

CERTIFIED EXPERT
Top Expert 2014

Commented:
Of course, this would be the most Pythonic form.
    if Not (1 <= guess <= 20):
        break

Open in new window

Author

Commented:
Very helpful!!