简体   繁体   中英

Python user input split() and loop

I am taking user input as follows: 0,1,2,3,5 The user can write any number and separate it with a comma, the input will be x,y,z,k,c

Then I am having trouble checking if any of the number after split() is invoked is 0 or more than 30.

Code-snippet:

numbers = input(user[i]['name'] + 
", assign 10 different numbers between 1-30 (separate each with a comma ','): ")
        usrNums = numbers.split()

for number in usrNums:
    if number < 1 or number > 30: 
     #Something goes here, however, not important now. 

Ps I've read a little bit on all()

Clarification: The user inputs some numbers eg 0,5,2,9,7,10 the usrNums = numbers.split() split() is invoked and these are stored in usrNums , then I want to check each number in usrNums [0, 5, 2, 9, 7, 10] if any of them is "0 meaning number < 1 or > 30".

EDIT: NO THIS IS NOT A DUPLICATE, I read through, How can I read inputs as integers in Python? , and it isn't the same at all. My question is about user inputting numbers with separated commas, not one number per input.

when you use split the numbers are of type string. To compare with 1 or 30 convert these to integers

numbers  = "0,1,2,3,5"
usrNums = numbers.split(",")
#usrNums ["0","1","2","3","5"]
for number in usrNums:
    if int(number) < 1 or int(number) > 30: 
numbers = "1,2,3,31"
for number in numbers.split(","):
    number = eval(number) # or use int(number) or float(number) as example
    if number < 1 or number > 30:
        #do something

You forget the "," in the split function and forget to convert the string into an integer.

You can use map() method.

numberString = '1, 2, 3, 4, 5, 6, 7'
numbers = map(int, numberString.split(',')) # numbers = [1, 2, 3, 4, 5, 6, 7]
for num in numbers:
    if num < 1 or num > 30:
        # Do whatever you want here...

Hope this helps! :)

The input is a string. Use eval to compare to int :

for number in usrNums:
     if eval(number) < 1 or eval(number) > 30: 
     #Something goes here, however, not important now. 

You also need to indicate how to split the string : input.split(',')

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