日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python int函数详解,python int()函数

發布時間:2024/9/19 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。