对于刚开始学习python编程的小菜鸟,for循环和while循环在实际使用中,没有理解透彻。导致程序循环结果不理想。
1、for循环
for循环,就是遍历某一对象,通俗说就是根据循环次数限制做多少次重复操作。
如 for i in range(3): 意思就是i循环4次,i的取值为0、1、2。
2、while循环
while循环,是当满足什么条件的时候,才做某种操作
如 while count < 3: 意思就是当count小于3时,才做下面的操作
比如登录的一个小程序,最多输入用户名和密码3次,这时就应该用while循环,而不是for循环,因为循环次数不一定
username = 'konglongmeimei'passwd = '123456'count = 0import datetimetoday =datetime.date.today()while count < 3: new_username = input('请输入用户名:') new_passwd = input('请输入密码:') new_username = new_username.strip() new_passwd = new_passwd.strip() if new_username == username and new_passwd == passwd: print('%s,欢迎登录,今天的日期是%s'%(new_username,today)) break elif new_username =='' or new_passwd =='': print('输入的用户名或密码为空') count+=1 continue else: print('输入的用户名或密码有误') count+=1 continueelse: print('失败次数超过3次')运行结果:可以只循环1次
运行结果:也可以循环3次,这里可以看出最多循环了3次,因为count限制了循环次数最多是3次
来源:https://www.cnblogs.com/klmm/p/8620331.html