基础练习

基础练习

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

    if count == 7:
        count += 1
        continue
    print(count, end=" ")
    count += 1

  1. 求1-100的所有数的和
sum = 0
for i in range(101):
    sum += i
print(sum)

  1. 输出 1-100 内的所有奇数

    for i in range(1, 101):
        if i % 2 == 1:
            print(i, end=" ")
    
  2. 输出 1-100 内的所有偶数

    count = 1
    while count <= 100:
        if count % 2 == 0:
            print(count, end=" ")
        count += 1
    
  3. 求1-2+3-4+5 ... 99的所有数的和

while count < 100:

    if count % 2 == 0:
        sum -= count
        count += 1
        continue
    sum += count
    count += 1
print(sum)

  1. 用户登陆(三次机会重试)
user = "randysun"
pwd = "123456"

count = 0
while count < 3:
    user_in = input("请输入账户:")
    pwd_in = input("请输入密码:")
    if user_in == user and pwd == pwd:
        print("登录成功")
        break
    else:
        print("账户或密码错误")
    count += 1
    if count == 3:
        print("你没有机会了")
  1. 猜年龄游戏要求: 允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出

    age = 18
    
    for i in range(3):
        age_in = input("请输入您猜的年龄:")
        age_in = int(age_in)
        if age_in == age:
            print("恭喜下你猜对了!")
            break
    
  2. 猜年龄游戏升级版,要求: 允许用户最多尝试3次 每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y,就继续让其猜3次,以此往复,如果回答N或n,就退出程序 如何猜对了,就直接退出

age = 18
count = 0

while True:
    age_in = input("请输入您猜的年龄:")
    age_in = int(age_in)
    if age_in == age:
        print("恭喜下你猜对了!")
        break
    count += 1
    if count == 3:
        print("三次机会已用完!")
        res = input("继续玩输入Y或y,不想玩请输入N或n:")
        if res == "Y" or res == "y":
            count = 0;
        elif res == "N" or res == "n":
            break
  1. for循环打印99乘法表
for i in range(1, 10):
    for j in range(1, i+1):
        print(f"{j} * {i} = {i * j}", end="\t")
    print()

  1. for循环打印金字塔:如下

           *
          ***
         *****
        *******
       *********
    
    for i in range(1, 6):
        print(f'{"*" * (2 * i - 1): ^10}')
    
posted @ 2019-07-17 17:35  RandySun  阅读(198)  评论(0编辑  收藏  举报