Files
2025PY/day08/05-while循环的高级练习.py
2025-05-22 16:50:44 +08:00

68 lines
1.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 练习 1模拟银行账户操作
# 编写一个程序来模拟银行账户的操作,用户可以选择存款、取款、查看余额或退出。
balance = 0
while True:
print("\n银行账户操作")
print("1. 存款")
print("2. 取款")
print("3. 查看余额")
print("4. 退出")
choice = input("请输入你的选择: ")
if choice == '1':
amount = float(input("请输入存款金额: "))
if amount > 0:
balance += amount
print(f"存款成功,当前余额: {balance}")
else:
print("存款金额必须为正数。")
elif choice == '2':
amount = float(input("请输入取款金额: "))
if amount > 0 and amount <= balance:
balance -= amount
print(f"取款成功,当前余额: {balance}")
else:
print("取款金额无效或余额不足。")
elif choice == '3':
print(f"当前余额: {balance}")
elif choice == '4':
print("感谢使用,再见!")
break
else:
print("无效的选择,请重新输入。")
# 练习 2猜数字游戏限定次数
# 编写一个猜数字游戏,计算机随机选择一个 1 到 100 之间的数字,用户有 10 次机会猜出这个数字。
import random
number = random.randint(1, 100)
attempts = 0
max_attempts = 10
while attempts < max_attempts:
guess = int(input("猜一个 1 到 100 之间的数字: "))
attempts += 1
if guess < number:
print("猜的数字太小了,再试一次。")
elif guess > number:
print("猜的数字太大了,再试一次。")
else:
print(f"恭喜你,猜对了!你用了 {attempts} 次尝试。")
break
if attempts == max_attempts:
print(f"很遗憾,你已经用完了 {max_attempts} 次尝试。正确的数字是 {number}")