Search code examples
pythonpython-3.xuser-input

Can I make my user input accept either int or string values?


I was wondering if it was possible to make my input accept either int or str values. This is the code so far:

NumOfKeys = int(input("How many keys would you like to add:"))

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`

Solution

  • Try this:

    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)
    

    Hope is what you intend. Let me know if its ok. If the key contain both number and characters is must be a string.