4.3 파이썬 언어에 대한 시작

저자:선함, 2019-04-28 09:55:02에 생성, 업데이트:

초기

그래서, 당신은 파이썬 프로그래밍 언어를 배우고 싶지만 간결하고 아직 완전한 튜토리얼을 찾을 수 없습니다. 이 튜토리얼은 10 분 안에 파이썬을 가르치려고 노력할 것입니다. 그것은 아마도 튜토리얼과 속임수 시트 사이의 교차이기 때문에 튜토리얼이 아닙니다. 따라서 시작하기 위해 몇 가지 기본 개념을 보여줄 것입니다. 분명히, 당신이 정말로 언어를 배우고 싶다면 잠시 동안 프로그래밍을해야합니다. 나는 당신이 이미 프로그래밍에 익숙하다고 가정하고 따라서 언어 특이없는 대부분의 것을 건너뛰을 것입니다. 중요한 키워드는 쉽게 발견 할 수 있도록 강조 될 것입니다. 또한, 이 튜토리얼의 간결성으로 인해 일부 사항은 코드에 직접 소개되고 간단히 언급 될 것입니다.

우리는 파이썬 3에 집중할 것입니다. 왜냐하면 그것이 여러분이 사용해야 할 버전이기 때문입니다. 책에 있는 모든 예제는 파이썬 3에 있고, 만약 누군가가 여러분에게 2를 사용하라고 조언한다면, 그들은 여러분의 친구가 아닙니다.

성질

파이썬은 강력한 타입 (즉 타입이 강제된다), 동적, 암시 타입 (즉 변수를 선언할 필요가 없다), 대소변 민감 (즉 var와 VAR는 두 가지 다른 변수) 및 객체 지향 (즉 모든 것이 객체이다) 이다.

도움 을 구하는 것

파이썬의 도움말은 항상 인터프리터에서 바로 사용할 수 있습니다. 만약 당신이 어떤 객체가 어떻게 작동하는지 알고 싶다면, 당신이 해야 할 일은 help (() 를 호출하는 것입니다! 또한 유용한 것은 dir() 입니다. 이 방법은 모든 객체의 메소드를 보여줍니다.닥터, 문서 문자열을 보여줍니다:

>>> help(5)
Help on int object:
(etc etc)

>>> dir(5)
['__abs__', '__add__', ...]

>>> abs.__doc__
'abs(number) -> number

Return the absolute value of the argument.

문법

파이썬에는 의무적인 문장 종료 문자가 없으며 블록은 힌트를 통해 지정됩니다. 블록을 시작하기 위해 힌트를 입력하고, 하나를 끝내는 데 힌트를 입력합니다. 힌트 레벨을 기대하는 문장은 두 단점 (:) 으로 끝납니다. 댓글은 파운드 (#) 기호로 시작되며 단일 라인이며, 멀티 라인 문자열은 멀티 라인 댓글에 사용됩니다. 값은 동일 기호 (=) 로 할당되며 (사실, 객체는 이름에 묶여 있습니다) 동등 기호 (=) 를 사용하여 평등 테스트가 수행됩니다. += 및 -= 연산자를 사용하여 각각 오른쪽 금액으로 값을 증가 / 감소시킬 수 있습니다. 이것은 문자열을 포함한 많은 데이터 타입에서 작동합니다. 또한 한 줄에 여러 변수를 사용할 수 있습니다. 예를 들어:

>>> myvar = 3
>>> myvar += 2
>>> myvar
5
>>> myvar -= 1
>>> myvar
4
"""This is a multiline comment.
The following lines concatenate the two strings."""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print(mystring)
Hello world.
# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
>>> myvar, mystring = mystring, myvar

데이터 타입

파이썬에서 사용할 수 있는 데이터 구조는 목록, 튜플 및 사전입니다. 세트는 세트 라이브러리에서 사용할 수 있습니다. 목록은 1 차원 배열과 같습니다 (하지만 다른 목록의 목록도 가질 수 있습니다), 사전은 연관 배열 (해시 테이블이라고도 불립니다) 이며 튜플은 변수가 변하지 않는 1 차원 배열입니다. 사용 방법은 다음과 같습니다.

>>> sample = [1, ["another", "list"], ("a", "tuple")]
>>> mylist = ["List item 1", 2, 3.14]
>>> mylist[0] = "List item 1 again" # We're changing the item.
>>> mylist[-1] = 3.21 # Here, we refer to the last item.
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.15 # This is how you change dictionary values.
>>> mytuple = (1, 2, 3)
>>> myfunction = len
>>> print(myfunction(mylist))
3

두 단점 (:) 을 사용하여 배열 범위에 액세스 할 수 있습니다. 시작 인덱스를 비어두고 첫 번째 항목을 가정하고, 끝 인덱스를 남겨두고 마지막 항목을 가정합니다. 인덱싱은 포괄적-특수적이므로 [2:10]을 지정하면 항목이 반환됩니다.

>>> mylist = ["List item 1", 2, 3.14]
>>> print(mylist[:])
['List item 1', 2, 3.1400000000000001]
>>> print(mylist[0:2])
['List item 1', 2]
>>> print(mylist[-3:-1])
['List item 1', 2]
>>> print(mylist[1:])
[2, 3.14]
# Adding a third parameter, "step" will have Python step in
# N item increments, rather than 1.
# E.g., this will return the first item, then go to the third and
# return that (so, items 0 and 2 in 0-indexing).
>>> print(mylist[::2])
['List item 1', 3.14]

문자열

문자열은 단일 또는 이중 인용구를 사용할 수 있으며 다른 종류의 문자열을 사용하는 문자열 안에 한 종류의 인용구를 가질 수 있습니다.트리플 더블 (또는 싱글) 코팅(). 파이썬 문자열은 항상 유니코드이지만 순수 바이트인 또 다른 문자열 유형이 있습니다. 그것들은 bystrings라고 불리며 b 접두어로 나타납니다. 예를 들어 bHello \xce\xb1. 값으로 문자열을 채우려면 % (modulo) 연산자와 튜플을 사용합니다. 각 %s는 튜플의 항목으로 왼쪽에서 오른쪽으로 대체되며 또한 다음과 같이 사전 대체를 사용할 수 있습니다.

>>> print("Name: %s\
Number: %s\
String: %s" % (myclass.name, 3, 3 * "-"))
Name: Stavros
Number: 3
String: ---

strString = """This is
a multiline
string."""

# WARNING: Watch out for the trailing s in "%(key)s".
>>> print("This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"})
This is a test.

>>> name = "Stavros"
>>> "Hello, {}!".format(name)
Hello, Stavros!
>>> print(f"Hello, {name}!")
Hello, Stavros!

흐름 제어 설명서

흐름 제어 명령어는 if, for, 그리고 while이다. switch이 없다. 대신 if를 사용한다. 리스트의 구성원들을 통한 수를 수록하기 위해 for를 사용한다. 반복할 수 있는 숫자의 순서를 얻기 위해 range() 을 사용한다. 이 명령어 문법은 다음과 같다:

rangelist = list(range(10))
>>> print(rangelist)
range(0, 10)
>>> print(list(rangelist))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in rangelist:
    # Check if number is one of
    # the numbers in the tuple.
    if number in (3, 4, 7, 9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continue
else:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass # Do nothing

if rangelist[1] == 2:
    print("The second item (lists are 0-based) is 2")
elif rangelist[1] == 3:
    print("The second item (lists are 0-based) is 3")
else:
    print("Dunno")

while rangelist[1] == 1:
    print("We are trapped in an infinite loop!")

기능

함수들은 def 키워드로 선언된다. 선택적 인 논증들은 의무적인 논증 뒤에 기본값을 부여함으로써 함수 선언에 설정된다. 이름된 논증들에 대해서는 논증의 이름에 값을 부여한다. 함수들은 튜플을 반환할 수 있다 (그리고 튜플 해독을 사용하여 여러 값을 효과적으로 반환할 수 있다). 람다 함수는 단일 명령어로 구성된 특이 함수이다. 매개 변수는 참조로 전달되지만, 호출자로부터 호출자 안에서 변동성형 (투플, 인트, 문자열 등) 은 변경될 수 없다. 이는 항목의 메모리 위치만 전달되고, 다른 객체를 변수에 묶으면 오래된 객체가 폐기되기 때문에 변동성형이 대체된다. 예를 들어:

# Same as def funcvar(x): return x + 1
funcvar = lambda x: x + 1
>>> print(funcvar(1))
2

# an_int and a_string are optional, they have default values
# if one is not passed (2 and "A default string", respectively).
def passing_example(a_list, an_int=2, a_string="A default string"):
    a_list.append("A new item")
    an_int = 4
    return a_list, an_int, a_string

>>> my_list = [1, 2, 3]
>>> my_int = 10
>>> print(passing_example(my_list, my_int))
([1, 2, 3, 'A new item'], 4, "A default string")
>>> my_list
[1, 2, 3, 'A new item']
>>> my_int
10

클래스

파이썬은 클래스에서 한정된 형태의 복수 상속을 지원한다. 개인 변수와 메소드를 선언할 수 있다 (협약상, 이것은 언어에 의해 강제되지 않는다) 선두 하부자 (예: _spam) 를 추가함으로써. 우리는 또한 임의의 이름을 클래스 인스턴스에 묶을 수 있다. 예를 들어 다음과 같다:

class MyClass(object):
    common = 10
    def __init__(self):
        self.myvariable = 3
    def myfunction(self, arg1, arg2):
        return self.myvariable

    # This is the class instantiation

>>> classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all instances.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will bind a new object to the old
# variable name.
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50

# This class inherits from MyClass. The example
# class above inherits from "object", which makes
# it what's called a "new-style class".
# Multiple inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
    # The "self" argument is passed automatically
    # and refers to the class instance, so you can set
    # instance variables as above, but from inside the class.
    def __init__(self, arg1):
        self.myvariable = 3
        print(arg1)

>>> classinstance = OtherClass("hello")
hello
>>> classinstance.myfunction(1, 2)
3
# This class doesn't have a .test member, but
# we can add one to the instance anyway. Note
# that this will only be a member of classinstance.
>>> classinstance.test = 10
>>> classinstance.test
10

예외

파이썬의 예외는 try-except [exceptionname] 블록으로 처리됩니다.

def some_function():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print("Oops, invalid.")
    else:
        # Exception didn't occur, we're good.
        pass
    finally:
        # This is executed after the code block is run
        # and all exceptions have been handled, even
        # if a new exception is raised while handling.
        print("We're done with that.")

>>> some_function()
Oops, invalid.
We're done with that.

수입

외부 라이브러리는 import [libname] 키워드와 함께 사용된다. 또한 개별 함수들을 위해 from [libname] import [funcname]을 사용할 수 있다. 다음은 예이다:

import random
from time import clock

randomint = random.randint(1, 100)
>>> print(randomint)
64

파일 I/O

파이썬은 광범위한 라이브러리를 내장하고 있습니다. 예를 들어 파일 I/O로 일련화 (픽클 라이브러리를 사용하여 데이터 구조를 문자열로 변환) 를 사용하는 방법은 다음과 같습니다.

import pickle
mylist = ["This", "is", 4, 13327]
# Open the file C:\\binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile = open(r"C:\\binary.dat", "wb")
pickle.dump(mylist, myfile)
myfile.close()

myfile = open(r"C:\\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()

myfile = open(r"C:\\text.txt")
>>> print(myfile.read())
'This is a sample string'
myfile.close()

# Open the file for reading.
myfile = open(r"C:\\binary.dat", "rb")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print(loadedlist)
['This', 'is', 4, 13327]

다른 것

  • 조건은 연쇄될 수 있다: 1 < a < 3는 a가 3보다 작고 1보다 크다는 것을 확인한다.
  • del을 사용하여 배열의 변수나 항목을 삭제할 수 있습니다.
  • 목록 이해는 목록을 만들고 조작하는 강력한 방법을 제공합니다. 그들은 다음과 같이 0 또는 더 많은 if 또는 for 조항을 따르는 for 조항으로 이어지는 표현으로 구성됩니다.
>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print([x * y for x in lst1 for y in lst2])
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print([x for x in lst1 if 4 > x > 1])
[2, 3]
# Check if a condition is true for any items.
# "any" returns true if any item in the list is true.
>>> any([i % 3 for i in [3, 3, 4, 4, 3]])
True
# This is because 4 % 3 = 1, and 1 is true, so any()
# returns True.

# Check for how many items a condition is true.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)
2
>>> del lst1[0]
>>> print(lst1)
[2, 3]
>>> del lst1
  • 글로벌 변수는 함수 외부에 선언되고 특별한 선언 없이 읽을 수 있지만, 그들에게 글을 쓰고 싶다면 global 키워드로 함수의 시작에 선언해야 한다. 그렇지 않으면 파이썬은 그 객체를 새로운 로컬 변수에 묶을 것이다.
number = 5

def myfunc():
    # This will print 5.
    print(number)

def anotherfunc():
    # This raises an exception because the variable has not
    # been bound before printing. Python knows that it an
    # object will be bound to it later and creates a new, local
    # object instead of accessing the global one.
    print(number)
    number = 3

def yetanotherfunc():
    global number
    # This will correctly change the global.
    number = 3

에필로그

이 튜토리얼은 파이썬의 전부 (또는 심지어 부분 집합) 의 포괄적인 목록이 될 수 있는 것은 아닙니다. 파이썬은 라이브러리의 광범위한 배열과 다른 방법을 통해 발견해야 할 훨씬 더 많은 기능을 가지고 있습니다. 훌륭한 책 다이브 인 파이썬과 같은. 나는 파이썬에 대한 전환을 더 쉽게 만들었습니다. 개선되거나 추가 될 수있는 것이 있다고 생각하거나보고 싶은 다른 것이 있다면 댓글을 남겨주세요 (클래스, 오류 처리, 무엇이든).


더 많은