[Python3基础] for循环、while循环、break、continue、pass、range()函数

for循环

根据变量赋值的次数来进行循环

格式:循环语句注意缩进4格

for 变量 in list/tuple/string/dictionary/set:
    循环语句
else:

例如:

for item in 'python':   #字符串
    print("hello"+item)
    
print("*****************************")

for item in ['tom','bob','jerry']:   #列表
    print('hello'+item)
    
print("*****************************")

for item in ('tom','bob','jerry'):   #元组
    print('hello'+item)
    
print("*****************************")

for item in {'tom','bob','jerry'}:   #集合
    print('hello'+item)
    
print("*****************************")

for item in {'tom':123,'bob':321,'jerry':1234567}:   #字典
    print('hello'+item)      #赋的是key
    
print("*****************************")

adict = {'tom':123,'bob':321,'jerry':1234567}
for item in adict:   #字典
    print('hello'+str(adict[item]))      #根据键取值

在这里插入图片描述
这样的话有点麻烦,我们通常使用数字序列来进行循环

range()函数

如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列:

range(stop)
range(start, stop[, step])
start默认是0,显示的时候不含stop,step步长,默认走一步
可以参考string类型的取值

默认是0开始
>>>for i in range(5):
...     print(i)
...
0
1
2
3
4
指定区间(含头不含尾)
>>>for i in range(5,9) :
    print(i)    
5
6
7
8
指定步长
>>>for i in range(0, 10, 3) :
    print(i)     
0
3
6
9
可以为负
>>>for i in range(-10, -100, -30) :
    print(i)    
-10
-40
-70
count = 0
for count in range(0,5):
   print (count, " 小于 5")
else:
   print ("hahah")    #循环结束后执行

在这里插入图片描述

len()函数

获取序列的长度

>>> a="string"
>>> print(len(a))
6
循环语句的子语句break、continue、pass
  • break:立即退出循环,任何对应的循环 else 块将不执行。
  • continue:结束当前循环(下面的语句不执行),继续执行下一次循环
  • pass:空语句,是为了保持程序结构的完整性。没有实际作用

while循环

根据是否满足条件进行循环

一般格式:循环语句注意缩进4格

while 条件:
    循环语句

猜数字小游戏

import random
c_choice = random.randint(1,100)
i = 0
while i < 10: 
    i=i+1
    p_choice = int(input("请输入100以内的整数:"))
    if p_choice > c_choice:
        print('你猜大了')
    elif p_choice == c_choice:
        print('猜对了!')
        break
    else :
        print("你猜小了")

在这里插入图片描述
1-10内的偶数和

summ = 0
num = 0
while num < 10:
    num += 1
    if num % 2:      #如果是奇数
        continue    #跳出此次循环,后面语句都不执行
    summ += num     
print(summ)

在这里插入图片描述
while…else…格式:

循环输出数字,并判断大小:

count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")

在这里插入图片描述

>>>while True:
...     pass  # 等待键盘中断 (Ctrl+C)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值