鱼C论坛

 找回密码
 立即注册
查看: 2793|回复: 7

[已解决]新手,求问while循环和for循环的用法

[复制链接]
发表于 2020-2-19 17:33:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
>>> def Findstr(father,son):
        s = 0
        i = 0
        while i < len(father):
                print (father[i]+father[i+1])
                if (father[i]+father[i+1]) == son:
                        s += 1
                        i += 1
        print ("son appear ",s,'times')

       
请问各位大神这里的循环出啥问题了,为什么结果是这样(如下)
>>> Findstr('you can not improve your past , but you can improve your future . once time is wasted ,life is wasted ','im')
yo
yo
yo
yo
。。。。。。(无数个yo)

还有
>>> def Findstr(father,son):
        s = 0
        i = 0
        for each in father:
                if (father[i]+father[i+1]) == son:
                        s += 1
                        i += 1
        print ("son appear ",s,'times')

为啥两个都循环不起来


最佳答案
2020-2-19 17:51:28
#你的if 条件都满足不了,i怎么增加的?正确代码已经附上
  1. def Findstr(father,son):
  2.     s = 0
  3.     i = 0
  4.     while i < len(father)-1:
  5.             if (father[i]+father[i+1]) == son:
  6.                     s += 1
  7.             i += 1
  8.     print ("son appear ",s,'times')
  9.    
  10. print( Findstr('you can not improve your past , but you can improve your future . once time is wasted ,life is wasted ','im'))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-2-19 17:38:16 From FishC Mobile | 显示全部楼层
不要在>>>下验证多行代码,无他,太累
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-19 17:40:59 | 显示全部楼层
你看看你有没有正确的退出循环的条件
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-19 17:48:41 | 显示全部楼层
第二个for each ......用的是each,但是下面用的是i
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-19 17:51:28 | 显示全部楼层    本楼为最佳答案   
#你的if 条件都满足不了,i怎么增加的?正确代码已经附上
  1. def Findstr(father,son):
  2.     s = 0
  3.     i = 0
  4.     while i < len(father)-1:
  5.             if (father[i]+father[i+1]) == son:
  6.                     s += 1
  7.             i += 1
  8.     print ("son appear ",s,'times')
  9.    
  10. print( Findstr('you can not improve your past , but you can improve your future . once time is wasted ,life is wasted ','im'))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-19 17:58:18 | 显示全部楼层
本帖最后由 qiuyouzhi 于 2020-2-19 18:21 编辑

这个发错了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-19 19:14:01 From FishC Mobile | 显示全部楼层
我也是新手,但是while循环我还是略知一二的

比如,你给wy赋值:
wy=3
while wy>0:
(你要写的程序)
wy=wy-1
如果你要循环五次可以把wy的值赋5
while wy指wy>0时运行这个程序,后面wy=wy-1就是逐渐减小wy的值,也就是循环次数少一次,当wy=0是就停止运行了
for循环我就不知道了,我也是新手
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-3-2 16:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表