【问题标题】:Can the input() function in Python dynamically detect the input's data type?Python中的input()函数可以动态检测输入的数据类型吗?
【发布时间】:2019-11-22 14:48:30
【问题描述】:

所以我正在使用 Python 3.7 制作控制台应用程序;这在很大程度上取决于输入 (wowz)。

应用程序的功能是在两个整数变量的值之间“交换”。这不是问题所在,问题是当我尝试通过使用几个“if 语句”检查输入的 data-type 来验证用户的输入时,无论是什么使用“input()”函数的用户输入;输入的 data-type 将始终定义为 ""

我只是想让这小块 ART 动态运行。 (我希望 input() 函数动态检测输入的数据类型并将其分配给变量?请)

P.S.:我什么都没尝试,因为我发现的都是无用的;我猜。 (告诉我使用 int() 函数,例如:{

# Works just fine when input is fully composed of integral numbers. 
a = int(input("Enter an integer as a value for A: "))

} (编辑以下第 5 行)

我不想使用 int() 函数;因为它会导致一堆问题,如果用户的输入是一个不完全由整数组成的字符串。 (值错误)

def swap(x, y):
    return y, x
aValid = 1
bValid = 1
a = input("Enter an integer as a value for A: ")
if (str(type(a)) != "<class 'int'>"):
    print("Please take us seriously, we're watching you.\n")
    aValid = 0
    while (aValid == 0):
        a = input("Enter an integer as a  value for A: ")
        if str(type(a)) != "<class 'int'>":
            print("Please take us seriously, we're watching you.\n")
            aValid = 0
        else:
            aValid = 1

# ! To be worked on:

b = input("Now, Please enter the value for B: ")
print("A = " , a)
print ("B = ", b)

a, b = swap(a, b)

print("Now:\nA = ", a)
print("B = ", b)

我希望 Python 3.7 (32bit) 中的 input() 函数能够动态检测输入的 data-type 并分配它到变量以及输入本身。

但实际发生的是它总是将输入的 data-type 分配为 ""; (之前没有空格,)导致程序进入无限循环,这让我很头疼;我的愚蠢。

【问题讨论】:

  • 在 Python 2.7 中,input used 这样做; raw_input 返回一个字符串,input() 等价于 eval(raw_input())。正确的做法是在 try 语句中简单地调用 a = int(a) 并在无法将值解析为整数时捕获可能的 ValueError

标签: python python-3.x input dynamic integer


【解决方案1】:

因此,在 python 2 中,input() 函数将检测用户输入的类型。但是python3中的input()指的是python 2中的raw_input()。为了动态检测类型,可以使用ast,具体是ast.literal_eval

您可以编写自己的输入函数,如下所示:

import ast

def input_detect(s):
    return ast.literal_eval(input(s))

然后您的代码将如下所示:

import ast

def input_detect(s):
    return ast.literal_eval(input(s))

def swap(x, y):
    return y, x
aValid = 1
bValid = 1
a = input_detect("Enter an integer as a value for A: ")
if (str(type(a)) != "<class 'int'>"):
    print("Please take us seriously, we're watching you.\n")
    aValid = 0
    while (aValid == 0):
        a = input_detect("Enter an integer as a  value for A: ")
        if str(type(a)) != "<class 'int'>":
            print("Please take us seriously, we're watching you.\n")
            aValid = 0
        else:
            aValid = 1

# ! To be worked on:

b = input_detect("Now, Please enter the value for B: ")
print("A = " , a)
print ("B = ", b)

a, b = swap(a, b)

print("Now:\nA = ", a)
print("B = ", b)

【讨论】:

    【解决方案2】:

    也许while 循环和try/except 是捕获和验证输入的更可靠方法。此外,我们避免使用eval/literal_eval,这可能会影响安全性。

    例如:

    
    a = None
    b = None
    
    while a is None: 
        try: 
            a = int(input("Enter an integer as a value for A: "))
        except ValueError:
            continue
    
    while b is None:
        try:
            b = int(input("Enter an integer as a value for B: "))
        except ValueError:
            continue
    
    print("A is {}".format(a))
    print("B is {}".format(b))
    
    a, b = b, a
    
    print("A is now {}".format(a))
    print("B is now {}".format(b))
    

    这样你的代码更健壮,因为你不必考虑不同的类型检查,如果你要编写一个验证函数,比如validate_user_input,你可以添加一大堆检查来引发ValueError 他们失败了,你的代码几乎不会改变。

    【讨论】:

      【解决方案3】:

      在 python 3 中,输入函数是 raw_input。这意味着它将始终是一个字符串。但是,如果您希望它采用其值的格式,您应该使用:ast.literal_eval() 函数。 注意:不要使用 eval() 函数!不安全,因为我可以从计算机中删除文件。

      另外:不要使用交换函数,它是非 Python 的。 x, y = y, x

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-07
        • 2017-03-28
        • 1970-01-01
        • 2020-07-02
        • 1970-01-01
        • 1970-01-01
        • 2015-04-26
        相关资源
        最近更新 更多