2016-07-31 49 views
0

我正在使用最新的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.") 

請糾正我,如果看起來不對,我是新來的蟒蛇。無論如何,我想要做的就是再次打印問題,而不必重複介紹(開始)。我的實際代碼更長,是一個完整的測驗,我需要從代碼的不同部分重複某些代碼段。請幫忙!另外,如果代碼粘貼到我的帖子中時沒有正確打印,我很抱歉。

+0

看起來您已經理解如何「跳過」代碼的某些部分,一種方法就是您在這裏使用if .. elif。 。else'語句。 Python中代碼區域(包括up)之間跳轉*的典型方法是循環(例如'while','for in')和函數。你可能會考慮閱讀這些語言的方面。 [本教程](http://introtopython.org/while_input.html)似乎特別適用,因爲它處理循環*和*用戶輸入。 – jedwards

回答

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's Learning Python