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.打印金字塔

1.使用while循环输出1 2 3 4 5 6 8 9 10

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

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

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

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

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

7.猜年龄

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

9.打印九九乘法表

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

10.打印金字塔

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))          
原文地址:https://www.cnblogs.com/wuzhengzheng/p/9652262.html