Ojars Taurins
Ojars Taurins

Reputation: 11

How to loop Python code, changing details each time?

This code does what it is supposed to do, but I do not know how to loop it correctly. Code itself is working perfectly, but it is way too long, so I need to put it in a loop. My code looks as follows:

    random1 = random.randint(0, 100)
    random2 = random.randint(0, 100)
    solution1 = random1 + random2
    print ("What is ", random1, " + ", random2, "?")
    user_answer1 = input()
    if solution1 == int(user_answer1):
         print ("Answer is correct!")
         score += 1
    else:
         print ("Answer is wrong!")

    print ("Your score is ", score, "! Let's continue.")

This is only a 1/10 of the code, this is repeated 9 more times.

Okay, I know a bit about how to use loops. The problem in this code is that I need the program to have 3 addition , 4 subtraction and 3 multiplication questions. Is there a way to do it?

Upvotes: 0

Views: 102

Answers (3)

arekolek
arekolek

Reputation: 9621

Just for fun, using itertools, eval and other Python niceties:

from random import randint
from itertools import chain, repeat

def question(op, a=0, b=100):
  operation = "{} {} {}".format(randint(a, b), op, randint(a, b))
  correct = eval(operation) == int(input("\nWhat is {}?\n> ".format(operation)))
  print("Your answer is {}!".format("correct" if correct else "wrong"))
  if not correct: print("It's {}.".format(eval(operation)))
  return correct

score = sum(map(question, chain.from_iterable(map(repeat, '+-*', [3, 4, 3]))))

print("\nYour total score is {}!".format(score))

Upvotes: 0

elzell
elzell

Reputation: 2306

Make it a function where you can specify if you want to add, subtract or multiply:

def question(op):
    random1 = (random.randint(0, 100))
    random2 = (random.randint(0, 100))
    if op == '+':
        solution1 = random1+random2
    elif op == '-':
        solution1 = random1-random2
    else:
        solution1 = random1*random2
    print ("What is ",random1, op,random2, "? ")
    user_answer1 = (input())
    if solution1 == int(user_answer1):
        print ("Answer is correct!")
        return 1
    else:
        print ("Answer is wrong!")
        return 0

score = 0
for i in range(3):
    score += question('+')
for i in range(4):
    score += question('-')
for i in range(3):
    score += question('*')

print ("Your score is",score,"!")

Upvotes: 4

adrianus
adrianus

Reputation: 3199

Just put your code in a method and loop over it 10 times:

import random

def ask_questions():
    random1 = random.randint(0, 100)
    ...

for i in range(10):
    ask_questions()

Upvotes: 4

Related Questions