检查空白条目

时间:2019-05-24 14:59:33

标签: python

我正在尝试从用户处获取输入,如果该输入为空,则应该看到带有(请输入数字)的消息

我尝试使用if语句并将其设置为等于None

def get_player_numbers():
    number_csv = input("Enter your 6 numbers, separated by commas: ")
    if number_csv == None:
        print("Enter something")
        get_player_numbers()
    else:
        number_list = number_csv.split(",")
        integer_set = {int(number) for number in number_list}
        return integer_set

我应该能够看到 (“请输入数字,输入不能为空”)

3 个答案:

答案 0 :(得分:1)

input()始终返回一个字符串。空的输入返回一个空字符串:

if number_csv == '':
        print("Please enter digits , input can't be blank")

由于隐含虚假的空字符串,可以将其简化为:

if not number_csv:
        print("Please enter digits , input can't be blank")

答案 1 :(得分:1)

我认为这不会编译,因为您将收到文件结束错误。您应该使用raw_input()而不是input()。区别在于input()返回python表达式类型的对象,而raw_input返回一个字符串。在这种情况下,您将要比较字符串。您的新代码将是...

def get_player_numbers():
    number_csv = raw_input("Enter your 6 numbers, separated by commas: ")
    if number_csv == "":
        print("Enter something")
        return get_player_numbers()
   else:
        number_list = number_csv.split(",")
        integer_set = {int(number) for number in number_list}
        return integer_set

注意:现在,您的if语句会将输入值与“”而不是“ None”进行比较。

编辑:感谢您的评论!如果用户输入空格,我通过添加return语句来修复递归调用。这需要发生,或者当用户最终输入内容时,输出将为“无”。

答案 2 :(得分:1)

我建议您使用正则表达式(test)来测试输入:

import re


def get_player_numbers():
    integer_set = None
    while not integer_set:
        number_csv = input("Enter your 6 numbers, separated by commas: ")
        if not re.match("([0-9]+,){5}[0-9]+", number_csv):
            print("Invalid input.")
        else:
            number_list = number_csv.split(",")
            integer_set = {int(number) for number in number_list}
    return integer_set


res = get_player_numbers()

print(res)

输出:

Enter your 6 numbers, separated by commas: 
Invalid input.
Enter your 6 numbers, separated by commas: 1,2
Invalid input.
Enter your 6 numbers, separated by commas: some-word
Invalid input.
Enter your 6 numbers, separated by commas: 1,2,3,4,5,6