Python的for循环与while语句

1.for循环语句
for 循环使用的语法:

for 变量 in range(10):
    循环需要执行的代码
else:
    全部循环结束后要执行的代码

(1) 求1~100之和
for(i=1;i<=100;i++)
sum = 0
for i in range(1,101):
#sum = sum +i
sum += i
print(sum)

(2)求1~100的奇数之和
sum = 0
for i in range(1,101,2):
sum += 1
print(sum)
(3) 求1~100的偶数只和
sum = 0
for i in range(2,101,2):
sum +=i
print(sum)

(4)用户输入一个数字,求该数的阶乘:3!=321
num = int(input('Num:'))
res = 1
for i in range(1,num+1):
res = res * i
print('%d的阶乘的结果为:%d' %(num,res))

用户登陆程序
1.输入用户名和密码
2.判断用户名和密码是否正确('name==root','passwd='westos')
3.为了防止暴力破解,登陆次数仅有三次,如果超过三次机会,报错

for i in range(3): #0 1 2
name = input('用户名:')
passwd = input('密码:')
if name == 'root' and passwd == 'westos':
print('登陆成功')
跳出整个循环,不会再执行后面的内容
break
else:
print('登陆失败')
print('您还剩余%d次机会' %(2-i))
else:
print('登陆次数超过三次,请等待100s后再次登陆')

Python的for循环与while语句

2. break continue exit
break:跳出整个循环,不会再循环后面的内容
continue:跳出本次循环,continue后面代码不会执行,
但是循环依然继续的
exit():结束程序的运行

for i in range(10):
if i == 5:
#break
#continue
exit()
print(i)

print('hello')

#break
Python的for循环与while语句
#continue
Python的for循环与while语句
exit()
Python的for循环与while语句

3.while语句

while 条件满足:
满足条件执行的语句
else:
不满足条件执行的语句

2、 while 死循环
只要满足 while的条件永远为真,就会进入无限循环
while True:
print('!!!!!!!!!!!!')
3.while嵌套

乘法表
row = 1
while row <= 9:
col = 1
while col <=row:
print('%d %d = %d\t' %(row,col,rowcol),end='')
col += 1
print('')
row += 1

\t:在控制台输出一个制表符,协助我们在输出文本的时候在垂直方向保持对齐
print('1 2 3')
print('10 20 30')
print('1\t2\t3')
print('10\t20\t30')
\n:在控制台输出一个换行符
print('hello\nworld')
\:转译
print('what\'s')

乘法表
Python的for循环与while语句

cro = 9
while cro > 0 :
col = cro
while col > 0 :
print('%d%d=%d\t' %(cro,col,crocol),end='')
col -=1
print('')
cro -=1

Python的for循环与while语句

cro = 9
while cro > 0 :
col = 9
while col > 0 :
if col > cro :
print(' \t' ,end='')
else:
print('%d%d=%d\t' %(cro,col,crocol),end='')
col -=1
print('')
cro -=1
Python的for循环与while语句

cro = 1
while cro <= 9 :
col = 9
while col > 0 :
if cro < col :
print(' \t' ,end='')
else:
print('%d%d=%d\t' %(cro,col,crocol),end='')
col -=1
print('')
cro +=1

Python的for循环与while语句

猜你喜欢

转载自blog.51cto.com/12893781/2400950