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

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

validateInput()

File "C:\\*******.py\line 28, in validateInput

userGuess = int(userGuess)

ValueError: invalid literal for int() with base 10: '4.3'

解决方案

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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值