【问题标题】:Why does my code keep repeating the question prompt instead of progressing to the conditional statements?为什么我的代码不断重复问题提示而不是进入条件语句?
【发布时间】:2021-10-15 11:57:47
【问题描述】:

当我运行我的代码时,即使输入与条件语句匹配,它也会不断迭代思考 while 循环的开始。当我输入“y”时,它会重复输入“l”或输入“e”的问题提示

intro = "Welcome to the leap year Calculator\n"
print(intro)
leapyear = True
def leap_year_calc():
    test= input("What year are you checking? ")
    year = int(test)
    if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0):
       prompt = str(year) + " Is a leap year"
       print (prompt)
       return leapyear == True
    else:
       prompt = str(year) + " Isn't a leap year"
       print (prompt)
       return leapyear == True
def leap_year_list():
    leap_years = []
    for i in range(4001):
        if i >= 1752: #this was the 1st leap year in th Gregorian calender
            if ((i % 4 == 0) and (i % 100 != 0)) or (i % 400 == 0):
                leap_years.append(i)
        else:
           pass
    print(leap_years)
    return leap_years

while leapyear != False:
     question = input("Do you want to know if a year is a leap year(type 'y'), \nor see a list of leap years(type 'l') or exit (type 'e'? ").lower
     if question == 'y':
        leap_year_calc()
     elif question == 'l':
        leap_year_list()
     else:
        leapyear == False

#leap_year_calc()
#leap_year_list()

【问题讨论】:

  • 请使用 4 空格缩进。它有助于区分几个代码块
  • 您可以尝试删除很多 else 语句。

标签: python function while-loop conditional-statements


【解决方案1】:

而不是做:

while leapyear != False:
      question = input("Do you want to know if a year is a leap year(type 'y'), \nor see a list of leap years(type 'l') or exit (type 'e'? ").lower
      if question == 'y':
        leap_year_calc()
      elif question == 'l':
        leap_year_list()

做:

while leapyear:
      question = input("Do you want to know if a year is a leap year(type 'y'), \nor see a list of leap years(type 'l') or exit (type 'e'? ").lower
      if question == 'y':
        leap_year_calc()
      elif question == 'l':
        leap_year_list()
      else:
        leapyear = False

【讨论】:

  • 你在.lower后面漏掉了括号,应该是.lower()
【解决方案2】:

您在下部函数中缺少 ():

question = input("Do you want to know if a year is a leap year(type 'y'), \nor see a list of leap years(type 'l') or exit (type 'e'? ").lower()

【讨论】:

  • 这不是他们问题的原因,尽管这可能会引发异常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 2014-06-03
  • 2016-12-08
相关资源
最近更新 更多