python基础---for循环(12)

1、定义

①:什么是for循环

循环就是重复做某件事,for循环是python 提供第二种循环机制

②:为何要有for循环

理论上for循环能做的事情,while循环都可以做
之所以要有for循环,是因为for循环在循环取值(遍历取值)比while循环更简洁

③:如何用for循环

语法:
 for 变量名 in 可迭代对象: # 可迭代对象可以是:列表、字典、字符串、元组、集合
      代码1
      代码2
      ....

2、for循环基本使用

①:循环取值

# 简单版
l = ['zhou', 'shun', '123']
for x in l: #
    print(x)
# 复杂版:
l = ['zhou', 'shun', '123']
i = 0
while i < 3:
    print(l[i])
    i += 1

②:字典循环取值

# 简单版:
dic = {'k1': 1, 'k2': 2, 'k3': 3}
for k in dic:
    print(k, dic[k])

# 复杂版:while循环可以遍历字典,太麻烦了

③:字符串循环取值

# 简单版:
msg = "good good study, day day up"
for x in msg:
    print(x)

# 复杂版:while循环可以遍历字典,太麻烦了

3、for循环控制循环次数:range

for i in range(30):
    print(i)

4、 for + break:同while循环一样

while循环请参考:https://blog.csdn.net/qq_43707174/article/details/125697393

5、for + else : 同while循环一样

while循环请参考:https://blog.csdn.net/qq_43707174/article/details/125697393

username = 'zhoushun'
password = '123'
for i in range(3):
    inp_name = input('请输入您的账号:')
    inp_pwd = input('请输入您的密码:')
    if inp_name == username and inp_pwd == password:
        print('登录成功!')
        break
else:
    print('密码或账号输错超过三次')

6、 for + continue

for i in range(6):
    if i == 4:
        continue
    print(i)

7、for循环嵌套

外层循环循环一次,内层循环循环需要完整的循环完毕

for i in range(3):
    print('外层循环---》', i)
    for j in range(5):
        print('内层循环---》', j)

补充:终止for循环只有break一种方案

8、 for循环与while循环

①:相同之处

都是循环,for循环可以干的事,while循环也可以干

②:不同之处

(1)while循环称之为条件循环,循环次数取决于条件何时变为假。
(2)for循环称之为“取值循环”,循环次数取决于in后包含的值的个数。

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值