reply=float(raw_input("Enter your choice: "))

if reply!=1 or reply!=2:
    print "Not a Valid Choice"

i cant use while loops other wise i prob wouldve done so. Basically im trying to get the user input to only allow the numbers 1 or 2. anything else should give a not a valid choice. i tried it and it works with numbers but when the user enters nothing or letters it gives the traceback error

Recommended Answers

All 4 Replies

reply=float(raw_input("Enter your choice: "))

if reply!=1 or reply!=2:
    print "Not a Valid Choice"

i cant use while loops other wise i prob wouldve done so. Basically im trying to get the user input to only allow the numbers 1 or 2. anything else should give a not a valid choice. i tried it and it works with numbers but when the user enters nothing or letters it gives the traceback error

Well you are turing the reply into a float right off the bat.. So it will allways error if someone enters a string.

>>> float('')

Traceback (most recent call last):
  File "<pyshell#160>", line 1, in <module>
    float('')
ValueError: empty string for float()

Why don't you try allways using a string, as any input can be a string.

Here is an example of how you could use a string in your case:

>>> x = str(raw_input('Enter something: '))
Enter something: 123456
>>> x == '123456'
True
Member Avatar for masterofpuppets

hi,
note that if you only want 1 or 2 the condition of the if statement should be

reply = float(raw_input( "Enter your choice: " ) )
 
if reply != 1 [B]and[/B] reply != 2:
    print "Not a Valid Choice"

otherwise even in you enter 1 there's going to be a non valid choice error :)

You could use

reply = raw_input("Enter your choice: ")
reply = reply.strip()
if reply not in ("1", "2"):
    print("Not a valid choice")
else:
    reply = int(reply)

thanks, much appreciated ya

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.