-2

I'm trying to make it so it only allows numbers, not strings.

number = (input("Pick a number "))

I have tried using (raw_input("")), but this error comes up:

"line 1, in number = (raw_input("Pick a number ")) NameError: name 'raw_input' is not defined"

I also tried int(raw_input("")), and the same error came up.

I also tried int(input("")), but an error came up aswell:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Inactive
  • 13
  • 2
  • 5

1 Answers1

1

To ensure your input is a number, you can use:

while True:
    try:
        n = int(input("pick: "))
        break
    except:
        print("Expecting a number...")
        pass

Example:

pick: adsf
Expecting a number...
pick: dsf
Expecting a number...
pick: 2

The idea: casting something else than a number with int() throws an error, so you keep asking until no error is thrown.

If you use python2, you might prefer using raw_input.

Derlin
  • 9,572
  • 2
  • 32
  • 53