for 循环
1.用户输入一个整型数,求该数的阶乘
5 = 5 * 4 * 3 * 2 * 1
num = int(input('Num:'))
res = 1
for i in range(1,num+1):
res *= i
print('%d 的结果是: %d' %(num,res))
跳出循环
break:跳出整个循环,不会再循环后面的内容
continue:跳出本次循环,continue后面的代码不再执行,但是循环依然继续
exit():结束程序的运行
for i in range(10):
if i == 5:
# break
continue
print('hello python')
# exit()
print(i)
print('hello world')
for 循环练习
- 有1,2,3,4四个数字
求这四个数字能生成多少互不相同且无重复数字的三位数(122,133)
count = 0
for i in range(1,5):
for y in range(1,5):
for t in range(1,5):
if i != y and y !=t and t !=i:
print(i*100 + y*10 + t)
count += 1
print(count)
- 用户登陆程序需求:
1. 输入用户名和密码;
2. 判断用户名和密码是否正确? (name=‘root’, passwd=‘westos’)
3. 登陆仅有三次机会, 如果超>过三次机会, 报错提示;
trycount = 0
for i in range(3):
name = input('用户名: ')
password = input('密码: ')
if name == 'root' and password == 'westos':
print('登录成功')
break
else:
print('登录失败')
print('您还剩余%d次机会' %(2-i))
else:
print('登录次数超过3次,请稍后再试!')
while 循环
while 条件():
条件满足时,做的事情1
条件满足时,做的事情2
#1.定义一个变量,记录循环次数
i = 1
#2.开始循环
while i <= 3:
#循环内执行的动作
print('hello python')
#处理计数器
i += 1
while 死循环
while True:
print('hello python')
while 求和
100以内
i = 0
result = 0
while i <= 100:
result += i
i += 1
print(result)
while 嵌套
在控制台连续输出五行*,每行依次递增
*
**
***
****
*****
*****
****
***
**
*
*
**
***
****
*****
*****
****
***
**
*
row1 = 1
while row1 <= 5:
col1 = 1
while row1 >= col1:
print('*',end='')
col1 += 1
print('')
row1 += 1
row = 5
while row >= 1:
col = 1
while col <= row:
print('*',end='')
col += 1
print('')
row -= 1
row2 = 5
while row2 >= 1:
col2 = 1
while row2 > col2:
print(' ',end='')
col2 += 1
while row2 <= col2 and col2 <=5:
print('*',end='')
col2 += 1
print('')
row2 -= 1
row3 = 1
while row3 <= 5:
col3 = 1
while row3 > col3 :
print(' ',end='')
col3 += 1
while row3 <= col3 and col3 <= 5:
print('*',end='')
col3 += 1
print('')
row3 += 1
猜数字
猜数字游戏
- 系统随机生成一个1~100的数字;
- 用户总共有5次猜数字的机会;
- 如果用户猜测的数字大于系统给出的数字,打印“too big”;
- 如果用户猜测的数字小于系统给出的数字,打印"too small";
- 如果用户猜测的数字等于系统给出的数字,打印"恭喜",并且退出循环;
import random
trycount = 0
computer = random.randint(1,100)
print(computer)
while trycount < 5:
player = int(input('Num:'))
if player > computer:
print('too big')
trycount += 1
elif player < computer:
print('too small')
trycount += 1
else:
print('恭喜')
break