2016-07-15 6 views
0

私はPythonを学んでいますが、練習の1つは単純な乗算ゲームを作ることです。これは正しく答えるたびに実行されます。私はゲームの仕事をしましたが、試行回数を数えることで、正しく答えるとループ/機能が終了するようにしたいと思います。私の問題は、コードの終わりに関数が再び呼び出され、試行回数が当初設定したものに戻ってしまうことです。私はあなたがループして終わりでmultiplication_game()のお電話を囲むことができ、各ループをカウントし、試行の指定された数?:ループの数を計算するPython

def multiplication_game(): 
    num1 = random.randrange(1,12) 
    num2 = random.randrange(1,12) 

    answer = num1 * num2 

    print('how much is %d times %d?' %(num1,num2)) 

    attempt = int(input(": ")) 

    while attempt != answer: 
     print("not correct") 

     attempt = int(input("try again: ")) 
    if attempt == answer: 
     print("Correct!") 

multiplication_game() 
+0

コードをフォーマットすることができます。インデントが正しくない –

+1

あなたのコードから、再帰的に呼び出すかどうかは不明です。コードをフォーマットできますか? – nagyben

+0

3つの可能性:グローバルカウンタ変数を追加します。関数にパラメータとして現在のターン番号を渡すか、(望ましい)再帰を別のループに変更します。 –

答えて

1

で終了できるように、どのように私は、このことについて行くことができます。たとえば、

for i in range(5): 
    multiplication_game() 

とすると、プログラムが終了する前に5回ゲームをプレイできます。あなたが実際にどのラウンドにいるのかを数えたい場合は、追跡を続ける変数を作成し、ゲームが終了するたびにその変数をインクリメントします(これを関数定義の中に入れます)。

1

私はそれのうちforループとbreakを使用します。

attempt = int(input(": ")) 

for count in range(3): 
    if attempt == answer: 
     print("correct") 
     break 

    print("not correct") 
    attempt = int(input("try again: ")) 
else: 
    print("you did not guess the number") 

あなたはそれがどのように動作するかの詳細が必要な場合はここでelse clauses for for loops上のいくつかのドキュメントです。

0
NB_MAX = 10 #Your max try 
def multiplication_game(): 
    num1 = random.randrange(1,12) 
    num2 = random.randrange(1,12) 

    answer = num1 * num2 
    i = 0 
    while i < NB_MAX: 
      print('how much is %d times %d?' %(num1,num2)) 

      attempt = int(input(": ")) 

      while attempt != answer: 
       print("not correct") 

      attempt = int(input("try again: ")) 
      if attempt == answer: 
       print("Correct!") 
      i += 1 

multiplication_game()