2017-06-01 56 views
-2

我是一個完全新手,使用Python並從事多選題測驗,該測驗從文件中讀取問題並保留一個分數,然後寫入文件。添加驗證以便在測驗中回答給出錯誤的答案

一切都很完美,直到我添加驗證到用戶給出的答案。現在當我運行該程序時,它說我的答案不正確!

我做了什麼?

版本1,工程

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() 

版本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 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) 

幫助?

回答

3

在您的原始版本中,answer是一個字符串;在你的新版本中,它是一個int

如果您改變try身體是:

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

,那麼你仍然可以趕上ValueError但留下answer的字符串。

+0

好的,我現在看到了。如果讀取的文件以字符串的形式回答標題,那麼我如何驗證用戶輸入以匹配? – Jaskew

+0

我想我已經整理過了 - 感謝您的幫助 – Jaskew