2017-11-25 65 views
0

我正在爲學校編寫測驗代碼。代碼遍歷一個文本文件並從中加載問題和答案。用戶將選擇難度來進行測驗。答案選項的數量取決於難度。我在文本文件中用逗號分隔了每個問題和可能的答案。如何測試python

from random import shuffle 

file = open("maths.txt" , "r") 
for line in file: 
    question = line.split(",") 
    print(question[0]) 
    if difficulty in ("e", "E"): 
     options = (question[1], question[2]) 

    if difficulty in ("m", "M"): 
     options = (question[1], question[2], question[3]) 

    if difficulty in("h", "H"): 
     options = (question[1], question[2], question[3], question[4]) 

    options = list(options) 
    shuffle(options) 
    print(options) 

    answer = input("Please enter answer: ") 

    if answer in (question[1]): 
     print("Correct!") 
    else: 
     print("incorrect") 
    file.close() 

這是文本文件的行會是什麼樣子? 問題1.什麼是4 + 5,9,10,20,11

第一個選項(問題[1] )將永遠是正確的答案,因此我想洗牌的選項。使用此代碼,選項將用方括號,換行符和引號輸出。有誰知道我可以如何去除這些?我試圖使用:line.split(",").strip()然而,這似乎什麼也沒做。謝謝

+1

預期輸出是什麼?如果在(「m」,「M」「)中遇到困難,則更新這個':' – bhansa

+0

'line.split(」,「)。strip()'應該引發一個錯誤,而不是什麼都不做。'maths .txt'看起來像? – 2017-11-25 17:54:30

+0

請在代碼塊中添加該問題 – 2017-11-25 17:56:40

回答

3

問題是您正在嘗試打印list對象。相反,你應該打印每個選項。你可能會得到更好的打印周圍的一些格式:

for option_num, option in enumerate(options): 
    print("{} - {}").format(option_num, option) 

請閱讀enumerateformat瞭解這裏

1
for option in options: 
    print(option) 
+0

在那裏需要'.strip()' – 2017-11-25 18:06:04

+0

@Blurp我相信上面提到的逗號和括號實際上是Python打印列表的方式,這就是爲什麼答案比看起來簡單得多。地帶需要 –

+0

最後一個選項是否會有需要刪除的換行符?選項可能有前導和尾隨空白。這就是爲什麼我建議使用'csv'模塊來讀取上面的文件。 – 2017-11-25 20:50:35

1

究竟發生了什麼,從字符串中刪除字符,請使用.rstrip("put text to remove here")從右側刪除字符結束字符串和.lstrip("text to remove")刪除字符串左側的字符。

2

這樣的事情?

from random import shuffle 
def maths_questions(): 
    file = open("maths.txt" , "r") 
    for line in file: 
    question = line.strip().split(",") # every line in file contains newline. add str.strip() to remove it 
    print(question[0]) 

    if difficulty in ("e","E"): 
     options = [question[1],question[2]] 
    elif difficulty in ("m","M"): 
     options = [question[1],question[2],question[3]] 
    elif difficulty in("h","H"): 
     options = [question[1],question[2],question[3],question[4]] 
    # why to create tuple and then convert to list? create list directly 

    shuffle(options) #shuffle list 
    print("Options: ", ", ".join(options)) # will print "Options: opt1, opt2, opt3" for M difficulty 

    answer=input("Please enter answer: ") 

    if answer in (question[1]): 
      print("Correct!") 
    else: 
     print("Incorrect, please try again...") 
    file.close() 

Python docs

str.join(iterable)

返回一個字符串,它是在可迭代的字符串的連接。如果迭代中有任何非字符串值(包括字節對象),則會引發TypeError。元素之間的分隔符是提供此方法的字符串。