8

以下のコードは、10 進数(例: 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!")

int()orを使用float()せず、単に使用する場合:

how_much=next

として入力しても、「else」に移動します49.8

4

5 に答える 5

12

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?
于 2012-08-18T17:57:35.103 に答える
5

int() 整数のように見える文字列に対してのみ機能します。float のように見える文字列では失敗します。float()代わりに使用してください。

于 2012-08-18T17:43:21.963 に答える
2

整数 (int略して) は、0、1、2、3 ... で数えられる数字であり、それらの負の対応する数字 ... -3、-2、-1 は小数部分のないものです。

したがって、小数点を導入すると、実際には整数を扱っていません。あなたは有理数を扱っています。Python の float またはdecimal型は、これらの数値を表現または概算したいものです。

これを自動的に行う言語 (Php) に慣れているかもしれません。ただし、Python ではコードを暗黙的ではなく明示的にすることを明示的に優先します。

于 2012-08-18T17:49:28.300 に答える
1

プログラムで小数点を処理できるように、 int()の代わりにfloat()を使用します。また、組み込みの Python 関数である next() を使用しないでください。next

また、投稿されたコードが欠落import sysしており、の定義がありませんdead

于 2012-08-18T17:46:09.047 に答える