0

I am having a problem trying to enforce my python code in order to avoid that a number out of a specific range can be provided in input.

I created a list of process to monitor and subselect function is to check the input validity. Accepted values should be from 1 to 9

My design works well for number but if by mistake another type is given I get NameErr

def subselect():
    while True:
        choise = input("Please select a Subsystem to monitor: ")
        print(type(choise))
        print(choise)
        if int(choise) <= 0 or choise >= 10:
           print("Selection invalid")
        else:
           return choise


if __name__== "__main__":
    subsystem = ["","a","b","c","d","e","f","g","h"]
    while True:
        print("1  - a")
        print("2  - b")
        print("3  - c")
        print("4  - d")
        print("5  - e")
        print("6  - f")
        print("7  - g")
        print("8  - h")
        print("9  - i")
    select = subselect()

Executing the script I get NameError for provided input in case it's not numeric.

1  - a
2  - b
3  - c
4  - d
5  - e
6  - f
7  - g
8  - h
9  - i
Please select a Subsystem to monitor: 20
<type 'int'>
20
Selection invalid
Please select a Subsystem to monitor: fff

Traceback (most recent call last):
  File "./MyScript.py", line 102, in <module>
    select = subselect()
  File "./MyScript.py", line 72, in subselect
    choise = input("Please select a Subsystem to monitor: ")
  File "<string>", line 1, in <module>
**NameError: name 'fff' is not defined**

I also tried to use int but same result choise = int(input("Please select a Subsystem to monitor: "))

  • Sounds like you're using python 2 and need to use `raw_input` – Alex Hall May 04 '18 at 15:11
  • kindly add relevant version tag of language too while asking question. like you can use both tag `python` because it's parent tag and `python-2.x` or `python-3.x` suitable to your question – Gahan May 04 '18 at 15:20

1 Answers1

0

If you are using python 2, you need to use raw_input like this:

choise = raw_input("Please select a Subsystem to monitor: ")

Because in python2.x, input returns raw code instead of a string. In python3.x however, you would need something like this to get the raw code:

exec('a='+input('enter some raw code'))

Or if you just want a variable:

a=eval(input('enter a variable (like this: var) that has been previously assigned, or like this: 'some text', 5, [1, 2, 3]'))
Artemis
  • 2,553
  • 7
  • 21
  • 36