2017-11-25 30 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。元素之间的分隔符是提供此方法的字符串。