爲什麼我不是得到準確的結果,當我一個比較用b,其中b值是1之間什麼9?蟒蛇2號相比沒有發生
#!/usr/bin/python
b=raw_input("Enter value of b:\n")
a = 10
if a>b:
print("a is larger")
else:
print("b is larger")
爲什麼我不是得到準確的結果,當我一個比較用b,其中b值是1之間什麼9?蟒蛇2號相比沒有發生
#!/usr/bin/python
b=raw_input("Enter value of b:\n")
a = 10
if a>b:
print("a is larger")
else:
print("b is larger")
的raw_input
命令返回一個字符串。在比較之前,你應該把'b'作爲一個整數。
#!/usr/bin/python
b=raw_input("Enter value of b:\n")
b=int(b)
a = 10
if a>b:
print("a is larger")
else:
print("b is larger")
B = INT(的raw_input( 「輸入B的值:\ n」))這個固定的問題,謝謝。 –
這是因爲raw_input將輸入視爲字符串。你需要的是
B =輸入( 「輸入B的值:\ n」)
您與整數比較字符串。你需要投raw_input
與int
。
a = 10
b = raw_input('Enter value of b:')
if (b.isdigit()):
b = int(b)
if a>b:
print("a is larger")
else:
print("b is larger")
else:
print("b is not a number that can be compared with a")
Python文檔:https://docs.python.org/2/library/functions.html#raw_input
的raw_input([提示])
如果提示參數存在時,它被寫入到標準輸出沒有尾隨換行符。然後,該函數讀取從輸入的線,將其轉換成字符串(剝離的後換行),並返回。讀取EOF時,引發EOFError。
NOTE
:您將需要添加更好的錯誤處理,因爲在您的代碼中,用戶可以輸入非數字數字,並且會失敗。
在這裏,您與integer
爲raw_input
在python2.x
比較string
和input()
在python3.x
總是返回string
。所以,你必須與int
類型比較之前,將其強制轉換爲int
:
#!/usr/bin/python
b=int(raw_input("Enter value of b:\n"))
a = 10
if a>b:
print("a is larger")
else:
print("b is larger")
注意,如果== B檢查仍然會打印出「b爲大」 – Kai
因爲'B'是一個字符串,而不是數字。 –
你甚至嘗試看看是什麼'了'和'B'? –