2017-04-26 34 views
-2

如何向我的代碼添加一個循環,使其重複10次,然後提供最終的分數?這是到目前爲止,我已經試過代碼:如何向我的代碼添加循環,以便重複10次,然後提供最終分數?

import random 

randomNumber1 = random.randint (1,250) 
randomNumber2 = random.randint (1,250) 

def askQuestion(): 
    global randomNumber1 
    global randomNumber2 
    userAnswer = int(input("What is " + str(randomNumber1) + " + " + \ 
       str(randomNumber2) + " ?: ")) 
    return userAnswer 

def checkAnswer (userAnswer): 
    global randomNumber1 
    global randomNumber2 

    correctAnswer = randomNumber1 + randomNumber2 
    print() 
    if userAnswer == correctAnswer: 
     print("Congratulations!") 
    else: 
     print("It's wrong. The correct answer is", correctAnswer) 

def main(): 
    userAnswer = askQuestion() 
    checkAnswer(userAnswer) 

main() 
+0

即使你確實添加了一個循環,你的答案就根本不會被保存。 – Makoto

+0

閱讀[for loops](https://www.tutorialspoint.com/python/python_for_loop.htm) –

回答

0

該腳本會詢問10個問題,通過對ask_questions功能

import random 

def ask_questions(n): 
    for q in range(n): 
     n1 = random.randint(1, 250) 
     n2 = random.randint(1, 250) 

     user_answer = int(input('\nWhat is {} + {}? '.format(n1, n2))) 
     if user_answer == n1 + n2: 
      print("Congratulations!") 
     else: 
      print('It\'s wrong. The correct answer is {}'.format(n1 + n2)) 

def main(): 
    ask_questions(10) 

main() 
+0

但我如何重複10個問題。我的指示是「程序應該使用循環來顯示10個問題,然後給出最終分數。」 –

+0

另外,如何在開始時爲選項添加菜單?對於操作+ - x? –

0
import operator, random 

ops = {"+": lambda a, b: operator.add(a, b), 
     "-": lambda a, b: operator.sub(a, b), 
     "*": lambda a, b: operator.mul(a, b)} 

def main(): 
    score = 0 
    for q in range(10): 
     a, b = random.randint(1, 10), random.randint(1, 10) 
     op = random.choice(list(ops.keys())) 
     ans = ops[op](a, b) 

     print(a, op, b, "=", end = " ") 
     user_input = int(input()) 

     if user_input == ans: 
      score += 1 

    print("Scored:", score) 


main() 

兩個隨機數生成以及參數指定運營商。該程序循環10次,然後輸出最後的分數。

輸出

7 - 6 = 1 
9 + 4 = 13 
9 + 8 = 17 
1 - 1 = 0 
9 + 7 = 16 
5 + 7 = 12 
7 * 8 = 56 
8 - 8 = 0 
4 + 3 = 7 
9 + 6 = 15 
Scored: 10 
相關問題