2017-04-09 6 views
0

私は現在Pythonを学んでいて、たくさんのことを知っているわけではないので、ここで私を助けてくれる経験豊富な人が必要です。この迷惑なエラーメッセージを回避するにはどうすればよいですか? (Python 3.6.1)

usernum = input('Enter a number, Ill determine if its pos, neg, OR Zero.') 
if usernum < 0: 
    print("Your number is negative.") 
if usernum > 0: 
    print("Your number is positive.") 
if usernum == 0: 
    print("Your number is zero.") 

エラーはこれです:

コードはこれです

usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.')) 

あなたはそれを持っていたようにあなたの最初の行

Traceback (most recent call last): 
    File "C:\Users\Admin\Documents\Test.py", line 2, in <module> 
    if usernum < 0: 
TypeError: '<' not supported between instances of 'str' and 'int' 
+0

「usernum」は文字列です。 'int(usernum = input( '数字を入力すると、そのpos、neg、ORがゼロかどうかを判断する)'))' –

+0

http://stackoverflow.com/questions/379906/parse-string-to -float-or-int - 浮動小数点数も忘れないでください。 – stdunbar

答えて

0

変更、usernum文字列ですの値です。input()は常にPytの文字列を返しますあなたは整数と比較しようとしていました。それで最初に整数に変換してください。私はint()タイプキャストでinputコールを囲んでこれを行いました。

ユーザーが整数以外を入力すると、エラーが発生することに注意してください。これは例外処理によって処理される可能性がありますが、これはおそらく今あなたの外にあります。

1

試してください:あなたはそれがint(...)を経ることによって、その文字列に整数を作成する必要があるので

usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.')) 
if usernum < 0: 
    print("Your number is negative.") 
if usernum > 0: 
    print("Your number is positive.") 
if usernum == 0: 
    print("Your number is zero.") 

input(...)は、文字列を作成します。また、私は、もしにあなたがIFSだスイッチングのelifと他のことをお勧めしたい:

usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.')) 
if usernum < 0: 
    print("Your number is negative.") 
elif usernum > 0: 
    print("Your number is positive.") 
else: 
    print("Your number is zero.") 

をそれは大したことではないのですが、この方法は、あなたは、あなたが実際に必要なコードを実行しています。したがって、usernumが0より小さい場合、次の節は評価されません。最後に、ユーザー入力のエラー修正を追加することを検討できます。

usernum = None 
while usernum is None: 
    try: 
     usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.')) 
    except ValueError as ex: 
     print("You didn't enter an integer. Please try again.") 
if usernum < 0: 
    print("Your number is negative.") 
if usernum > 0: 
    print("Your number is positive.") 
if usernum == 0: 
    print("Your number is zero.") 
+0

はい、うまくいくと思います。ありがとうございます。 –

関連する問題