python while 1_循环 while—1(Python)

循环

while的语法结构

while 条件表达式:

代码指令

while 循环的语法特点:

1、循环必须有初始值

2、必须有条件表达式

3、循环体内有变量的自增或者自减,否则会造成死循环

4、使用条件,往往是使用次数不确定,是依靠循环条件来结束。

5、循环的目的:为了将相似或者相同的代码操作变得更加简洁,使代码可以重复利用

练习 输出1~100之间的数据

i = 100

while i > 0:

print(i)

i = i-1

或者

i = 1

while i <=100:

print(i)

i+=1

分支if...else(python)中猜拳小游戏的改进:

多次运行该游戏,例如:运行3次:

import random

i = 3

while i >0:

people = int(input("请出拳【0:石头;1:剪刀;2:布】:"))

computer = random.randint(0,2)

if people == 0 and computer == 1:

print("你赢了")

pass

elif people == 1 and computer == 2:

print("你赢了,厉害了")

pass

elif people == 2 and computer == 0:

print("你真厉害,你赢了")

pass

elif people==computer:

print("打成平手了")

pass

else:

print("你输了")

pass

i=i-1

循环的嵌套

打印乘法表

# while循环的嵌套

# 练习:打印9*9的乘法表

row = 9

while row >= 1:

col = 1

while col <= row:

F = col * row

print("%d*%d=%d"%(col,row,F), end = " ") # end = " ",表示不换行,Python中print的输出默认是换行的。

col = col+1

print() # 打印完一行后是需要换行的,所以在此处加上print()

row = row-1

结果

9*9乘法表

可以换一个方向

row = 1

while row <= 9:

col = 1

while col <= row:

F = col * row

print("%d*%d=%d"%(col,row,F), end = " ") # end = " ",表示不换行,Python中print的输出默认是换行的。

col = col+1 #col+=1

print() # 打印完一行后是需要换行的,所以在此处加上print()

row = row+1 #row+=1

9*9乘法表

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值