2015-11-01 69 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