我想用x和z来计算y的值,给出x的范围是1-5,z在2-6之间。还需要注意的是,x控制着外部循环。我的代码的问题是内部for循环不迭代。
x = 1
for x in range(1, 6, 1):
for z in range(2, 6, 1):
if(x==z):
print("Function undefined")
else:
y =(float)(x*z)/(x-z)
print("When x = ",x ,", z =",z , "then y =",y)
break 发布于 2022-09-02 22:00:21
你的代码就快到了。
您所需要做的就是删除break语句,该语句在第一次迭代中退出内部z循环(每次2次)。
结果会是这样:
When x = 1 , z = 2 then y = -2.0
When x = 1 , z = 3 then y = -1.5
When x = 1 , z = 4 then y = -1.3333333333333333
When x = 1 , z = 5 then y = -1.25
Function undefined
When x = 2 , z = 2 then y = -1.25
When x = 2 , z = 3 then y = -6.0
When x = 2 , z = 4 then y = -4.0
When x = 2 , z = 5 then y = -3.3333333333333335
When x = 3 , z = 2 then y = 6.0
Function undefined
When x = 3 , z = 3 then y = 6.0
When x = 3 , z = 4 then y = -12.0
When x = 3 , z = 5 then y = -7.5
When x = 4 , z = 2 then y = 4.0
When x = 4 , z = 3 then y = 12.0
Function undefined
When x = 4 , z = 4 then y = 12.0
When x = 4 , z = 5 then y = -20.0
When x = 5 , z = 2 then y = 3.3333333333333335
When x = 5 , z = 3 then y = 7.5
When x = 5 , z = 4 then y = 20.0
Function undefined
When x = 5 , z = 5 then y = 20.0发布于 2022-09-02 22:32:16
作为另一种选择,如果您实际上不需要打印"Function undefined" (调试除外),我们可以迭代生成器表达式来创建所有的x、y、z数字。
>>> for x, y, z in ((x, y, z) for x in range(1, 6, 1)
... for z in range(2, 6, 1)
... if x != z
... for y in [(x*z) / (x-z)]):
... print(f"When x = {x}, z = {z}, then y = {y}")
...
When x = 1, z = 2, then y = -2.0
When x = 1, z = 3, then y = -1.5
When x = 1, z = 4, then y = -1.3333333333333333
When x = 1, z = 5, then y = -1.25
When x = 2, z = 3, then y = -6.0
When x = 2, z = 4, then y = -4.0
When x = 2, z = 5, then y = -3.3333333333333335
When x = 3, z = 2, then y = 6.0
When x = 3, z = 4, then y = -12.0
When x = 3, z = 5, then y = -7.5
When x = 4, z = 2, then y = 4.0
When x = 4, z = 3, then y = 12.0
When x = 4, z = 5, then y = -20.0
When x = 5, z = 2, then y = 3.3333333333333335
When x = 5, z = 3, then y = 7.5
When x = 5, z = 4, then y = 20.0https://stackoverflow.com/questions/73588241
复制相似问题