我是 python 的初學者,我正在終端中撰寫乘法器挑戰。我需要呼叫函式 randint 來詢問有關乘法表的隨機問題。問題是在我的迭代回圈中,列印的數字總是相同的,它會生成一個亂數字,但在每個回圈中都是相同的,這對我來說是個大問題,這是我的代碼
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
multi=(randint(1,10))
for nombreQuestions in range(nombreQuestions):
question=str(choixTable) " x " str(multi) " = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
非常感謝
uj5u.com熱心網友回復:
您只randint在第 6 行開始呼叫,在進入回圈之前設定一次這意味著每個迭代都使用相同的值要解決此問題,您需要multi在回圈內部(而不是外部)設定
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
for nombreQuestions in range(nombreQuestions):
multi=(randint(1,10)) # multi is now set every loop
question=str(choixTable) " x " str(multi) " = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
uj5u.com熱心網友回復:
添加multi=...回圈,使其在每個回圈迭代中執行。
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
for nombreQuestions in range(nombreQuestions):
multi=(randint(1,10))
question=str(choixTable) " x " str(multi) " = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
uj5u.com熱心網友回復:
如果您想每次都生成一個亂數,那么您需要在回圈內部而不是外部呼叫 randint() 方法。
這意味著這條線multi=(randint(1,10))應該在 for 回圈中使用。
像這樣,
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
for nombreQuestions in range(nombreQuestions):
multi = randint(1,10)
question=str(choixTable) " x " str(multi) " = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
還有一件事,在 import 陳述句中指定函式的名稱是更可取的,即,而不是像from random import *use一樣匯入from random import randint
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/512365.html
上一篇:無法解決這個for回圈
