您的代码已经基本实现了星座计算器的功能,但还有一些细节需要完善。

  1. 星座计算函数:

    • calculate_constellation 函数中,应该先判断月份是否在有效范围内(1-12),并在不满足条件时返回 None。
    • calculate_constellation 函数中,应该先判断日期是否在有效范围内(1-31),并在不满足条件时返回 None。
    • calculate_constellation 函数中,应该在所有的日期判断条件都不满足时,返回默认的星座名称(例如:"未知")。
  2. 生肖计算函数:

    • calculate_zodiac 函数中,应该先判断年份是否在有效范围内(1900-2099),并在不满足条件时返回 None。
    • calculate_zodiac 函数中,应该在年份不在有效范围内时,返回默认的生肖名称(例如:"未知")。
  3. 组件显示顺序:

    • 在页面布局中,应该先显示生肖名称,再显示星座名称。

完善后的代码如下:

import streamlit as st

# 星座名称和日期范围
constellations = {
    "白羊座": ((3, 21), (4, 19)),
    "金牛座": ((4, 20), (5, 20)),
    "双子座": ((5, 21), (6, 21)),
    "巨蟹座": ((6, 22), (7, 22)),
    "狮子座": ((7, 23), (8, 22)),
    "处女座": ((8, 23), (9, 22)),
    "天秤座": ((9, 23), (10, 23)),
    "天蝎座": ((10, 24), (11, 22)),
    "射手座": ((11, 23), (12, 21)),
    "摩羯座": ((12, 22), (1, 19)),
    "水瓶座": ((1, 20), (2, 18)),
    "双鱼座": ((2, 19), (3, 20))
}

# 生肖名称和起始年份
zodiacs = {
    "鼠": 1900,
    "牛": 1901,
    "虎": 1902,
    "兔": 1903,
    "龙": 1904,
    "蛇": 1905,
    "马": 1906,
    "羊": 1907,
    "猴": 1908,
    "鸡": 1909,
    "狗": 1910,
    "猪": 1911
}

def calculate_constellation(birth_date):
    month, day = birth_date.month, birth_date.day
    if month < 1 or month > 12:
        return None
    if day < 1 or day > 31:
        return None
    for constellation, date_range in constellations.items():
        start_date, end_date = date_range
        if (month == start_date[0] and day >= start_date[1]) or (month == end_date[0] and day <= end_date[1]):
            return constellation
    return "未知"

def calculate_zodiac(birth_year):
    if birth_year < 1900 or birth_year > 2099:
        return None
    for zodiac, start_year in zodiacs.items():
        if birth_year >= start_year:
            return zodiac
    return "未知"

# 页面布局
st.title("星座计算器")

birth_date = st.date_input("请选择您的出生日期")
if birth_date:
    zodiac = calculate_zodiac(birth_date.year)
    constellation = calculate_constellation(birth_date)

    if zodiac:
        st.write(f"您的生肖是:{zodiac}")
    else:
        st.write("请输入有效的出生日期")

    if constellation:
        st.write(f"您的星座是:{constellation}")
    else:
        st.write("请输入有效的出生日期")

请注意,这里我做了一些假设和调整:

  • 我将不满足条件时的返回值从 None 改为了 "未知"。
  • 我假设年份的有效范围是 1900-2099。

如果有其他需求或问题,请随时告诉我。

import streamlit as st# 星座名称和日期范围constellations = 白羊座 3 21 4 19 金牛座 4 20 5 20 双子座 5 21 6 21 巨蟹座 6 22 7 22 狮子座 7 23 8 22 处女座 8 23 9 22 天秤座 9 23 10 23 天蝎座 10 24 11 22 射手座 11

原文地址: http://www.cveoy.top/t/topic/jcVf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录