将输入的整数分离到列表中以检查列表中的每个元素是否满足要求

时间:2013-10-08 20:01:44

标签: python

input_list = input("Enter numbers separated by spaces: ")

number = input_list.split()
for n in number:
     a = int(n)
if len(number)!=5 or number>5 or number<0 :
        print ('invalid input')
        if 0< a <=5:
            print ('x'* a)
        elif a == 0:
            print ('.')

我的程序正在检查输入的5位数字,好像它们是一个数字,但我希望我的程序首先确保输入5位数,然后检查它们是否介于0和5之间,但程序结合了所有5位数字在一个数字中,我希望程序自己检查列表中的每个元素,然后在打印任何内容之前,我希望程序检查输入的数字是否满足所有条件,如果不打印(无效输入)并停止它们< / p>

4 个答案:

答案 0 :(得分:1)

input_list = input("Enter numbers separated by spaces: ")

numbers = input_list.split()

if len(numbers) == 5 and all(0 <= int(n) <= 5 for n in numbers):
    print("ok")
    print("".join(numbers))
else:
    print("invalid")

答案 1 :(得分:0)

我在python 2中使用raw_input。对于python 3,输入正常。

input_list = raw_input("Enter numbers separated by spaces: ").split()
numbers = [int(n) for n in input_list if 0 <= int(n) <= 5]
if len(numbers) != 5:
    print ('invalid input')

for a in numbers:
    if a == 0:
        print ('.')
    else:
        print ('x'* a)

答案 2 :(得分:0)

input_list = input("Enter numbers separated by spaces: ")

number = input_list.split()
if len(number) == 5:
    for n in number:
        a = int(n)
        if 0< a <=5:
            print ('x'* a)
        elif a == 0:
            print ('.')
        else:
            print ("Number does not lie in the range 0 to 5.")
else:
    print ("Invalid Input.")
Yes, the above works but is should check input first to make sure it is valid

答案 3 :(得分:-1)

number = raw_input("Enter numbers separated by spaces: ")
2   num_list = number.split()
3   for n in num_list:
4       a = 'True'
5       if int(n) <0 or int(n) >5:
6           a = 'False'
7           break       
8   if (len(num_list) == 5) and a == 'True':
9       for n in num_list:
10          b = int(n)
11          if 0< b <=5:
12              print ('x'* b)
13          elif b == 0:
14              print ('.')
15  else:
16      print 'Invalid Input!'