我的代码没有提供输出,我预计会有一些数字

时间:2013-06-12 17:32:19

标签: python loops python-3.x while-loop

我期待一些数字作为上述代码的输出,但我没有把它拿出来。 我是python的新手,但开始用PHP编写代码。 对不起,如果我在某些地方出错了。谢谢

# By Websten from forums
#
# Given your birthday and the current date, calculate your age in days.
# Compensate for leap days.
# Assume that the birthday and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is 2 Jan 2012
# you are 1 day old.
#
# Hint
# A whole year is 365 days, 366 if a leap year.
def nextDay(year, month, day):
    """Simple version: assume every month has 30 days"""
    if day < 30:
        return year, month, day + 1
    else:
        if month == 12:
            return year + 1, 1, 1
        else:
            return year, month + 1, 1

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    """Returns the number of days between year1/month1/day1
      and year2/month2/day2. Assumes inputs are valid dates
      in Gergorian calendar, and the first date is not after
      the second."""
    num = 0

    # YOUR CODE HERE!
    yearx = year1
    monthx = month1
    dayx = day1

    while ((year2 >= year1 ) and ( month2 >= month1 ) and ( day2 >= day1 ) ) :
         yearx,monthx,dayx = nextDay(yearx,monthx,dayx)
         num = num + 1
    num = '5'
    return num 

print daysBetweenDates(2012,9,30,2012,10,30)

3 个答案:

答案 0 :(得分:1)

我从来没有掌握Python中的while语句,但我认为这是你的无限循环,第二天总是如此&gt; day1等因此,条件仍然正确,因此你会遇到num increase

会发生什么 - 您收到任何错误消息吗?

如果我这样做,我会设置函数来确定

  1. 如果岁月相同
  2. 如果年份相同则计算它们之间的天数
  3. 如果年份不同,则计算该特定年份的第一个日期和年末之间的天数
  4. 计算第二个日期年初至第二个日期之间的天数
  5. 计算第一年结束与第二年结束之间的年数差异并将其转换为天数
  6. 它可能很笨重,但它应该让你回家

答案 1 :(得分:1)

您需要更改一行:

  

while((year2&gt; = year1)和(month2&gt; = month1)和(day2&gt; = day1)):

为:

  

while((year2&gt; = yearx)和(month2&gt; = monthx)和(day2&gt; = dayx)):

因为您没有更改代码中month1的值,而是更改monthx的值。

另外,我认为你的while循环会在dayx比第二天更好的时候中断,所以你的测量结果会被1点关闭。

答案 2 :(得分:0)

这是我在一个功能中的解决方案

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
##
# Your code here.
##
a1=str(month1)+'/'+str(day1)+'/'+str(year1)
date1 = datetime.strptime(a1, '%m/%d/%Y')

a2=str(month2)+'/'+str(day2)+'/'+str(year2)
date2 = datetime.strptime(a2, '%m/%d/%Y')

result= (date2 - date1).days
return result