如何循环Python代码,每次更改细节?

时间:2015-11-26 09:36:02

标签: python loops

此代码执行它应该执行的操作,但我不知道如何正确循环它。代码本身工作正常,但它太长了,所以我需要把它放在一个循环中。我的代码如下:

    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.")

这只是代码的1/10,重复了9次。

好的,我对如何使用循环有所了解。这段代码中的问题是我需要程序有3个加法,4个减法和3个乘法问题。有办法吗?

3 个答案:

答案 0 :(得分:4)

只需将代码放入方法中并循环10次:

import random

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

for i in range(10):
    ask_questions()

答案 1 :(得分:4)

使其成为一个函数,您可以指定是否要添加,减去或相乘:

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,"!")

答案 2 :(得分:0)

只是为了好玩,使用itertoolseval和其他Python细节:

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))