从python中的某一行开始

时间:2016-07-31 11:29:37

标签: python

我正在使用最新的python软件,我真的很难在代码中打印某一行。

name = input("Before we begin, what is your name? ")
print("Cool, nice to meet you "+name+"!")

score = 0 
score = int(score)
count = 0

answer1 = "dogs" 
answer01 = "dog"
question1 = ""
while question1 != answer1 and count < 2:
    count = count + 1
    question1 = input("What animal barks? ") #Asks the user a question 

    if question1.lower()== answer1:
          print("Correct! Off to a great start, the right answer is dogs!") 
          score = score + 1
          break

    elif question1.lower()== answer01:
          print("Correct! Off to a great start, the right answer is dogs!") 
          score = score + 1
          break

    elif count == 1:
          print("That is wrong",name,"but you can try again. Hint: They like bones. ")  

if count == 2 and question1 != answer1:
    print("Incorrect again, sorry! The right answer was dogs.") 

如果看起来不对,请纠正我,我是python的新手。无论如何,我想要做的就是再次打印问题而不重复介绍(开始)。我的实际代码更长,是一个完整的测验,我需要从代码的不同部分重复代码的某些部分。请帮忙!另外,如果我将代码粘贴到我的帖子中时代码没有正确打印,我很抱歉。

1 个答案:

答案 0 :(得分:1)

所以,问题是你的问题是硬编码的,所以他们重复等等。相反,你可以提供一个数据结构,存储你所有的问题,错误的正确答案,你会传递给一些解析逻辑。例如:

questions = ['What animal barks?', ...]
answers = [('dogs', 'dog'), ...]
hints = ['They like bones', ...]

def dialog(qst, ans, hnt):
    score = 0
    for question, answers, hint in zip(qst, ans, hnt):
        incorrects = 0
        while True:
            usr_ans = input(question)
            iscorrect = any(usr_ans.strip().casefold() == answ.strip().casefold() for answ in answers)
            if incorrects < 5 or not iscorrect:
                print('That is wrong, {},  but you can try again. Hint: {}'.format(name, hint))
                incorrects += 1
            elif incorrects >= 5:
                print('Incorrect again, sorry! The right answer was {}.'.format(' or '.join(answers))
                break
            else:
                print('Correct! Off to a great start, the right answer is {}!'.format(usr_ans))
                score += 1
                break
    return score

当你开始学习时,它可能看起来有点复杂。我建议不要编写完整的代码,直到您已经知道基础知识的时间点。一个好的开始,尝试官方的Python教程,我推荐Lutz的学习Python