书写技术成长之路

Python 未指定编码导致的问题

# VarArgs parameters - 变长参数
# Sometimes you might want to define a function that can take any number of parameters.
# variable number of arguments, this can be achieved by using the stars

def total(a=5, *numbers, **phonebook):
    print('a', a)

    # iterate through all the items in tuple
    for single_item in numbers:
        print('signle_item', single_item)

    # iterate through all the items in dictionary
    for first_part, second_part in phonebook.items():
        print(first_part, second_part)

print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))

程序中含有中文字符,运行程序的时候直接报这个错误

SyntaxError: Non-ASCII character '\xe5' in file function_varargs.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

上网查了下是由于编码问题导致的,需要在文件开头声明编码类型 # -*- coding: utf-8 -*-

也就是这样

# -*- coding: utf-8 -*-
# VarArgs parameters - 变长参数
# Sometimes you might want to define a function that can take any number of parameters.
# variable number of arguments, this can be achieved by using the stars

def total(a=5, *numbers, **phonebook):
    print('a', a)

    # iterate through all the items in tuple
    for single_item in numbers:
        print('signle_item', single_item)

    # iterate through all the items in dictionary
    for first_part, second_part in phonebook.items():
        print(first_part, second_part)

print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))