【问题标题】:Print different strings using same loop使用相同的循环打印不同的字符串
【发布时间】:2020-05-27 11:55:58
【问题描述】:

所以我正在制作这个数学问题生成器。它从 1-20 中选择 2 个随机数和一个随机数学运算符。我希望它打印这个:

num1 符号 num2(例如 5 * 2)

但我不知道该怎么做。这就是我的代码得到的结果:

num1 符号 num2 符号(例如 5 * 2 *)

这是我的代码:

import random

def problem():

    randsymbol = random.randint(1,4)

    if randsymbol == 1:
        symbol = "+"
    elif randsymbol == 2:
        symbol = "-"
    elif randsymbol == 3:
        symbol = "*"
    else:
        symbol = "/"

    for count in range (0, 2):
        num = random.randint(1,20)
        print(num,symbol)

problem()

我知道问题是因为我在循环内同时打印数字和符号,但如果我不这样做,那么我就无法打印 2 个不同的数字。所以如果我把代码从循环中取出,我会得到这样的东西: num1 符号 num1(例如 5 * 5)

它只打印一次符号,但打印两次完全相同的数字。

谢谢!

【问题讨论】:

    标签: python string printing


    【解决方案1】:

    改变这个:

        for count in range (0, 2):
            num = random.randint(1,20)
            print(num,symbol)
    

    到这里:

        num1 = random.randint(1,20)
        num2 = random.randint(1,20)
        print(num1,symbol,num2)
    

    【讨论】:

      【解决方案2】:

      试试这个:

      import random
      
      def problem():
          randsymbol = random.choice(["+", "-", "*", "/"])
          num1 = random.randint(1,20)
          num2 = random.randint(1,20)
          print(f"{num1} {randsymbol} {num2}")
      
      problem()
      

      【讨论】:

        【解决方案3】:
        def problem():
            randsymbol = random.choice('+-*/')
            nums = random.sample(list(range(1,21)), 2)
            print('{} {} {}'.format(nums[0], randsymbol, nums[1]))
        

        例子

        >>> problem()
        14 * 6
        >>> problem()
        4 / 10
        >>> problem()
        7 / 10
        

        然后,您可以将这些符号的字典用于operator 中的函数来评估此表达式并返回值(例如,用于检查用户输入)

        import operator
        import random
        
        def problem():
            randsymbol = random.choice('+-*/')
            nums = random.sample(list(range(1,21)), 2)
            print('{} {} {}'.format(nums[0], randsymbol, nums[1]))
        
            ops = {'+' : operator.add,
                   '-' : operator.sub,
                   '*' : operator.mul,
                   '/' : operator.truediv}
        
            return ops[randsymbol](nums[0], nums[1])
        

        例子

        >>> problem()
        15 + 16
        31
        >>> problem()
        15 - 8
        7
        >>> problem()
        8 - 16
        -8
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-06
          • 2021-04-21
          • 1970-01-01
          • 1970-01-01
          • 2023-03-19
          • 2019-09-28
          相关资源
          最近更新 更多