【问题标题】:Problem with using a function just once in a range在一个范围内只使用一次函数的问题
【发布时间】:2020-09-22 15:11:12
【问题描述】:

我有一个任务,无法找出真正的解决方案。

def triple(n):    #multiplies number with 3
    return (n*3)
def square(n):
    return (n**2)   #takes second power of number

for i in range(1,11):
    if triple(i) > square(i):
        print((f"triple({i})=={triple(i)} square({i})=={square(i)}"))
triple(1)==3 square(1)==1
triple(2)==6 square(2)==4
  1. 当一个值的平方大于该值的三倍时,我应该停止迭代,在最后一次迭代中不打印任何内容。

  2. 并且函数triple 和square 每次迭代都必须调用一次。

我尝试过的其他事情

    ls =[f"triple({i})=={triple(i)} square({i})=={square(i)}" for i in range(1,11) if triple(i) > square(i)]
    for i in ls:
        print(i)

有一个测试可以检查我的答案,它说“打印行数错误”,我问过某人,他们刚刚告诉我,我应该将从每个函数获取的值存储到一个变量中。这些就是我试图按照他们所说的去做的事情

【问题讨论】:

  • 是的,因为 Triple(3) 是 9,而 square(3) 是 9,在这种情况下你正在打破。如果您希望程序继续运行,请不要中断,简单。

标签: python function stopiteration


【解决方案1】:

试试下面的代码,

    def triple(n):    #multiplies number with 3
        return (n*3)
    def square(n):
        return (n**2)   #takes second power of number

    for i in range(1,11):   #I asked to iterate 1 to 10
        triple_ = triple(i)
        square_ = square(i)
        if triple_ < square_:   #it shouldnt print if square of the 
number is larger than the triple
            pass #it must END the loop
        else:
            print("Triple of " + str(i) + " is " + str(triple(i)) + " and its greater than or equal to its square " + str(square(i)))

在 i = 3 的情况下,正方形是 9,三重也是 9。因此,如果将

之后它会停止打印,因为没有满足任何条件。对于 (1,10) 之间的数字,只有 1,2 和 3 是三元组平方小于或等于三元组的唯一可能数。

【讨论】:

    【解决方案2】:

    根据您的 cmets,您的 if 条件全部错误:

    def triple(n):    #multiplies number with 3
        return (n*3)
    def square(n):
        return (n**2)   #takes second power of number
    
    for i in range(1,11):   #I asked to iterate 1 to 10
        triple_ = triple(i)
        square_ = square(i)
        if triple_ > square_:   #it should only print if the square of the number is smaller than the triple
            print(f"triple({i})=={triple(i)} square({i})=={square(i)}")
    

    break 将退出 foror 循环,您希望避免打印,这是一个完全不同的主题

    【讨论】:

      猜你喜欢
      • 2019-10-30
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 2010-11-30
      相关资源
      最近更新 更多