Python 我不知道这里出了什么问题。我确信这是正确的语法,并且我已经检查了拼写错误

Python 我不知道这里出了什么问题。我确信这是正确的语法,并且我已经检查了拼写错误,python,Python,错误是:“ParseError:bad input on line 17”。这个程序的目的是给出任何日期的星期几。正如你所看到的,它对我为了自己的利益而给出函数的目的感到不满意。我真的觉得我错过了一些东西 这是经过改进的工作版本(感谢您的帮助!) 您可能会因为混合空格和选项卡的问题而出错。尝试使用 # Lists. months = [6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4] weekdays = ["Sunday", "Monday", "Tuesday", "W

错误是:“ParseError:bad input on line 17”。这个程序的目的是给出任何日期的星期几。正如你所看到的,它对我为了自己的利益而给出函数的目的感到不满意。我真的觉得我错过了一些东西

这是经过改进的工作版本(感谢您的帮助!)


您可能会因为混合空格和选项卡的问题而出错。尝试使用

# Lists.
months = [6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",  "Saturday"]

# Fruitful Functions for Algorithm.
def yearcode(y):
    """Year Code Generator Algorithm"""
    y = y % 100
    y = y + (y / 4) % 7
    return int(round(y))

def monthcode(m):
    """Retrieve Month Number from Month List"""
    return months[m - 1]

def daycode(d):
    """Simplify Day Input for Efficiency"""
    return d % 7

# Inputs.
dayin = int(input("What Day in the Month?"))
monthin = int(input("What Month? E.g.- January is 1"))
yearin = int(input("What Year?"))

# Define Variables for Functions.
yearout = yearcode(yearin)
monthout = monthcode(monthin)
dayout = daycode(dayin)

# Final Add-Up and Output.
result = int((dayout + monthout + yearout) % 7)
print(weekdays[result])
看看能不能告诉你什么

也许,只使用模块中的内置函数会更容易


作为补充说明,运行代码时,我没有得到ParseError——我得到了
namererror
,因为没有定义
dayin
。也许您不是有意将其命名为dayayin?

您是否尝试过删除该行并手动重新输入?我经常看到人们,尤其是Mac用户,输入不可见的Unicode字符(如果我没记错的话,请使用alt+space)。这可能是问题的根源。

您应该在monthcode函数体中使用“m”而不是“monthin”

我已经看到一些简单的错误:

可能是使用变量
dayayin
而不是
dayin

>>> import calendar
>>> calendar.weekday(2013,2,18)
0
>>> calendar.day_name[calendar.weekday(2013,2,18)]
'Monday'
在函数
monthcode
中,
mothin
来自哪里

dayayin = int(input("What Day in the Month?"))
...
dayout = daycode(dayin)
编辑: 修正这些后,将
结果
设为整数

def monthcode(m):
    """get month number from month-list"""
    return months[monthin - 1]

脚本将运行,但代码中仍存在一些逐个错误。当我输入出生日期(1978年5月19日)时,它返回星期四,但我出生在星期五。

正如我在另一个答案中指出的,当我输入出生日期时,它给出了一个错误的答案

更具体地说,当您在2013年尝试某个日期时,您的代码会给出正确的答案,但当您尝试将其用于更久远的日期或未来的日期时,返回错误答案的概率为81.76%。除其他外,它没有考虑闰年,也没有补偿不在21世纪的日期

为了弄清楚你哪里出错了,我需要知道你用的是哪种算法。谷歌搜索列表
[6,2,2,5,0,3,5,1,4,6,2,4]
让我看到了(pdf),它有非常详细的描述,但也有一些额外的步骤,你目前在你的算法中有

这是我对该算法的实现。从公历开始到2300年的每一天,我都会根据提供的
日历
解决方案进行检查

result = int((dayout + monthout + yearout) % 7)
导入日期时间
导入日历
月份=[6,2,2,5,0,3,5,1,4,6,2,4]
工作日=[“周日”、“周一”、“周二”、“周三”,
“周四”、“周五”、“周六”、“周日”]
世纪={17:5,
18: 3,
19: 1,
20: 0,
21: -2,
22: -4}
定义每周的第天(日、月、年):
#此算法仅对公历有效
#从1752年9月14日开始。
如果年我同意BioGeek

脚本正在运行,但在您的脚本中仍然存在一些一个接一个的错误 代码。当我输入出生日期(1978年5月19日)时,它会在星期四返回, 但是我出生在星期五

与一些在线计算器相比,您的工作版本似乎要休息一天。e、 g

import datetime
import calendar

months = [6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday", "Sunday"]
centuries = {17: 5,
             18: 3,
             19: 1,
             20: 0,
             21: -2,
             22: -4}

def day_of_week_biogeek(day, month, year):
    # This algorithm is only valid for the Gregorian calendar
    # which began on September 14, 1752.
    if year <= 1752 and month <= 9 and day < 14:
        raise RuntimeError("This algorithm is only valid for the Gregorian " + \  
                           "calendar which began on September 14, 1752.")
    if year >= 2300:
        raise RuntimeError("This algorithm is only valid for the Gregorian " + \
                           "calendar up till December 31, 2299.")


    # Take multiples of 28 from the the last 2 digits of the year
    y = divmod(year, 100)[1] % 28

    # Add a quarter of the nearest multiple of 4 below the number,
    y += divmod(y, 4)[0]

    # Take away 7 or multiples of 7. This leaves us the year code
    y = y % 7

    # The code for the month from the table above
    m = months[month - 1]

    # If it is a leap year AND the month is January or February, subtract 1
    if is_leap_year(year) and month in [1,2]:
        m -= 1

    # Take away 7 or multiples of 7 from the day
    d = day % 7

    # Add the codes for the year, the month and the day
    result = y + m + d

    # Add 1 if the date is in the 1900s
    result += centuries[divmod(year, 100)[0]]

    # Take away 7 or multiples of 7
    result = result % 7

    # The final number indicates day of the week
    return weekdays[result]

def is_leap_year(year):
    # Leap years are the years evenly divisible by 4
    # unless it ends in 00 and is a multiple of 400
    if not year % 400:
        return True
    elif not year % 100:
        return False
    elif not year % 4:
        return True
    return False

# original code by user2080262
def yearcode(y):
    """Year Code Generator Algorithm"""
    y = y % 100
    y = y + (y / 4) % 7
    return int(round(y))

def monthcode(m):
    """Retrieve Month Number from Month List"""
    return months[m - 1]

def daycode(d):
    """Simplify Day Input for Efficiency"""
    return d % 7


def day_of_week_user2080262(dayin, monthin, yearin):
    yearout = yearcode(yearin)
    monthout = monthcode(monthin)
    dayout = daycode(dayin)
    result = int((dayout + monthout + yearout) % 7)
    return weekdays[result]

# alternate solution using builtin functions
def day_of_week_mgilson(day, month, year):
    """ See https://stackoverflow.com/a/14941764/50065"""
    c = calendar.weekday(year, month, day)
    return calendar.day_name[c]

def date_generator(day, month, year):
    """Convience function to return the next day"""
    d = datetime.date(year, month, day)
    while True:
        d += datetime.timedelta(days=1)
        yield d.day, d.month, d.year


if __name__ == '__main__':
    # checking all days from the beginning of the Gregorian
    # calender till 2300
    methods = {'user2080262': day_of_week_user2080262,
               'BioGeek': day_of_week_biogeek}
    for user, func in methods.items():
        checked = 0
        wrong = 0
        d = date_generator(14, 9, 1752)
        for day, month, year in d:
            checked += 1
            if year == 2300:
                break
            if func(day, month, year) != day_of_week_mgilson(day, month, year):
                wrong += 1
        print("The code by {0} gives a wrong answer ".format(user) + \ 
              "{0:.2f}% of the time.".format((float(wrong)/checked)*100))

但是其他的计算器显示它为
星期二

该死,但是我确实在那一行得到了一个解析错误。不过,为打字错误的提醒干杯。@user2080262——修复后,出现了一个
索引器
,因为您使用非整数(
float
)作为索引——可能还有其他错误。@user2080262——另外,尝试以
python-t yourscript.py运行它以检查空格和制表符是否混合。完成后,仍然有一个错误也将
result
更改为
int((dayout+monthout+yearout)%7)
谢谢,我将调整它。这可能是因为舍入操作不正常。如果答案是(在年号中)某物.5,那么它需要汇总。四舍五入不是问题,但这可能就是问题所在。它现在起作用了!谢谢你!现在都修好了,非常好用
result = int((dayout + monthout + yearout) % 7)
import datetime
import calendar

months = [6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday", "Sunday"]
centuries = {17: 5,
             18: 3,
             19: 1,
             20: 0,
             21: -2,
             22: -4}

def day_of_week_biogeek(day, month, year):
    # This algorithm is only valid for the Gregorian calendar
    # which began on September 14, 1752.
    if year <= 1752 and month <= 9 and day < 14:
        raise RuntimeError("This algorithm is only valid for the Gregorian " + \  
                           "calendar which began on September 14, 1752.")
    if year >= 2300:
        raise RuntimeError("This algorithm is only valid for the Gregorian " + \
                           "calendar up till December 31, 2299.")


    # Take multiples of 28 from the the last 2 digits of the year
    y = divmod(year, 100)[1] % 28

    # Add a quarter of the nearest multiple of 4 below the number,
    y += divmod(y, 4)[0]

    # Take away 7 or multiples of 7. This leaves us the year code
    y = y % 7

    # The code for the month from the table above
    m = months[month - 1]

    # If it is a leap year AND the month is January or February, subtract 1
    if is_leap_year(year) and month in [1,2]:
        m -= 1

    # Take away 7 or multiples of 7 from the day
    d = day % 7

    # Add the codes for the year, the month and the day
    result = y + m + d

    # Add 1 if the date is in the 1900s
    result += centuries[divmod(year, 100)[0]]

    # Take away 7 or multiples of 7
    result = result % 7

    # The final number indicates day of the week
    return weekdays[result]

def is_leap_year(year):
    # Leap years are the years evenly divisible by 4
    # unless it ends in 00 and is a multiple of 400
    if not year % 400:
        return True
    elif not year % 100:
        return False
    elif not year % 4:
        return True
    return False

# original code by user2080262
def yearcode(y):
    """Year Code Generator Algorithm"""
    y = y % 100
    y = y + (y / 4) % 7
    return int(round(y))

def monthcode(m):
    """Retrieve Month Number from Month List"""
    return months[m - 1]

def daycode(d):
    """Simplify Day Input for Efficiency"""
    return d % 7


def day_of_week_user2080262(dayin, monthin, yearin):
    yearout = yearcode(yearin)
    monthout = monthcode(monthin)
    dayout = daycode(dayin)
    result = int((dayout + monthout + yearout) % 7)
    return weekdays[result]

# alternate solution using builtin functions
def day_of_week_mgilson(day, month, year):
    """ See https://stackoverflow.com/a/14941764/50065"""
    c = calendar.weekday(year, month, day)
    return calendar.day_name[c]

def date_generator(day, month, year):
    """Convience function to return the next day"""
    d = datetime.date(year, month, day)
    while True:
        d += datetime.timedelta(days=1)
        yield d.day, d.month, d.year


if __name__ == '__main__':
    # checking all days from the beginning of the Gregorian
    # calender till 2300
    methods = {'user2080262': day_of_week_user2080262,
               'BioGeek': day_of_week_biogeek}
    for user, func in methods.items():
        checked = 0
        wrong = 0
        d = date_generator(14, 9, 1752)
        for day, month, year in d:
            checked += 1
            if year == 2300:
                break
            if func(day, month, year) != day_of_week_mgilson(day, month, year):
                wrong += 1
        print("The code by {0} gives a wrong answer ".format(user) + \ 
              "{0:.2f}% of the time.".format((float(wrong)/checked)*100))
What Day in the Month?19
What Month? E.g.- January is 15
What Year?1942
Monday