我可以让我的用户输入接受 int 或 string 值吗? (Python)

时间:2021-03-21 11:22:06

标签: python-3.x user-input

我目前正在处理一个项目,想知道是否可以让我的输入接受 int 或 str 值。这是到目前为止的代码:

`NumOfKeys = int(input("你想添加多少个键:"))

    for i in range(NumOfKeys):
        TypeInput = input("Is your key:value a string or int value? (str/int/both)")
        if TypeInput.lower() == "str":
            KeyInput = input("Please input your key")
            ValueInput = input("Please input your value")
        elif TypeInput.lower() == "int":
            KeyInput = int(input("Please input your key"))
            ValueInput = int(input("Please input your value"))
        elif TypeInput.lower() == "both":
            # I want the key to be either str or int
            # I want the value to be either str or int`

2 个答案:

答案 0 :(得分:0)

python 中的输入将返回一个字符串。 将输入存储在变量中后,如果需要,您可以尝试使用 int() 函数将其解析为 int,但它会首先存储为字符串。

答案 1 :(得分:0)

试试这个:

NumOfKeys = int(input("How many keys would you like to add:"))
for i in range(NumOfKeys):
    KeyInput = input("Please insert your key")
    if KeyInput.isdigit():
        TypeInput = int(KeyInput)
    ValueInput =input("Please input your value")
    if ValueInput.isdigit():
        ValueInput = int(ValueInput)

希望就是你想要的。让我知道它是否可以。 如果key同时包含数字和字符,则必须是字符串。

相关问题