天天看點

python基礎:if判斷與流程控制案例

本文目錄:

1.使用while循環輸出1 2 3 4 5 6 8 9 10

2.求1-100的所有數的和

3.輸出1-100以内的所有奇數

4.輸出1-100以内的所有偶數

5.求1-2+3-4+5...99的所有數的和

6:使用者登入(三次機會重試)

7.猜年齡

8.猜年齡,三次以後還有機會,也可以放棄機會

9.列印九九乘法表

10.列印金字塔

count = 0
while count < 11:
    if count == 7:
        count += 1
        continue
    print(count)
    count += 1      

s = 0
count = 0
while count <= 100:
    s = s + count
    count += 1
print(s)      

3.輸出1-100内的所有奇數

for i in range(1, 100, 2):
    print(i)      

4.輸出1-100内的所有偶數

res = 1
while res <= 100:
    if res % 2 == 0:
        print(res)
    res += 1      

e = 1
s = 0
while e < 100:
    if e % 2 == 0:
        s -= e
    else:
        s += e
    e += 1
print(s)      

6.使用者登入(三次機會重試)

count = 0
while count<3:
    name = input('your name---')
    pwd = input('your password---')
    if name == 'tom' and pwd == '123':
        print('login successful')
        break
    else:
        print('user or password is error!')
    count += 1      

count = 0
while count < 3:

    age = input('my age?-----')
    if age =='18':
        print('恭喜答對了!')
        break
    else:
        print('再來!')
        count += 1      

8.猜年齡,三次以後還有機會,也可以放棄機會!

age_of_boy = 18
count = 1
while True:
    guess = int(input('猜我的年齡----'))

    if count == 3:
        choice = input('三次機會已用完,y繼續/n結束?')
        if choice =='y':
            count = 1
            continue
        else:
            break

    if guess == age_of_boy:
        print('恭喜猜對了!')
        break
    else:
        print('猜錯了!再來!')
        count += 1      

for i in range(1,10):
    for j in range(1, i + 1):
        print('%s*%s=%s' % (j,i,i*j),end = ' ')
    print()      

for i in range(1,10):
    result=[]
    for j in range(1,i+1):
        result.append(j)
    for j in range(i-1,0,-1):
        result.append(j)
    result=''.join(str(x) for x in result)
    print("{0:^17}".format(result))