不处理循环

时间:2017-04-26 15:37:47

标签: python

我正在尝试学习python并尝试创建一个简单的应用程序,我将其设置为从文本文件中读取行。第一行是问题,第二行是答案。现在,我能够阅读问题和答案。但是我将用户回答与实际答案进行比较的部分,即使输入的答案是正确的,它也不会在循环中执行操作。 我的代码:

//background.js
chrome.browserAction.onClicked.addListener(function () {  //when the extension's icon is pressed
  chrome.tabs.query({},function(tabs) {  // get all tabs
    for (var i = tabs.length; i--;){     // loop through all tabs
      chrome.tabs.executeScript(tabs[i].id,{code:  //execute this code in each tab
        "if (!document.querySelector(\".someClass\")) close();"});
       // ^ if no element is found with the selected class, close the tab
    }
  });
});

我真的很感激任何指导。 我的q.txt文件:

def populate():

print("**************************************************************************************************************")
f=open("d:\\q.txt")
questionList=[]

b = 1
score=0
start=0

for line in f.read().split("\n"):
    questionList.append(line)


while b<len(questionList):
    a = questionList[start]
    print(a)
    userinput=input("input user")
    answer=questionList[b]
    b = b + 2
    print(answer)
    if userinput==answer:
        score =score+1
        print(score)
    else:
        break
    start += 2

1 个答案:

答案 0 :(得分:1)

您的代码是:

  • 总是问同样的问题:questionList[start]
  • 丢掉every
  • 的价值
  • 用什么都不替换答案中的每个空格,所以&#34;系统软件&#34;成为&#34; SystemSoftware&#34;
  • 无法考虑案例:需要在.lower()userinput上使用answer

这是一个更加pythonic的实现:

#!/usr/bin/env python3

from itertools import islice


# Read in every line and then put alternating lines together in
# a list like this [ (q, a), (q, a), ... ]
def get_questions(filename):
    with open(filename) as f:
        lines = [line.strip() for line in f]
    number_of_lines = len(lines)
    if number_of_lines == 0:
        raise ValueError('No questions in {}'.format(filename))
    if number_of_lines % 2 != 0:
        raise ValueError('Missing answer for last question in {}'.filename)
    return list(zip(islice(lines, 0, None, 2), islice(lines, 1, None, 2)))


def quiz(questions):
    score = 0
    for question, answer in questions:
        user_answer = input('\n{}\n> '.format(question))
        if user_answer.lower() == answer.lower():
            print('Correct')
            score += 1
        else:
            print('Incorrect: {}'.format(answer))
    return score


questions = get_questions('questions.txt')
score = quiz(questions)
num_questions = len(questions)
print('You scored {}/{}'.format(score, num_questions))