user18982401
user18982401

Reputation:

find out if input is a float, if not, append it to a dictionary

my_dictionary = {"City":[], "Number":[]}
while True:
    city = input("City: ")
    if city == "":
        break
    try:
        while int(city) == True:
            print("You entered a number instead of a city name")
            city = input("Input city name again: ")
    except ValueError:
        my_dictionary["City"].append(city)
    number = input("Number: ")
    if number == "":
        break
    **try:
        if int(number) == True and int(number) > 0:
            my_dictionary["Number"].append(number)
    except ValueError:
        print("You entered a float instead of an integer")
        number = input("Input an integer: ")
print(my_dictionary)**

Hi, I have a little problem with the highlighted part. I want to make the input so that it is restricted to integers only.

Upvotes: 0

Views: 64

Answers (3)

Jhanzaib Humayun
Jhanzaib Humayun

Reputation: 1183

Use number.isnumeric() to check if your number is an int. You can change your try and except block to this:

if number.lstrip("-").isnumeric() and int(number) > 0:
    my_dictionary["Number"].append(number)
else:
    print("You entered a float instead of an integer")
    number = input("Input an integer: ")

Upvotes: 0

Quint
Quint

Reputation: 590

Try using type(). It can be used to check for any kind of data type. For example type(list), type(object), type(int), ect...

i = 1.000000000001
if type(i) is float:
 print(type(i))

Upvotes: 0

AlexApps99
AlexApps99

Reputation: 3584

You're using int(<number>) == True to check if it's an integer, but the int() function will only ever return integers, or raise exceptions, so that's not the right way to do it.

If you want to check if something can be converted to an int, you can do

try:
  foo = int(foo)
  # foo can be converted to an int, so do code here
except ValueError:
  # foo cannot be converted to an int, so do code here

Upvotes: 1

Related Questions