Python elif到嵌套if

Python elif到嵌套if,python,Python,我用elif语句编写了这个程序,我只是想知道如何用嵌套的ifs来代替它 用户必须输入一个数字,程序会告诉他们现在是哪个月,有多少天 month_num = int(input("Enter the number of a month (Jan = 1) : ")) if month_num == 1: print(month_num, "is Feburary, and has 29 days.") elif month_num == 2: print(month_num,

我用elif语句编写了这个程序,我只是想知道如何用嵌套的ifs来代替它

用户必须输入一个数字,程序会告诉他们现在是哪个月,有多少天

month_num = int(input("Enter the number of a month (Jan = 1) : "))

if month_num == 1:
    print(month_num, "is Feburary, and has 29 days.")

elif month_num == 2:
    print(month_num, "is January, and has 31 days.")

elif month_num == 3:
    print(month_num, "is March, and has 31 days.")

elif month_num == 4:
    print(month_num, "is April, and has 30 days.")

elif month_num == 5:
    print(month_num, "is May, and has 31 days.")

elif month_num == 6:
    print(month_num, "is June, and has 30 days.")

elif month_num == 7:
    print(month_num, "is July, and has 31 days.")

elif month_num == 8:
    print(month_num, "is August, and has 31 days.")

elif month_num == 9:
    print(month_num, "is September, and has 30 days.")

elif month_num == 10:
    print(month_num, "is october, and has 31 days.")

elif month_num == 11:
    print(month_num, "is November, and has 30 days.")

elif month_num == 12:
    print(month_num, "is december, and has 31 days.")

else:
    print(month_num, "Is not a valid number")

两者都不是好的解决方案。你最好编一本字典

假设f字符串可用(Python>=3.6)。如果没有,则可以轻松地将其转换为使用
。格式

month_num = int(input("Enter the number of a month (Jan = 1) : "))

d = {1: ('January', 31),
     2: ('February', 29),
     ...
     }

try:
    month_name, num_of_days = d[month_num]
    print(f'{month_num} is {month_name}, and has {num_of_days} days')
except KeyError:
    print(month_num, "Is not a valid number")
还请注意,二月并不总是有29天。

您可以使用,即:



您只是比较单个值,为什么要嵌套
if
(s)?如果使用嵌套
if
s,则
1
2
的结果也会错误,但更不容易更正。您可以,但是你需要更多的if-else语句。我建议你查看字典,而不是嵌套的
if
sie:如果月份不是1,那么如果月份不是2,那么如果月份不是3…,否则打印3,否则打印2,否则打印1你可以使用
monthlen(2020,m)
而不是
monthrange(2020,m)[1]
我不认为
calendar
monthlen
方法,是吗?是的。不知道为什么它没有文档化。我在发表评论之前尝试过它,但python 3.6.8似乎没有。你用的是哪个版本?做了一点调查。它可能是在3.7中引入的,并且应该是“私有的”(前缀为
\uu
):
import calendar as cal
from datetime import date
m = int(input("Enter the number of a month (Jan = 1) : "))
if m in range(1,13):
  print(f"{m} is {cal.month_name[m]} and has {cal.monthrange(date.today().year, m)[1]} days.")
1 is January and has 31 days.
2 is February and has 29 days.
3 is March and has 31 days.
4 is April and has 30 days.
5 is May and has 31 days.
6 is June and has 30 days.
7 is July and has 31 days.
8 is August and has 31 days.
9 is September and has 30 days.
10 is October and has 31 days.
11 is November and has 30 days.
12 is December and has 31 days.