【问题标题】:Does anyone know how i can put this into a loop?有谁知道我怎么能把它变成一个循环?
【发布时间】:2017-01-08 12:05:22
【问题描述】:
print("welcome to the maths game")
import random
score = 0
print("Question One")
numberOne=random.randint(1,12)#These two randomly generate 2 numbers for the question
numberTwo=random.randint(1,12)      
question = str(numberOne)+ " x " + str(numberTwo) + " = " 
answer = int(input(question))                             

if answer == numberOne*numberTwo:
    print("Well Done It's Correct, Next Question")
    score + 1 #puts the score plus one
else:
    print("Better Luck Next Time, Next Question")
print("Question Two")
numberOne=random.randint(1,12)    
numberTwo=random.randint(1,12)
question = str(numberOne)+ " x " + str(numberTwo) + " = " 
answer = int(input(question))                             

if answer == numberOne*numberTwo:
    print("Well Done It's Correct, Next Question")
    score = score + 1
else:
    print("Better Luck Next Time, Next Question")
print("Question Three")
numberOne=random.randint(1,12)    
numberTwo=random.randint(1,12)
question = str(numberOne)+ " x " + str(numberTwo) + " = " 
answer = int(input(question))                             

if answer == numberOne*numberTwo:
    print("Well Done It's Correct, Next Question")
    score = score + 1
else:
    print("Better Luck Next Time, Next Question")
print("Question Four")
numberOne=random.randint(1,12)    
numberTwo=random.randint(1,12)
question = str(numberOne)+ " x " + str(numberTwo) + " = " 
answer = int(input(question))                             

if answer == numberOne*numberTwo:
    print("Well Done It's Correct, Next Question")
    score = score + 1
else:
    print("Better Luck Next Time, Next Question")
print("Question Five")
numberOne=random.randint(1,12)    
numberTwo=random.randint(1,12)
question = str(numberOne)+ " x " + str(numberTwo) + " = " 
answer = int(input(question))                             

if answer == numberOne*numberTwo:
    print("Well Done It's Correct, Thats The End")
    score = score + 1
else:
    print("Better Luck Next Time, Thats The End")

我需要通过将其放入循环来缩短此代码。但是,当我尝试时,我无法在每个段落中保留问题一、二、三、四、五。就是随机生成 2 个数字 5 次进行小乘法表测试(我学校的 Python 作业)。

【问题讨论】:

标签: python python-3.x loops


【解决方案1】:

最简单的方法可能是创建一个单词列表并在每次迭代时对该列表进行索引。显然,当您希望能够扩展到任意数量时,这会成为一个问题,在这种情况下,您似乎可以使用讨论过的库之一here。要显示您的单词,您可以使用format 方法。

import random

number_words = ['one', 'two', 'three', 'four', 'five']
score = 0

for x in range(5):
    print("Question {}".format(number_words[x]))
    numberOne=random.randint(1,12)    
    numberTwo=random.randint(1,12)
    question = "{} x {} = ".format(numberOne, numberTwo)
    answer = int(input(question))       

    if answer == numberOne*numberTwo:
        if x != 4:
            print("Well Done It's Correct, Next Question")
        else:
            print("Well Done It's Correct, Thats The End")
        score = score + 1
    else:
        if x != 4:
            print("Better Luck Next Time, Next Question")
        else:
            print("Better Luck Next Time, Thats The End")

print("This is not in the loop")
# Write non-looping code here

【讨论】:

  • 如何将循环放在这段代码中,它下面的代码(我没有显示)包含在循环中,我不希望它添加代码如果你想让我单独发表评论
  • @JarrethGriffith 我做了两次编辑。首先,在循环的最后一次迭代中,您会收到一条消息,说“到此结束”。该循环仅适用于在该循环内缩进的代码。例如,你可以看到我把print("This is not in the loop") 没有缩进 - 这只会打印一次,并且只会在循环完成 5 次后打印。
  • 那是我放其他代码的地方,但每次都在使用它,我会重试编辑——它已经成功了,对不起,我没有正确复制我的代码,而不是你
  • @JarrethGriffith 这是不可能的,只要代码在for 中与f 开始的位置相同,那么它就不在for 循环的范围内,并且不会重复。你需要仔细检查你的缩进。
  • 是的,我明白了,因为我是 python 新手
【解决方案2】:

试试那个:

import random

print("welcome to the maths game")
score = 0

titles = map(lambda s: "Question %s" % s, ['One', 'Two', 'Three', 'Four', 'Five'])


def gen_randoms():
    return random.randint(1, 12), random.randint(1, 12)


for t in titles:
    print(t)
    num_one, num_two = gen_randoms()
    question = str(num_one) + " x " + str(num_two) + " = "
    answer = int(input(question))
    if answer == num_one * num_two:
        print("Well Done It's Correct, Next Question")
        score += 1  # puts the score plus one
    else:
        print("Better Luck Next Time, Next Question")

print("Your resulting score is %s" % score)

【讨论】:

  • 谢谢你的工作,因为我是 python 的相对论新手,我不明白你使用的一些命令你能告诉我什么是“def”、“map”、“lamba”,以及"%s" 用于
  • def 只是定义一个新函数的关键字,该函数可以在代码的其他地方调用。 lambda 是一个匿名函数(您不必使用 def,如果您只想定义一个使用它的函数,这会有所帮助), map 可以使用该函数(第一个参数)并在列表的每个元素上调用它(第二个参数), "%s" 仅用于字符串格式化,
  • 谢谢你让我更了解它
【解决方案3】:
import random
def int_to_en(num):
    # http://stackoverflow.com/questions/8982163/how-do-i-tell-python-to-convert-integers-into-words
    # @SiLent SoNG
    d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five',
          6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten',
          11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen',
          15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen',
          19 : 'nineteen', 20 : 'twenty',
          30 : 'thirty', 40 : 'forty', 50 : 'fifty', 60 : 'sixty',
          70 : 'seventy', 80 : 'eighty', 90 : 'ninety' }
    k = 1000
    m = k * 1000
    b = m * 1000
    t = b * 1000
    assert(0 <= num)
    if (num < 20):
        return d[num]
    if (num < 100):
        if num % 10 == 0: return d[num]
        else: return d[num // 10 * 10] + '-' + d[num % 10]
    if (num < k):
        if num % 100 == 0: return d[num // 100] + ' hundred'
        else: return d[num // 100] + ' hundred and ' + int_to_en(num % 100)
    if (num < m):
        if num % k == 0: return int_to_en(num // k) + ' thousand'
        else: return int_to_en(num // k) + ' thousand, ' + int_to_en(num % k)
    if (num < b):
        if (num % m) == 0: return int_to_en(num // m) + ' million'
        else: return int_to_en(num // m) + ' million, ' + int_to_en(num % m)
    if (num < t):
        if (num % b) == 0: return int_to_en(num // b) + ' billion'
        else: return int_to_en(num // b) + ' billion, ' + int_to_en(num % b)
    if (num % t == 0): return int_to_en(num // t) + ' trillion'
    else: return int_to_en(num // t) + ' trillion, ' + int_to_en(num % t)
    raise AssertionError('num is too large: %s' % str(num))

def get_question(num, *args):
  # param: num, convert int to word (instead list = ['one', 'two', 'three', 'four', 'five'.......])
  # your game should be scalable for N number of questions

  q_header = 'Question {0}:'.format(int_to_en(num)) # convert and add it to string, use {n} with index, faster than without
  r_N_a, r_N_b = [random.randint(1,12) for __ in range(2)] # to random num
  q_str = '{0} x {1} = '.format(r_N_a, r_N_b) #  creating question string  
  return (q_header, r_N_a*r_N_b, q_str) # return, you could now call get_question method from outside, if you need a question block in your other modules 

def run_game(num, score = 0):
  for n in range(num):
    q_header, expectation, q_str = get_question(n)
    print (q_header)
    answer = int(input(q_str))
    if not answer == expectation:
      print ('wrong')
    else:
      score += 1
      print ('next')

  return score

score = run_game(3) # 3 questions

block = [get_question(n) for n in range(50)] # 50 question/solution block
print (block)

print (block[24])    

[('Question zero:', 40, '5 x 8 = '), ('Question one:', 80, '8 x 10 = '), ('Question two:', 49, '7 x 7 = '), ('Question three:', 2, '1 x 2 = '), ('Question four:', 60, '12 x 5 = '), ('Question five:', 77, '7 x 11 = '), ('Question six:', 144, '12 x 12 = '), ('Question seven:', 77, '7 x 11 = '), ('Question eight:', 88, '8 x 11 = '), ('Question nine:', 5, '1 x 5 = '), ('Question ten:', 40, '5 x 8 = '), ('Question eleven:', 72, '12 x 6 = '), ('Question twelve:', 24, '4 x 6 = '), ('Question thirteen:', 72, '9 x 8 = '), ('Question fourteen:', 1, '1 x 1 = '), ('Question fifteen:', 2, '2 x 1 = '), ('Question sixteen:', 24, '6 x 4 = '), ('Question seventeen:', 80, '8 x 10 = '), ('Question eighteen:', 36, '4 x 9 = '), ('Question nineteen:', 99, '11 x 9 = '), ('Question twenty:', 42, '6 x 7 = '), ('Question twenty-one:', 12, '12 x 1 = '), ('Question twenty-two:', 96, '12 x 8 = '), ('Question twenty-three:', 50, '5 x 10 = '), ('Question twenty-four:', 72, '12 x 6 = '), ('Question twenty-five:', 80, '8 x 10 = '), ('Question twenty-six:', 24, '3 x 8 = '), ('Question twenty-seven:', 88, '8 x 11 = '), ('Question twenty-eight:', 108, '9 x 12 = '), ('Question twenty-nine:', 12, '3 x 4 = '), ('Question thirty:', 144, '12 x 12 = '), ('Question thirty-one:', 2, '2 x 1 = '), ('Question thirty-two:', 56, '8 x 7 = '), ('Question thirty-three:', 32, '8 x 4 = '), ('Question thirty-four:', 5, '1 x 5 = '), ('Question thirty-five:', 16, '4 x 4 = '), ('Question thirty-six:', 84, '7 x 12 = '), ('Question thirty-seven:', 44, '11 x 4 = '), ('Question thirty-eight:', 7, '7 x 1 = '), ('Question thirty-nine:', 54, '9 x 6 = '), ('Question forty:', 22, '2 x 11 = '), ('Question forty-one:', 77, '7 x 11 = '), ('Question forty-two:', 20, '5 x 4 = '), ('Question forty-three:', 9, '1 x 9 = '), ('Question forty-four:', 8, '2 x 4 = '), ('Question forty-five:', 24, '8 x 3 = '), ('Question forty-six:', 15, '5 x 3 = '), ('Question forty-seven:', 24, '8 x 3 = '), ('Question forty-eight:', 30, '6 x 5 = '), ('Question forty-nine:', 96, '12 x 8 = ')]

('Question twenty-four:', 110, '11 x 10 = ')

【讨论】:

  • @Steven Summers,谢谢,我会及时执行您的客观批评。对于即将到来的读者和我来说,这是一个很大的乐趣
猜你喜欢
  • 2021-12-13
  • 2021-09-28
  • 2011-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多