python中的while语句
while用法
while 条件满足:
满足条件执行的语句
else:
不满足条件执行的语句
例:
i=0
sum=0
while i<=100:
sum +=i
i+=1
print(sum)
while死循环
while True:
print('~~~~~~~~~~~~~')
while 2>1:
print('%%%%%')
while嵌套循环
n = int(input('请输入你想打印的行数: '))
i = 0
while i < n:
j = 0
while j <= i:
print('*', end='');
j = j + 1;
print('')
i = i + 1
或者
for i in range(1,10):
for j in range(1,i+1):
print('*',end='')
print('')
row = 1
while row <= 9:
col = 9
while col >= row:
print('*', end='')
col -= 1
print('')
row += 1
row = 1
while row <= 9:
kongge = 1
while kongge <= 9 - row:
print(' ', end='')
kongge += 1
col = 1
while col <= row:
print('*', end='')
col += 1
print('')
row = row + 1
n=int(input('请输入你想打印的行数: '))
row = 1
while row <= n:
kongge = 1
while kongge <= row - 1:
print(' ', end='')
kongge += 1
col = 1
while col <= n - row +1:
print('*', 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\npython')
#
# # \:转义字符
# print('what\'s')
# print("what's")
练习;
猜数字游戏
if , while, break
1. 系统随机生成一个1~100的数字;
** 如何随机生成整型数, 导入模块random, 执行random.randint(1,100);
2. 用户总共有5次猜数字的机会;
3. 如果用户猜测的数字大于系统给出的数字,打印“too big”;
4. 如果用户猜测的数字小于系统给出的数字,打印"too small";
5. 如果用户猜测的数字等于系统给出的数字,打印"恭喜中奖100万",并且退出循环;
import random
computer=random.randint(1,100)
print(computer)
i=0
while i<5:
num = int(input('请输入您要猜的数: '))
if num>computer:
print('too big')
print('您还剩余%d次机会' % (4 - i))
elif num<computer:
print('too small')
print('您还剩余%d次机会' % (4 - i))
else:
print('恭喜中奖')
break
i=i+1
else:
print('登录超过五次,请等待100s后在登录')