How to convert float string to integer in python 3

I'm new to all encoding ... and so. Just trying to write a simple number guessing game, but also checking input. So only integers are accepted as input. I figured out how to weed out the alphabetic characters, so I can convert the numbers to an integer. I am having problems when I add a floating point number. I cannot get it to convert a floating point number to an integer. Any help is appreciated. As I said, I'm on the 3rd day of this encoding, so try to understand my little knowledge. Thanks in advance.

Here is a 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 is the error I get 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'
+4
3

int() float, . , float, int :

int(float(userGuess))
+4

-, float ? 4.7 , 4? 5? , ? 4.7 ( )? ...?


-, , , . userGuess.isalpha() , . , - , , "Hello!" , .

, , int try/except , :

def validateInput():
    while True:
        global userGuess
        userGuess = input("Please enter a number from 1 to 100. ")
        try:
            userGuess = int(userGuess)
            print(type(userGuess), "after int succeeeded")
            break
        except ValueError:
            print("Please enter whole numbers only, no words.")
            print(type(userGuess), "after int failed")
    return userGuess

, , , , isalpha except.

, float, , - try, float(userGuess) - except. , , int(userGuess) int(float(userGuess)).

try. , , -23 178? , 1 100.

, , , . , , .

0

Do not use isalphato display the screen. EAFP - Convert and handle this exception. Or ValueError- this is exactly what you want, so that you can handle it, and ask the user to correct their input. Or for some odd reason, you want to quietly adjust your input from "4.3" to "4".

def validateInput():
    while True:
        global userGuess
        userGuess = input("Please enter a number from 1 to 100. ")
        try:
            int(userGuess)
            return userGuess # you shouldn't really keep this string...
        except ValueError as e:
            print("Please enter whole numbers only, no words.")
0
source

All Articles