0
votes

I'm currently working on a project and 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`
2
What kind of inputs you recieve(Names, Dates, etc...)? Which values are a valid strings in your program? Its will help us understand better your problemEitan Rosati
I'm trying to make an input that gives the keys and values to an empty dictionary, and I want the input to accept either int or string values.MajesTwix
The inputs receive data such as age, budget, name, etc...MajesTwix
if the format of the input is like this: name space number you can split the string the the input get. and get 2 diffirent variables and cast the number to intEitan Rosati
How does that work?MajesTwix

2 Answers

0
votes

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.

0
votes

An input in python will return a string. After storing you input in a variable you can than try to parse it into an int with the int() function if you need it but it will be stored as a string first.