python - Capture value from function -
i'm having trouble while trying store output of function below, i'm trying create maths quiz asks randomized basic math questions , gives ability answer questions while checking whether correct , wondering if able me out code or provide me insight need learn in order complete it.
here have far:
print ("hello maths quiz, name?") name = input() random import choice,randint def rand_task1mathquiz(): a,b = randint(0,10),randint(0,10) random_operations = choice(["+","-","/","*"]) print("{0} {1} {2}".format(a,random_operations,b)) if __name__ == "__main__": x in range(10): rand_task1mathquiz()
the general pattern looking return
statement. when want capture return value of function, typically, you'd assign function's result variable, assign static values variables, except ()
on right-hand side makes function call evaluted, rather reference function object.
notice how doing return values library functions randint()
, choice()
, range()
, etc.
def rand_task1mathquiz(): a,b = randint(0,10),randint(0,10) random_operations = choice(["+","-","/","*"]) return("{0} {1} {2}".format(a,random_operations,b)) if __name__ == "__main__": x in range(10): quiz = rand_task1mathquiz() print quiz # evaluate returned value somehow, compare user input
the changed division of labor here worth noting -- function returns value, , caller prints it. useful function can run on own, no user interaction; input/output functionality should kept separate program logic far possible.
if want create list of questions, that's easy now, too:
questions = list() x in range(10): questions.append(rand_task1mathquiz()) # questions
or equivalently, less readably, using list comprehension:
questions = [rand_task1mathquiz() _ in range(10)]
a further improvement might have function return both question , answer; makes sense keep them both close in program code.
def rand_task(): a,b = randint(0,10), randint(0, 10) ops = {'+': int.__add__, '-': int.__sub__, '/': int.__truediv__, '*': int.__mul__} random_operation = choice(list(ops.keys())) # should still guard against op='/' b==0 return ops[random_operation](a, b), \ '{0} {1} {2}'.format(a, random_operation, b)
... though using __add__
, friends tricky understand yet. beats eval
in terms of security, perhaps should try it.
Comments
Post a Comment