05-条件循环语句

1.条件语句:

形式:

  
if 判断语句 :
    执行语句1
elif 判断语句2
    执行语句2
elif 判断语句3
    执行语句3
#...
else:
    执行语句4
    
占位符 pass

意义:

if(如果) A :
    B(当ATrue
elif(或者) C :
    D(当AFalse并且CTrue
else(否则) :
    E(当AC都为False

2.循环语句

1.while循环

while 判断语句A:
    执行语句B
else
    print('程序正常结束,执行else')
 

注意:循环要有终止条件

2.break和continue

while True:
    break   #终止循环
    continue  #跳过本次循环
    
#break 会终止循环,循环不再执行
#continue是跳过本次循环,循环继续
 

3.range

range(10) #表示0 - 9 这个范围
range(1,10) #表示 1 - 9这个范围
range(1,10,2) #表示 1 - 9这个范围,并且以步长2进行取数

4.for循环

for item in iterable:
    执行语句
else:
  print('程序正常结束,执行else')
#循环条件可以是任何可迭代的对象,如:序列类型,集合和字典
 

5.else

while True:
break
else:
print('OK')

#for
for item in iterable:
break
else:
print('OK')

"""
只有正常结束的循环,非break结束的循环才会执行else部分
"""

作业:

#1.写一个猜数字的游戏,要求:系统生成一个随机数(1-10),用户有3次机会,输入数字去猜。
# 如果输入数 小了 或者 大了,都给于相应提示。如果输入数 与 随机数相等,就提示“ 恭喜您猜对了!”

import random
password = random.randint(1,10)
guess = 0
count = 0
print("----猜数字游戏开始!----")
while guess != password:
number = input("亲,请输入数字(1-10):")
guess = int(number)
if guess > password:
print("您猜的数字太大,请重新输入!")
elif guess < password:
print("您猜的数字太小,请重新输入!")
else:
print("恭喜您!您猜中了!")
count = count +1
if count == 3:
a = input("亲,您的三次机会已用完!是否继续 (y: 继续 任意键: 结束)")
if a.lower() == 'y':
count == 0

#2.输出9*9 乘法口诀

'''
1*1 =1
1*2 =2 2*2 =4
1*3 =3 2*3 =6 3*3 =9
1*4 =4 2*4 =8 3*4 =12 4*4 =16

'''
print("**********九九乘法表**********")
for i in range(1,10):
for j in range(1,i+1):
print("%d*%d=%2d"%(i,j,i*j),end = " ")
print("")

原文地址:https://www.cnblogs.com/Jack-Ma/p/8644794.html