How to convert a float string to an integer in python 3

corey picture corey · Nov 20, 2014 · Viewed 19.4k times · Source

I'm new to the whole coding thing...so here goes. Just trying to write a simple number guess game, but also do input validation. So that only integers are accepted as input. I've figured out how to weed out alphabetic characters, so I can convert the numbers into an integer. I'm having trouble when I put in a float number. I can't get it to convert the float number over to an integer. Any help is appreciated. As I said I'm on about day 3 of this coding thing so try to be understanding of my little knowledge. Thanks in advance.

Here's the function from my main program.

def validateInput():
    while True:
        global userGuess
        userGuess = input("Please enter a number from 1 to 100. ")
        if userGuess.isalpha() == False:
            userGuess = int(userGuess)
            print(type(userGuess), "at 'isalpha() == False'")
            break
        elif userGuess.isalpha() == True:
            print("Please enter whole numbers only, no words.")
            print(type(userGuess), "at 'isalpha() == True'")
    return userGuess

Here's the error I'm getting if I use 4.3 (or any float) as input.

Traceback (most recent call last):
File "C:\\*******.py\line 58, in <module>
validateInput()
File "C:\\*******.py\line 28, in validateInput
userGuess = int(userGuess)
ValueError: invalid literal for int() with base 10: '4.3'

Answer

Irshad Bhat picture Irshad Bhat · Nov 20, 2014

Actually int() function expects an integer string or a float, but not a float string. If a float string is given you need to convert it to float first then to int as:

int(float(userGuess))