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)