内置函数range() range函数的优点:不管range对象表示的整数序列有多长,所有range对象占用的内存空间都是相同的
r=range(10)
print(list(r))
r=range(1,10)
print(list(r))
r=range(1,10,2)
print(list(r))
print(10 in r)
print(10 not in r)
循环结构
-
while -
for-in -
while循环的执行流程:
四步循环法:
- 初始化变量
- 条件判断
- 条件执行体
- 改变变量
sum=0
a=0
while a<5:
sum+=a
a=a+1
print('最终结果为',sum)
最终结果为 10
for in 循环
for item in 'python':
print(item)
for i in range(10):
print(i)
for _ in range(5):
print('hello')
水仙花作业:
'''
举例:
159=9*9*9+5*5*5+1*1*1就是水仙花数
'''
for item in range(100,1000):
ge=item%10
shi=item//10%10
bai=item//100
if ge*ge*ge+shi*shi*shi+bai*bai*bai==item:
print(item)
153
370
371
407
break语句(非正常结束循环)
用for in 语句来写银行密码的题:
for i in range(3):
psw=input('请输入密码')
if psw=='666':
print('密码正确')
break
else:
print('密码错误')
用while来写上面那道题:
a=0
while a<3:
b=input('请输入密码')
if b=='666':
print('密码正确')
a+=1
break
else:
a+=1
print('密码错误')
else:
print('次数已用完')
流程控制语句
for item in range(1,51):
if item%5!=0:
continue
else:
print(item)
else语句
for else的用法:
for i in range(3):
psw=input('请输入密码')
if psw=='666':
print('密码正确')
break
else:
print('密码错误')
else:
print('次数已用完')
嵌套结构
for i in range(1,4):
for j in range(1,5):
print(i,'*',j,'=',i*j,end='\t')
print()
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4
2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12
for s in range(1,10):
for q in range(1,s+1):
print(s,'*',q,'=',s*q,end='\t')
print()
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81
python中的end作用
python语句中end=’ '的作用 print默认是打印一行,结尾加换行。end=’ '意思是末尾不换行,加空格。空格数取决于引号里面的空格数
for i in range(1,4):
for j in range(1,5):
print(i,'*',j,'=',i*j,'')
print()
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
for i in range(1,4):
for j in range(1,5):
print(i,'*',j,'=',i*j,end=' ')
print()
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4
2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12
二重循环的break和continue
|