首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:如何在嵌套for循环中增加内循环和外循环

Python:如何在嵌套for循环中增加内循环和外循环
EN

Stack Overflow用户
提问于 2022-09-02 21:55:57
回答 2查看 40关注 0票数 -2

我想用x和z来计算y的值,给出x的范围是1-5,z在2-6之间。还需要注意的是,x控制着外部循环。我的代码的问题是内部for循环不迭代。

代码语言:javascript
复制
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        
EN

回答 2

Stack Overflow用户

发布于 2022-09-02 22:00:21

你的代码就快到了。

您所需要做的就是删除break语句,该语句在第一次迭代中退出内部z循环(每次2次)。

结果会是这样:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2022-09-02 22:32:16

作为另一种选择,如果您实际上不需要打印"Function undefined" (调试除外),我们可以迭代生成器表达式来创建所有的x、y、z数字。

代码语言:javascript
复制
>>> 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.0
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73588241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档