Python基础学习003——while循环

"""
1.while循环
2.无限循环
3.猜拳游戏进阶:无限循环版,积分制版
4.求和:求1-100的和,1-100之间的偶数和
"""
import random

# while循环-打印0-100
i = 0                   # 设置计数器
while i <= 100:         # 判断条件
    print(i)            # 执行重复代码
    i += 1              # 改变计数器(不改变计数器会导致死循环)
# 故意写的叫无限循环while True:(一般会在循环中添加if判断,当if成立则break终止循环)
# 非故意写出的叫死循环.
while True:
    print(i)
    i += 1
    if i > 5:
        break


# 猜拳游戏-无限循环版:
while True:
    player = int(input('玩家您好,请您出拳(1石头2剪刀3布0退出游戏),请您输入代号:'))
    computer = random.randint(1, 3)  # 电脑随机出拳,随机产生整数
    if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
        print('恭喜您获胜!')
    elif player == 0:
        print('您主动退出游戏')
        break
    elif player > 3 or player < 0:
        print('请您按照提示,输入符合要求的代号.')
    else:
        print("很遗憾您输了.继续加油吧!")
# 猜拳游戏-积分制版:
score = 0
while score >= 0:
    player = int(input('玩家您好,请您出拳(1石头2剪刀3布0退出游戏),请您输入代号:'))
    computer = random.randint(1, 3)  # 电脑随机出拳,随机产生整数
    if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
        score += 1
        print(f'恭喜您获胜,加一分!\n当前得分{score}')
    elif player == computer:
        print(f"平局,不得分!\n当前得分{score}")
    elif player == 0:
        print('您主动退出游戏')
        break
    elif player > 3 or player < 0:
        print('请您按照提示,输入符合要求的代号.')
    else:
        score -= 1
        print(f"很遗憾您输了.减一分,继续加油吧!\n当前得分{score}")
print('您输光啦!游戏退出!')


# 求1-100的和
sum_num = 0
n = 1
while n <= 100:
    sum_num += n
    n += 1
print('1+2+3+...+100=', sum_num)


# 求1-100之间偶数的和
# 方法1
sum_num2 = 0
n2 = 2
while n2 <= 100:
    sum_num2 += n2
    n2 += 2
print('1+2+4+...+100=', sum_num2)
# 方法2
sum_num3 = 0
n3 = 1
while n3 <= 100:
    if (n3 % 2) == 0:
        sum_num3 += n3
    n3 += 1
print('1+2+4+...+100=', sum_num3)

你可能感兴趣的:(python)