import math import datetime def guess_number(answer): while True: guess = int(input("请猜一个数字: ")) if guess == answer: print("恭喜你,猜对了!") break elif guess > answer: print("太大了,请猜小一点。") else: print("太小了,请猜大一点。") def factorial_sum(n): sum = 0 for i in range(1, n+1): fact = math.factorial(i) print(f"{i}! = {fact}") sum += fact print(f"{n}! 的和为 {sum}") def case_conversion(s): result = "" for c in s: if c.isupper(): result += c.lower() elif c.islower(): result += c.upper() else: result += c print(result) def calculate_age_and_zodiac(year): current_year = datetime.datetime.now().year age = current_year - year zodiacs = ["猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊"] zodiac_index = (year - 1900) % 12 zodiac = zodiacs[zodiac_index] print(f"你的年龄是{age}岁,生肖是{zodiac}。")给这个代码增加选择功能
时间: 2024-03-03 08:49:03 浏览: 65
好的,我可以为这个代码增加一个选择功能,让用户选择要执行的函数。下面是修改后的代码:
```
import math
import datetime
def menu():
print("请选择要执行的操作:")
print("1. 猜数字游戏")
print("2. 求阶乘和")
print("3. 大小写互换")
print("4. 计算年龄和生肖")
choice = input("请输入选择的数字:")
return int(choice)
def guess_number(answer):
while True:
guess = int(input("请猜一个数字: "))
if guess == answer:
print("恭喜你,猜对了!")
break
elif guess > answer:
print("太大了,请猜小一点。")
else:
print("太小了,请猜大一点。")
def factorial_sum(n):
sum = 0
for i in range(1, n+1):
fact = math.factorial(i)
print(f"{i}! = {fact}")
sum += fact
print(f"{n}! 的和为 {sum}")
def case_conversion(s):
result = ""
for c in s:
if c.isupper():
result += c.lower()
elif c.islower():
result += c.upper()
else:
result += c
print(result)
def calculate_age_and_zodiac(year):
current_year = datetime.datetime.now().year
age = current_year - year
zodiacs = ["猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊"]
zodiac_index = (year - 1900) % 12
zodiac = zodiacs[zodiac_index]
print(f"你的年龄是{age}岁,生肖是{zodiac}。")
while True:
choice = menu()
if choice == 1:
answer = int(input("请输入答案数字:"))
guess_number(answer)
elif choice == 2:
n = int(input("请输入一个整数:"))
factorial_sum(n)
elif choice == 3:
s = input("请输入一个字符串:")
case_conversion(s)
elif choice == 4:
year = int(input("请输入出生年份:"))
calculate_age_and_zodiac(year)
else:
print("选择无效,请重新选择。")
```
现在,当用户运行程序时,会先出现一个菜单,用户可以选择要执行的函数。根据用户的选择,程序会执行对应的函数。如果选择无效,程序会提示用户重新选择。
阅读全文