【问题标题】:The number shown starts at 10 and increases by a random amount until 60 is reached显示的数字从 10 开始并随机增加,直到达到 60
【发布时间】:2021-03-30 19:38:49
【问题描述】:

显示的数字从 10 开始并随机增加,直到达到 60。编写一个子程序来实现这一点。例如 10% 折扣。 24% 折扣。 48% 折扣。 60% 折扣。

这就是代码应该做的。这是我到目前为止写的代码。它只打印出 0% insted 的完整内容

import random

#subroutine to show discounts

def Percent(total, Num):
    while total != 60:
        total = total + Num
    return total, Num

#main program
Num = random.randint(0,10)
total = 10
print(total,"% off")

ps 我对 python 很陌生,所以如果修复真的很明显,请不要吝啬 :)

【问题讨论】:

  • 你永远不会打电话给Percent。这是故意的吗?
  • 如果所有回复都没有解决您的问题,请您更新它以澄清缺少的内容吗?或者,查看what to do when someone answers your question 上的帮助页面指南。

标签: python random subroutine


【解决方案1】:

好的,这里有一种方法可以做你想做的事。请如果你有问题问!我会尽力解释一切。

import random

starting_pos = 10
print(starting_pos, '% off')
to_reach = 60
total = starting_pos

while total < to_reach:
    max_limit = to_reach - total
    total += random.randint(1, max_limit)
    print(total, '% off')

【讨论】:

    【解决方案2】:

    你从来没有在你的代码中使用你的函数。 并考虑更改循环条件以避免无限循环

    import random
    
    def Percent(total, Num):
        while total <= 60:
            total = total + Num
        return total
    
    #main program
    Num = random.randint(0,10)
    total = 10
    p = Percent(total, Num)
    print(p,"% off")
    

    【讨论】:

      【解决方案3】:

      您的书面示例显示了不同的增量,因此随机数生成应放在您的函数中,以便每次调用产生不同的值。您也没有指定增量大小的任何上限,因此我假设您可以想象(但不太可能)直接从 10 跳到 60。以下实现使用 @ 编写为生成器987654321@ 而不是return。它总是以 10 开头,以 60 结尾。

      import random
      
      def Percent():
          current = 10   # start at 10
          while current < 60:    # keep going while you're below 60
              yield current      # hand back the current value when asked
              # Now generate the next value to be somewhere between the
              # last value and 65.  Anything bigger than 59 will cause it
              # to bail from the loop.  I chose 65 as an upper limit to
              # avoid a lot of dinky little steps as you get close to 60 
              current = random.randint(current + 1, 65)
          # We got something bigger than 59, so just cough up 60 as the outcome.
          yield 60    
      
      #main program
      for discount in Percent():
          print(discount,"% off")
      
      

      这会产生如下输出:

      10 % off
      25 % off
      52 % off
      58 % off
      60 % off
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-28
        • 2014-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多