简体   繁体   中英

Python 2.7 taking input from user for two separate variables

getMin, getMax = int(input("Enter a range (min,max): "));

Above is the code I am trying to implement but it gives me an error saying...

int() argument must be a string or a number, not 'tuple'

Basically, I have tried entering .split(,) after the input statement but I get the same error. When a user enters 1,10 as an input I want getMin = 1 and getMax = 10

Since you're on Python 2, you should be using raw_input instead of input . Try something like this:

from ast import literal_eval

prompt = "Enter a range (min,max): "
getMin = getMax = None

while {type(getMin), type(getMax)} != {int}:
    try:
        getMin, getMax = literal_eval(raw_input(prompt))
    except (ValueError, TypeError, SyntaxError):
        pass  # ask again...

IMHO, cleaner approach assuming you want the input to be comma separated

>>> prompt = "Enter a range (min,max): "
>>> while True:
...     try:
...             getMin, getMax = map(int, raw_input(prompt).split(','))
...             break
...     except (ValueError, TypeError):
...             pass
... 
Enter a range (min,max): skfj slfjd
Enter a range (min,max): 232,23123,213
Enter a range (min,max): 12, 432
>>> getMin
12
>>> getMax
432

the input function (see doc here ) will try to evaluate the provided input. For example, if you feed it with your name AMcCauley13 it will look for a variable named so. Feeding it with values like 1,10 will evaluate in a tuple (1,10) , which will break the int() function that expects a string.

Try with the simpler

getMin = int(raw_input("min range: "))
getMax = int(raw_input("max range: "))

or combining split and map as balki suggested in the meanwhile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM