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

标签 python python-3.x input dynamic integer

所以我使用 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)

关于python - Python 中的 input() 函数可以动态检测输入的数据类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57013667/

相关文章:

python - OpenCV 3.1 绘制轮廓 '(-215) npoints > 0'

python - 当程序启动时运行Python脚本

python - CommandError: Elasticsearch 中未命名任何模型或应用

python - 盘中数据的每日高/低

python - 我可以在 matplotlib 中生成没有数据集而只有相关值(中位数、四分位数等)的箱线图吗?

python - 根据位置多次打印字符串元素

python tkinter entry 命令无法转换为 int

javascript - 根据用户输入扩展数量 Html 输入宽度?

c# - 使用c#保持隐藏的输入框名称相同

python - __getitem__ 空元组参数