2017-06-01 7 views
-2

私はPythonの完全な初心者であり、ファイルから質問を読み込んでファイルに書き込むスコアを保持する複数の選択肢のクイズに取り組んでいます。クイズで答えを検証すると間違った答えが返される

ユーザーからの回答に検証を追加するまで、すべてが完全に機能していました。今私はプログラムを実行すると、私の答えが間違っていると言います!

私は何をしましたか?私は今、間違った答え

def inputandoutput(): 
    questions_file = open_file("questions.txt", "r") 
    title = next_line(questions_file) 
    welcome(title) 
    score = 0 

    # get first block 
    category, question, answers, correct, explanation = next_block(questions_file) 
    while category: 
     # ask a question 
     print(category) 
     print(question) 
     for i in range(4): 
      print("\t", i + 1, "-", answers[i]) 


     # get answer and validate 
     while True: 
      try: 
       answer = int(input("What's your answer?: ")) 
       if answer in range (1,5): 
        break 
      except ValueError: 
       print ("That's not a number") 
      else: 
       print ("the number needs to be between 1 and 4, try again ") 


     # check answer 
     if answer == correct: 
      print("\nRight!", end=" ") 
      score += 1 
     else: 
      print("\nWrong.", end=" ") 
     print(explanation) 
     print("Score:", score, "\n\n") 

     # get next block 
     category, question, answers, correct, explanation = next_block(questions_file) 

ヘルプを持っていると言い、バージョン2

def inputandoutput(): 
    questions_file = open_file("questions.txt", "r") 
    title = next_line(questions_file) 
    welcome(title) 
    score = 0 

    # get first block 
    category, question, answers, correct, explanation = next_block(questions_file) 
    while category: 
     # ask a question 
     print(category) 
     print(question) 
     for i in range(4): 
      print("\t", i + 1, "-", answers[i]) 

     # get answer 
     answer = input("What's your answer?: ") 

     # check answer 
     if answer == correct: 
      print("\nRight!", end=" ") 
      score += 1 
     else: 
      print("\nWrong.", end=" ") 
     print(explanation) 
     print("Score:", score, "\n\n") 

     # get next block 
     category, question, answers, correct, explanation = next_block(questions_file) 


    questions_file.close() 

を作品

バージョン1?

答えて

3

元のバージョンでは、answerは文字列でした。新しいバージョンでは、intです。

あなたがあることをごtryの体を変更した場合:

answer = input("What's your answer?: ") 
if int(answer) in range (1,5): 

その後、あなたはまだValueErrorをキャッチしますがanswer文字列を残すことができます。

+0

はいはい私は今それを見る。読み込まれたファイルに文字列としての答えの見出しがある場合、それが一致するようにユーザーエントリを検証するにはどうすればよいですか? – Jaskew

+0

私は今それをソートしたと思う - あなたの助けに感謝 – Jaskew

関連する問題