2015-11-01 67 views
0

我需要一些幫助使代碼更經濟 - 我相信,我可以削減很多行。Python - 使我的代碼更經濟

該代碼是關於一個測驗,將問10個問題,你的分數將在最後輸出。

import random 
studentname=input("what is your name?:") 
score=0 
trueanswer=0 

def question(): 
    global operation 
    global number1 
    global number2 
    global studentanswer 
    global score 
    number1=random.randrange(1,10) 
    number2=random.randrange(1,10) 
    operation=random.choice(["*","-","+"]) 
    print("what is", number1,operation,number2,"?:") 
    studentanswer=int(input("insert answer:")) 

def checking(): 
    global score 
    if operation == "*": 
     trueanswer = number1*number2 
     if studentanswer == trueanswer: 
      print("correct") 
      score=score+1 
     else: 
      print("incorrect") 
      score=score 
    elif operation == "-": 
     trueanswer = number1-number2 
     if studentanswer == trueanswer: 
      print("correct") 
      score=score+1 
     else: 
      print("incorrect") 
      score=score 
    elif operation == "+": 
     trueanswer = number1+number2 
     if studentanswer == trueanswer: 
      print("correct") 
      score = score+1 
     else: 
      print("incorrect") 
      score=score 

def main(): 
    for i in range (10): 
     question() 
     checking() 
    print("your score is", score) 

main() 
+1

先消除明顯的重複代碼,然後https://docs.python.org/2/library/operator.html –

+5

工作代碼應該在codereview.stackexchange.com上提出這樣的建議。 – chepner

回答

-3

您可以將整個檢查功能降低這樣的:

def checking(): 
    trueanswer = eval(str(number1)+operation+str(number2)) 
    if studentanswer == trueanswer: 
     print("correct") 
     score=score+1 
    else: 
     print("incorrect") 
     score=score 
+0

削減無用的線路可能是值得的努力,絕對不值得引入可怕的技巧。特別是,鼓勵使用'eval'永遠不是好事。作爲一個旁註,當你看到一串長長的「if ... elif ... else」時,它通常是一個標誌,代碼將從使用一些抽象(如輕量級[策略模式](https:/ /en.wikipedia.org/wiki/Strategy_pattern)。 – spectras

+0

感謝您的反饋。我不知道這個問題與exec/eval。 – Kamejoin