Python - Mental Math Test (Can this be more efficient?) -


i've been trying improve python skills , decided make program asks user 10 simple math questions using +, -, , /. code works (well have tested , far does) want retain current functionality. there method make more efficient? it's python 3.4.3

    import random      username = input("enter name: ")     score = 0      in range(10):         sign = ""         answer = 0         numone = random.randint(1,10)         numtwo = random.randint(1,10)         pickoperator = random.randint(1,3)         if pickoperator == 1:             sign = " + "             answer = numone + numtwo         elif pickoperator == 2:             sign = " - "             answer = numone - numtwo        elif pickoperator == 3:             sign = " * "             answer = numone * numtwo         else:             print ("an error has occured")         question = "what " + str(numone) + sign + str(numtwo) + "? "         user_answer = int(input(question))         if user_answer == answer:             print ("that correct answer!")             score = score + 1         else:             print ("that answer incorrect!")      print (username + " got " + str(score) + " out of 10") 

several things can done make code more pythonic, note: efficiency (like running code faster) same because speed limited on how fast user can input data , several magnitude orders slower computer's clock.

to easy expand operations, can create this:

from operator import add, sub, mul signs = ['+', '-', '*'] operations = [add, sub, mul] mapping = {s: o s, o in zip(signs, operations)} 

therefore, can use pickoperator way:

sign = signs[pickoperator] operation = mapping[sign] answer = operation(numone, numtwo) 

and remove if, elif.

when invalid operation occurs, sign assignment receive exception (indexerror). have catch , display error message continue program. although should never occur if use random functions correctly:

consider using randrange instead of randint. able write:

pickoperator = random.randrange(0, len(signs)) 

another option abandon variable , use random.choice instead:

sign = random.choice(signs) 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -