Skip to main content
 首页 » 编程设计

python之Python 中的 input() 函数可以动态检测输入的数据类型吗

2024年11月24日8me-sa

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

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

我只想让这个小 ART 动态运行。 (我希望 input() 函数动态检测输入的 data-type 并将其分配给变量?plsss)

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 并分配它到变量连同输入本身。

但实际发生的是,它总是将输入的数据类型指定为"< class 'str' >"; ( <和> 之前没有空格,) 导致程序进入死循环,这让我很头疼;我的愚蠢。

请您参考如下方法:

因此,在 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)