如何在Python 3中将浮点字符串转换为整数

cor*_*rey 11 python data-conversion python-3.x floating-point-conversion

我是整个编码的新手...所以这里.只是想写一个简单的猜数游戏,还要做输入验证.因此只接受整数作为输入.我已经弄清楚如何清除字母字符,所以我可以将数字转换为整数.当我输入一个浮点数时,我遇到了麻烦.我无法让它将浮点数转换为整数.任何帮助表示赞赏.正如我所说,我正在谈论这个编码的第3天,所以试着理解我的小知识.提前致谢.

这是我的主程序的功能.

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
Run Code Online (Sandbox Code Playgroud)

如果我使用4.3(或任何浮点数)作为输入,这是我得到的错误.

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'
Run Code Online (Sandbox Code Playgroud)

Irs*_*hat 8

实际上int()函数需要整数字符串浮点数,但不是浮点字符串.如果给出了一个浮点字符串,则需要float先将其转换int为:

int(float(userGuess))
Run Code Online (Sandbox Code Playgroud)