python int函数详解,python 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!")
If I dont use int() or float() and just use:
how_much=next
then it moves to "else" even if I give the input as 49.8.
解決方案
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
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.
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函数详解,python int()函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 农村创业的好项目 打工不如自己做一番事业
- 下一篇: 惠州德赛电池是苹果原装电池吗 德赛苹果电