Python은 동적이면서 강타입인 프로그래밍 언어예요. 덕 타이핑과 점진적 타이핑을 모두 사용하고, 타입 힌트를 통해 이를 지원해요. 명령형, 선언형(예: 함수형), 객체 지향 프로그래밍 _스타일_을 모두 지원하지만, 내부적으로는 **Python의 모든 것이 객체**예요.
Python은 코드 가독성을 매우 중시하며, (Haskell과 비슷하게) 함수, 메서드, 클래스 정의를 나타내는 데 의미 있는 들여쓰기를 사용해요.
Python은 Guido van Rossum이 만들었고 1991년에 처음 공개됐어요. Python 소프트웨어 재단이 Python과 CPython 개발을 위한 자원을 관리하고 이끌며, 커뮤니티 구성원이 Python 개선 제안(PEP)을 통해 언어 변경 제안을 내요.
현재 릴리스의 전체 문서는 docs.python.org에서 볼 수 있어요.
이 첫 번째 개념에서는 Python 언어의 네 가지 주요 기능을 소개해요:
def 키워드와 return 키워드),일반적으로 Python 트랙의 콘텐츠, 테스트, 분석 도구는 Python 코드 스타일에 대해 PEP 8과 PEP 257에 설명된 스타일 관례를 따르며, 한 글자짜리 변수 이름을 쓰지 말라는 (강한) 권고가 더해져요.
Python의 선(PEP 20)과 무엇이 Python다운가?에는 추가적인 철학이 담겨 있어요.
Python 트랙에서는 변수를 항상 snake_case로 쓰고, 상수는 SCREAMING_SNAKE_CASE로 써요.
Python에서는 변수나 상수를 만들 때 사용하는 키워드가 없어요.
대신 프로그래머는 할당 = 연산자를 사용해 이름(_변수_라고도 해요)을 모든 타입의 객체에 바인딩할 수 있어요: <name> = <value>.
이름은 사용되는 동안 다른 값(다른 객체 타입)으로 다시 할당하거나 다시 바인딩할 수 있어요.
예를 들어 my_first_variable은 =을 사용해 여러 번 다시 할당할 수 있고, 다시 할당할 때마다 다른 객체 타입을 가리킬 수 있어요:
>>> my_first_variable = 1 # my_first_variable bound to an integer object of value one.
>>> my_first_variable = 2 # my_first_variable re-assigned to integer value 2.
>>> print(type(my_first_variable))
<class 'int'>
>>> print(my_first_variable)
2
>>> my_first_variable = "Now, I'm a string." # <--You may re-bind a name to a different object type and value.
>>> print(type(my_first_variable))
<class 'str'>
>>> my_first_variable = 'You can call me "str".' # <--Strings can be declared using single or double quote marks.
>>> print(my_first_variable)
You can call me "str".
>>> import collections
>>> my_first_variable = collections.Counter([1,1,2,3,3,3,4,5,6,7]) # <--Now my_first_variable has been re-bound to a Counter object.
>>> print(type(my_first_variable))
<class 'collections.Counter'>
>>> print(my_first_variable)
Counter({3: 3, 1: 2, 2: 1, 4: 1, 5: 1, 6: 1, 7: 1})
상수는 프로그램에서 한 번만 할당하도록 의도된 이름이에요.
상수는 모듈(파일) 수준에서 정의해야 하고, 보통 프로그램의 모든 함수와 클래스에서 볼 수 있어요.
SCREAMING_SNAKE_CASE를 사용하면 그 이름을 다시 할당하거나 값을 변경해서는 안 된다는 신호예요.
# All caps signal that this is intended as a constant.
MY_FIRST_CONSTANT = 16
# Re-assignment will be allowed by the compiler & interpreter,
# but this is VERY strongly discouraged.
# Please don't do this, it could create problems in your program!
MY_FIRST_CONSTANT = "Some other value"
Python에서는 기능 단위가 함수로 캡슐화되어 있고, 함수 자체도 객체예요 (끝없이 이어지는 거북이).
함수는 그 자체로 실행할 수 있고, 다른 함수에 인자로 전달할 수 있으며, 중첩할 수 있고, 클래스에 바인딩할 수도 있어요. 함수를 클래스 이름에 바인딩하면 메서드라고 해요. 관련 있는 함수와 클래스(그리고 그 메서드)는 같은 파일이나 모듈에 함께 묶을 수 있고, 다른 프로그램에서 사용하기 위해 일부 또는 전체를 가져올 수 있어요.
def 키워드로 함수 정의를 시작해요.
각 함수는 () 괄호 안에 0개 이상의 형식 매개변수를 가질 수 있고, 그 뒤에 : 콜론이 와요.
함수의 _본문_을 이루는 문은 def 다음 줄부터 시작하고, _블록으로 들여쓰기_해야 해요:
# The body of a function is indented by 2 spaces & prints the sum of the numbers.
def add_two_numbers(number_one, number_two):
total = number_one + number_two
print(total)
>>> add_two_numbers(3, 4)
7
# Inconsistent indentation in your code blocks will raise an error.
>>> def add_three_numbers_misformatted(number_one, number_two, number_three):
... result = number_one + number_two + number_three # This was indented by 4 spaces.
... print(result) # <--This was only indented by 3 spaces.
...
...
File "<stdin>", line 3
print(result)
^
IndentationError: unindent does not match any outer indentation level
함수는 return 키워드를 통해 값이나 객체를 명시적으로 반환해요:
# Function definition on first line, explicit return used on final line.
def add_two_numbers(number_one, number_two):
return number_one + number_two
# Calling the function in the Python shell returns the sum of the numbers.
>>> add_two_numbers(3, 4)
7
# Assigning the function call to a variable and printing
# the variable will also return the value.
>>> sum_with_return = add_two_numbers(5, 6)
>>> print(sum_with_return)
11
return 뒤에 명시적인 표현식이 없는 함수는 None 객체를 암묵적으로 반환해요.
None의 자세한 내용은 나중에 나오는 개념에서 다뤄요.
이 연습 문제와 설명에서는 None을 아무것도 없는 상태, 즉 null을 나타내는 자리 표시자로 생각해요:
# This function will return `None`
def square_a_number(number):
square = number * number
return # <-- note that this return is not followed by an expression
# Calling the function in the Python shell appears
# to not return anything at all.
>>> square_a_number(2)
>>>
# Using print() with the function call shows that
# the function is actually returning the **None** object.
>>> print(square_a_number(2))
None
return을 생략한 함수도 None 객체를 암묵적으로 반환해요.
즉, 함수 안에서 return을 사용하지 않으면 Python이 대신 None 객체를 반환해요.
# This function omits a return keyword altogether
def add_two_numbers(number_one, number_two):
result = number_one + number_two
>>> add_two_numbers(5, 7)
>>> print(add_two_numbers(5, 7))
None
# Assigning the function call to a variable and printing
# the variable will also show None.
>>> sum_without_return = add_two_numbers(5, 6)
>>> print(sum_without_return)
None
함수는 이름 뒤에 ()를 붙여 호출해요.
클래스나 모듈 안에 정의된 함수를 호출할 때는 점(.) 표기법을 사용해요.
>>> def raise_to_power(number, power):
... return number ** power
...
>>> raise_to_power(3,3) # Invoking the function with the arguments 3 and 3.
27
# A mis-match between the number of parameters and the number of arguments will raise an error.
>>> raise_to_power(4,)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: raise_to_power() missing 1 required positional argument: 'power'
# Calling methods or functions in classes and modules.
>>> start_text = "my silly sentence for examples."
>>> str.upper(start_text) # <--Calling the upper() method from the built-in str class on start_text.
'MY SILLY SENTENCE FOR EXAMPLES.'
# Because a string is an instance of the str class, methods can also be called on them "directly".
>>> start_text = "my silly sentence for examples."
>>> start_text.upper() # <--Calling the upper() method on start_text directly.
'MY SILLY SENTENCE FOR EXAMPLES.'
# Alternatively, we can skip the variable assignment (although this gets messy quick).
>>> "my silly sentence for examples.".upper()
'MY SILLY SENTENCE FOR EXAMPLES.'
# Importing the math module
>>> import math
>>> math.pow(2,4) # <--Calling the pow() function from the math module.
16.0
Python의 주석은 문자열의 일부가 아닌 #으로 시작해서 줄 끝에서 끝나요.
다른 많은 프로그래밍 언어와 달리, Python은 여러 줄 주석 기호를 지원하지 않아요.
주석 블록의 각 줄은 # 문자로 시작해야 해요.
주석은 인터프리터가 무시해요:
# This is a single line comment.
x = "foo" # This is an in-line comment.
# This is a multi-line
# comment block over multiple lines --
# these should be used sparingly.
함수 본문의 첫 번째 문은 선택적으로 독스트링이 될 수 있고, 이는 함수나 객체의 목적을 간결하게 요약해 줘요. 독스트링은 코드 블록과 같은 수준으로 들여쓰기한 삼중 큰따옴표(""")로 선언해요:
# An example from PEP257 of a multi-line docstring
# reformatted to use Google style non-type hinted docstrings.
# Some additional details can be found in the Sphinx documentation:
# https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#getting-started
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword Arguments:
real (float): The real part of the number (default 0.0)
imag (float): The imaginary part of the number (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
독스트링은 자동화된 문서 도구가 읽으며, 함수, 메서드, 클래스 이름에 특별한 속성 .__doc__을 호출하면 반환돼요.
문서가 필요한 어떤 크기의 프로그램에도 권장되고, 그 규칙은 PEP257에 정리되어 있어요.
독스트링은 가벼운 단위 테스트로도 기능할 수 있고, PyTest나 doctest 모듈을 가져와서 읽고 실행할 수 있어요.
테스트와 doctest는 나중에 나오는 개념에서 다뤄요.
# An example on a user-defined function using a Google style docstring.
>>> def raise_to_power(number, power):
"""Raise a number to an arbitrary power.
Parameters:
number (int): The base number.
power (int): The power to raise the base number to.
Returns:
int: The number raised to the specified power.
Takes a number and raises it to the specified power, returning the result.
"""
return number ** power
...
# Calling the .__doc__ attribute of the function and printing the result.
>>> print(raise_to_power.__doc__)
Raise a number to an arbitrary power.
Parameters:
number (int): The base number.
power (int): The power to raise the base number to.
Returns:
int: The number raised to the specified power.
Takes a number and raises it to the specified power, returning the result.
...
# Printing the __doc__ attribute of the built-in type: str.
>>> print(str.__doc__)
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to 'utf-8'.
errors defaults to 'strict'.