Python 在一个范围内只使用一次函数的问题
我有一项任务,无法找出真正的解决办法Python 在一个范围内只使用一次函数的问题,python,function,stopiteration,Python,Function,Stopiteration,我有一项任务,无法找出真正的解决办法 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(
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)}"))
当值的平方大于值的三倍时,我应该停止迭代,而不在上一次迭代中打印任何内容
三重函数和平方函数每次迭代都必须调用一次
我试过的其他东西
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)
有一个测试检查了我的答案,结果显示打印的行数错误,我问过课程中的某个人,他们刚刚告诉我,ı应该将从每个函数得到的值存储到一个变量中。这就是我试图做的,他们说的根据你的评论,你的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将退出foor循环,您希望避免打印,这是一个完全不同的主题请尝试以下代码
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。如果你换成“是”,因为三元组3是9,平方组3是9,在这个条件下,你是在破坏。如果你想让程序继续,那么不要中断,简单。
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)))