- while循环:
初始条件设置 —— 通常是重复执行的计数器
while 条件(判断计数器是否达到目标次数):
条件满足时,做的事情1
条件满足时,做的事情2
条件满足时,做的事情3
处理条件(计数器 + 1)
-
while循环语句有冒号:
-
while循环体要缩进
-
while循环要设置循环初始条件和相关变量的计数(一般用复合赋值运算符)
- 复合赋值运算符:
-
+= 加法赋值运算符 c += a 等效于 c = c + a
-
-= 减法赋值运算符 c -= a 等效于 c = c - a
-
*= 乘法赋值运算符 c *= a 等效于 c = c * a
-
/= 除法赋值运算符 c /= a 等效于 c = c / a
-
//= 取整除赋值运算符 c //= a 等效于 c = c // a
-
%= 取模(余数)赋值运算符 c %= a 等效于 c = c % a
-
**= 幂赋值运算符 c **= a 等效于 c = c ** a
- continue和break
-
break:满足某项要求,退出整个循环
-
continue:满足某项要求,退出当次循环
- 转义字符\(为了能在Python中打出特殊的字符,必须使用转义字符)
\\ 反斜杠符号
\' 单引号
\" 双引号
\n 换行
- 随机数(random库)
1.产生大于等于n,小于等于m的一个随机数:
import random
a=random.randint(n,m)
2.产生大于0,小于1的浮点数:
import random
b=random.random()
作业1: 通过while循环完成“人机猜拳”的游戏制作,通过10次猜拳统计最终是机器获胜、人获胜还是打成平局,中途可以按0退出。如果用户输入的不是石头、剪刀和布,会反复提示用户输入正确的内容
import random
i=1
count=0
countperson=0
countcomputer=0
while i<=10:
person=input('您出拳:(石头,剪刀,布)')
while person!='石头'and person!='剪刀'and person!='布':
person = input('您出拳:(石头,剪刀,布)')
computer=''
r=random.randint(1,3)
if r==1:
computer='石头'
elif r==2:
computer='剪刀'
else:
computer='布'
print('机器出拳:%s'%computer)
if computer==person:
print('第%d次出拳:平局'%i)
count+=1
elif computer=='石头'and person=='布'or computer=='剪刀'and person=='石头'or computer=='布'and person=='剪刀':
print('第%d次出拳:您胜出'%i)
countperson+=1
else:
print('第%d次出拳:机器获胜' % i)
countcomputer += 1
choose=input('按0退出,按1继续:')
if choose=='0':
break
i+=1
print('您胜出%d次,机器胜出%d次,平局%d次'%(countperson,countcomputer,count))
if countperson>countcomputer:
print('您获得胜利')
elif countperson==countcomputer:
print('平局')
else:
print('机器获胜')
您出拳:(石头,剪刀,布)石头
机器出拳:剪刀
第1次出拳:您胜出
按0退出,按1继续:1
您出拳:(石头,剪刀,布)剪刀
机器出拳:石头
第2次出拳:机器获胜
按0退出,按1继续:
作业2:根据输入的菱形的上面三角形的行数(菱形边长),绘制菱形,每打印一个星后跟一个空格
rows=int(input('输入菱形边长:'))
i=1
while i<=rows:
j=1
while j<=(rows-i):
print(' ',end='')
j+=1
k=1
while k<=i:
print('* ',end='')
k+=1
print()
i+=1
bottom=rows-1
while bottom>0:
j=1
while bottom+j<=rows:
print(' ',end='')
j+=1
k=1
while k<=bottom:
print('* ',end='')
k+=1
print()
bottom-=1
输入菱形边长:4
*
* *
* * *
* * * *
* * *
* *
*