![](/img/trans.png)
[英]I created a guessing game and I can't understand why my -= command function doesn't work
[英]i dont understand why my “if” command don't work as it should
import random
cde = random.random()
print(cde)
tst = input("Whats the code?\n")
if tst == cde:
print("Welcome")
else:
print("Imposter!!!")
當我運行此代碼並輸入“ cde”后,它一直在說冒名頂替,但應該說“歡迎”
random返回一個與用戶輸入的string
進行比較的float
-它們將永遠不相等...
您可以嘗試:
import random
cde = str(round(random.random(), 3))
print(cde)
tst = input("Whats the code?\n") # <- python3
# tst = raw_input("Whats the code?\n") # <- python2
if tst == cde:
print("Welcome")
else:
print("Imposter!!!")
並且為了避免舍入效果,您可以考慮對random.random()
的結果進行舍入。
請注意,根據所使用的python版本,獲得用戶輸入的不同方式。
這是因為您沒有強制轉換,所以在這種情況下,您正在將字符串與long進行比較。 簡單修復(僅適用於python 2):
import random
cde = random.random()
print(cde)
tst = input("Whats the code?\n")
if long(tst) == long(cde):
print("Welcome")
else:
print("Imposter!!!")
也許它將以這種方式工作:str(tst)== str(cde)
問題取決於您的Python版本:
對於Python 2.x,問題在於
print(cde)
僅輸出cde
的前12個十進制數字。 因此,如果您只輸入一次tst
,在大多數情況下,由於還有更多數字,它不會匹配,您只是看不到。 您可以在交互式Python會話中對此進行測試:
>>> import random >>> a = random.random() >>> a 0.10981364144091466 >>> print a 0.109813641441
對於Python 3.x,問題在於
cde = random.random()
cde
的類型為builtins.float
,而帶有
tst = input("Whats the code?\\n")
tst
的類型為builtins.str
。 因此比較這兩個總是返回False
。
另一個問題是比較浮點數是否等於( ==
)並不總是可靠的。 打印的十進制值與內部二進制值不完全匹配。
我建議生成一個隨機整數並將輸入也轉換為整數:
import random
cde = int(random.random() * 1000000)
print(cde)
tst = int(input("Whats the code?\n"))
if tst == cde:
print("Welcome")
else:
print("Imposter!!!")
這段代碼適用於Python 2.x和3.x,但是對於Python 2.x,最好使用raw_input()
而不是input()
。 您可以只使用str()
而不是int()
,但是使用整數而不是強制轉換為str
的好處是您還可以輕松地進行數值較小/較大的比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.