关于函数global
def judge_year(year):if year % 4 == 0:
if year % 400 == 0:
year_name = 366# 'a leap year'
elif year % 100 == 0:
year_name = 365# 'not a leap year'
else:
year_name = 366# 'a leap year'
else:
year_name = 365# 'a leap year'
return year_name
def ordinaldate(year, month, day):
JAN =
MAR =
APR =
MAY =
JUN =
JUL =
AUG =
SEP =
OCT =
NOV =
DEC =
if judge_year(year) == 366:
FEB =
else:
FEB =
if month == JAN:
cumulative_monthly_days = 0
ordinal_date = cumulative_monthly_days + day
elif month == FEB:
cumulative_monthly_days = JAN
ordinal_date = cumulative_monthly_days + day
elif month == MAR:
cumulative_monthly_days = JAN + FEB
ordinal_date = cumulative_monthly_days + day
elif month == APR:
cumulative_monthly_days = JAN + FEB + MAR
ordinal_date = cumulative_monthly_days + day
elif month == MAY:
cumulative_monthly_days = JAN + FEB + MAR + APR
ordinal_date = cumulative_monthly_days + day
elif month == JUN:
cumulative_monthly_days = JAN + FEB + MAR + APR + MAY
ordinal_date = cumulative_monthly_days + day
elif month == JUL:
cumulative_monthly_days = JAN + FEB + MAR + APR + MAY + JUN
ordinal_date = cumulative_monthly_days + day
elif month == AUG:
cumulative_monthly_days = JAN + FEB + MAR + APR + MAY + JUN + JUL
ordinal_date = cumulative_monthly_days + day
elif month == SEP:
cumulative_monthly_days = JAN + FEB + MAR + APR + MAY + JUN + JUL \
+ AUG
ordinal_date = cumulative_monthly_days + day
elif month == OCT:
cumulative_monthly_days = JAN + FEB + MAR + APR + MAY + JUN + JUL \
+ AUG + SEP
ordinal_date = cumulative_monthly_days + day
elif month == NOV:
cumulative_monthly_days = JAN + FEB + MAR + APR + MAY + JUN + JUL \
+ AUG + SEP + OCT
ordinal_date = cumulative_monthly_days + day
elif month == DEC:
cumulative_monthly_days = JAN + FEB + MAR + APR + MAY + JUN + JUL \
+ AUG + SEP + OCT + NOV
ordinal_date = cumulative_monthly_days + day
return ordinal_date
def main():
year = int(input('please enter the year:'))
month = int(input('please enter the month:'))
day = int(input('please enter the day:'))
print('The ordinal date is', ordinaldate(year, month, day))
if __name__ == '__main__':
main()
在这里的第73行,在pycharm里面一直让我添加global条件,添加之后报错,不添加程序正常运行,只是显示一个warning,这个怎么解决?怎么解释?
return ordinal_date
本帖最后由 suchocolate 于 2021-10-16 16:58 编辑
他是怕你程序没有进入if,导致变量最后没有定义。所以你在函数开始设置一下初始值即可,不用global定义。
另外你的这个程序用字典就能简化很多。 suchocolate 发表于 2021-10-16 16:56
他是怕你程序没有进入if,导致变量最后没有定义。所以你在函数开始设置一下初始值即可,不用global定义。
...
我这个值只在这个函数里面,我觉得也不用global来进行规定 本帖最后由 suchocolate 于 2021-10-16 17:12 编辑
1005663861 发表于 2021-10-16 17:09
我这个值只在这个函数里面,我觉得也不用global来进行规定
是不需要global,但是需要有一个默认值,防止逻辑上的bug。写程序要严谨,pycharm虽然有时提示的似乎不是问题的原因,但还是能反映出代码上的一些问题。
建议你看一下leetcode上的这道题的解决方法:https://leetcode-cn.com/problems/day-of-the-year/ 温馨建议:Python 3.10.0 新增 match case 功能,能够帮助你的代码更整洁易读一些
页:
[1]