0
import random
>>> pc = random.randint(0,5)
>>> 
>>> while user > 0 & user < 6:
    while True:
     user = int(input("enter no"))
    if user < pc :
        print("low")
    elif user > pc:
        print("high")
    else :
        print("correct")
        break

here I was trying to limit the user from 0--6. so that if he enters the beyond the range he can not proceed

EDU_EVER
  • 47
  • 1
  • 8

2 Answers2

0

First, to get an input from the user, depending on which version of python you use, you need to do the following:

For python 2:

user = raw_input("Enter a number between 0 and 6: ")

For python 3:

user = input("Enter a number between 0 and 6: ")

Now, to check if the value entered by the user is between 0 and 6, you have the following check:

if 0 <= int(user) <= 6:
     ...

OR

if int(user) in range(7):
     ...

OR

if int(user) >= 0 and int(user) <= 6:
     ...

All these are valid. It is important to note here that the user will be a string, thus the int(user).

And then within the function, you can raise an exception if they enter a value that is not between 0 and 6 by:

raise ValueError("Invalid number input, must be within 0 and 6")

So in the end you would have something like this:

>>> import random
>>> pc_num = random.randint(0, 6) #Between 0 and 6, inclusive.
>>> while true:
        user_num = int(input("Enter a number between 0 and 6: "))
        if 0 <= user_num <= 6:
            if user_num < pc_num:
                print("low")
            elif user_num > pc_num:
                print("high")
            else:
                print("correct")
                break
        else:
            raise ValueError("Invalid number input, must be within 0 and 6")
  • While you certainly include some useful information, you're missing the most important part. How to check if the user's input is between `0` and `6`. Albeit this is very trivial to check, it seems to be the part the OP is confused about, so this is probably the main part you should address. – Christian Dean Jul 26 '17 at 01:03
0

You can use a while loop to read from user input, then you validate the user's input, if it meets your needs, you just break the loop, otherwise, you can continue the loop to ask for input.

For Python3:

while True:
    try:
        user = int(input('Choose a number: '))
    except ValueError:
        print("Not a number")
        exit(-1)
    if 0 <= user <= 6:
        break
    else:
        print("Make sure the input is between 0 to 6")

# process with the user variable
print(user)
shady
  • 455
  • 1
  • 7
  • 18