avatar

【if while 格式化】笔记整理

elif

name =str(input("输入你想过的节日(情人节,平安夜,生日):"))
if name == "情人节":
print("111")
elif name == "平安夜":
print("222")
elif name == "生日":
print("333")
else:
print("444")

输入你想过的节日(情人节,平安夜,生日):生日
333

if 判断年龄

age = float(input("你的年龄:"))
if age >= 18:
    print("欢迎光临")
else:
    print("你还太小了")

你的年龄:20
欢迎光临

if嵌套

has_ticket = True
knife_length = 19
if has_ticket :
    print("有车票,进安检")
    if knife_length > 20:
        print("不可以通过")
    else:
        print("可以通过")
else:
    print("没有车票,不可以通过")

有车票,进安检
可以通过

while嵌套

i = 1
while i<=9:
    b = 1
    while b <= i:
        #end替换print的换行也可以增加文本
        print("*",end="")
        b +=1
    print("")
    i +=1
*
**
***
****
*****
******
*******
********
*********

while循环

i = 0
while i<5:
    print("hello")
    i +=1
print("循环次数%.2f"%i)

hello
hello
hello
hello
hello
循环次数5.00

while输出乘法表

>>
i  = 1
while i<=9:
    a = 1
    while a <= i:
        print("%d*%d="%(a,i),a*i,end="\t")
        a +=1
    print("")
    i +=1
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
1*5= 5    2*5= 10    3*5= 15    4*5= 20    5*5= 25
1*6= 6    2*6= 12    3*6= 18    4*6= 24    5*6= 30    6*6= 36
1*7= 7    2*7= 14    3*7= 21    4*7= 28    5*7= 35    6*7= 42    7*7= 49
1*8= 8    2*8= 16    3*8= 24    4*8= 32    5*8= 40    6*8= 48    7*8= 56    8*8= 64
1*9= 9    2*9= 18    3*9= 27    4*9= 36    5*9= 45    6*9= 54    7*9= 63    8*9= 72    9*9= 81

while关键字break和contiue

i = 0
while i < 10:
    print(i)
    if i==5:
        break
    i += 1
a = 0
print("******")
while a < 10:
    print(a)
    if a==5:
        a+=1
        continue
    a +=1
0
1
2
3
4
5
******
0
1
2
3
4
5
6
7
8
9

while循环1+100

i= 0
a = 0
while i<=100:
    a += i
    i +=1
print("1+2+3......+100=%d"%a)

1+2+3……+100=5050

文章作者: wangzun233
文章链接: https://wangzun233.top/2019/09/16/%E3%80%90if-while-%E6%A0%BC%E5%BC%8F%E5%8C%96%E3%80%91%E7%AC%94%E8%AE%B0%E6%95%B4%E7%90%86/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 WangZun233