python int()函数 [英] python int( ) function
问题描述
如果小数(例如49.9)被发送到 next
变量,则下面的代码显示错误。你能告诉我为什么吗?为什么 int()
将其转换为整数?
The code below shows error if a decimal (eg. 49.9) is sent to next
variable. Can you please tell me why? Why does int()
converts it into an integer?
next=raw_input("> ")
how_much = int(next)
if how_much < 50:
print"Nice, you're not greedy, you win"
exit(0)
else:
dead("You greedy bastard!")
如果我不使用 int()
或 float()
并且只需使用:
If I dont use int()
or float()
and just use:
how_much=next
然后它移动到else即使我输入 49.8
。
then it moves to "else" even if I give the input as 49.8
.
推荐答案
正如其他答案所提到的, int
操作将如果字符串输入不可转换为int(例如float或字符),则会崩溃。您可以做的是使用一个小帮助方法来尝试为您解释字符串:
As the other answers have mentioned, the int
operation will crash if the string input is not convertible to an int (such as a float or characters). What you can do is use a little helper method to try and interpret the string for you:
def interpret_string(s):
if not isinstance(s, basestring):
return str(s)
if s.isdigit():
return int(s)
try:
return float(s)
except ValueError:
return s
所以它将获取一个字符串并尝试将其转换为int,然后浮动,否则返回字符串。这更像是查看可转换类型的一般示例。如果您的值从该函数仍然是一个字符串返回将是一个错误,然后您需要向用户报告并请求新输入。
So it will take a string and try to convert it to int, then float, and otherwise return string. This is more just a general example of looking at the convertible types. It would be an error for your value to come back out of that function still being a string, which you would then want to report to the user and ask for new input.
如果它既不是浮点也不是int,也许是一个返回无
的变体:
Maybe a variation that returns None
if its neither float nor int:
def interpret_string(s):
if not isinstance(s, basestring):
return None
if s.isdigit():
return int(s)
try:
return float(s)
except ValueError:
return None
val=raw_input("> ")
how_much=interpret_string(val)
if how_much is None:
# ask for more input? Error?
这篇关于python int()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!