python int()函数

Shu*_*wal 8 python int

如果将小数(例如49.9)发送到next变量,则下面的代码显示错误.你能告诉我为什么吗?为什么int()将它转换为整数?

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

如果我不使用int()float()只是使用:

how_much=next
Run Code Online (Sandbox Code Playgroud)

然后它转移到"其他",即使我输入为49.8.

jdi*_*jdi 12

正如其他答案所提到的,int如果字符串输入不能转换为int(例如float或字符),则操作将崩溃.您可以做的是使用一个小帮助方法来尝试为您解释字符串:

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

所以它需要一个字符串并尝试将其转换为int,然后浮点数,否则返回字符串.这更像是查看可转换类型的一般示例.如果您的值从该函数仍然是一个字符串返回,那么您将需要向用户报告并请求新输入,这将是一个错误.

None如果它既不浮动也不是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?
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 5

int() 适用于看起来像整数的字符串;对于看起来像浮点数的字符串,它将失败。使用float()代替。

  • 因为它不能解释为整数。 (3认同)