Python-basic

From 탱이의 잡동사니
Revision as of 08:57, 15 November 2016 by Pchero (talk | contribs) (→‎Statement)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Overview

Python 프로그래밍 내용 정리

Data structures

list

다음의 method 들을 지원한다.

  • list.append(x)
list 의 마지막에 item 을 추가한다. a[len(a):] = [x] 와 같다.
  • list.extend(L)
L 의 모든 item 을 list 의 마지막에 추가한다. a[len(a):] = L 과 같다.
  • list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
  • list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.
  • list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
  • list.clear()
Remove all items from the list. Equivalent to del a[:].
  • list.index(x)
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
  • list.count(x)
Return the number of times x appears in the list.
  • list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
  • list.reverse()
Reverse the elements of the list in place.
  • list.copy()
Return a shallow copy of the list. Equivalent to a[:].


<source lang=python>

</source>

sets

sets 는 리스트와 유사하지만, 중복된 개체를 허용하지 않는다는 점이 다르다.

단, 주의할 점은 빈 set 을 만들기 위해서는 set() 를 사용해야 한다는 점이다. {}를 사용하면 안된다. <source lang=python> >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # show that duplicates have been removed {'orange', 'banana', 'pear', 'apple'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False

>>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in either a or b {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'} </source>

Statement

for

  • 구구단 예제

<source lang=python> >>> for i in range(2,10): ... for j in range(1, 10): ... print(i*j, end=" ") ... print() </source>

while

while 문은 지정된 조건이 참일 경우에만 문장을 수행한다.

while <조건문>:
    <수행할 문장1>
    <수행할 문장2>

Sample <source lang=python> num = 0 while num < 10:

   num = num +1
   print("Check value. num[%d]" % num)
   if num == 10:
       print("Last number")

</source>

Exception

Exception handling

Python 에서의 기본적인 Exception Handling 은 다음과 같이 한다. <source lang=python> try:

 generate_exception()

except SomeException, e:

 if not can_handle(e):
   raise
 handle_exception(e)

</source>

raise

python 에서는 raise 를 통하여 임의로 Exception 을 발생시킬 수 있다. <source lang=python> if something:

   raise Exception('My error!')

</source>

Bugs

No child processes

Python-2.6.6 버전에서 다음과 같은 문제가 발생했었다.

여러개의 쓰레드가 돌아가고 있는 상황에서 subprocess 모듈을 사용해서 다른 프로그램들을 동시에 여러개를 실행했을 때, 하나의 프로그램을 종료했을 때, 다른 자식 프로세스의 핸들러에서 ECHILD 에러를 발생시키는 것이다.

[Errno 10] No child processes

여러 가지 방법을 찾아봤지만, 이는 결국 python 자체의 문제였다. Popen() 함수 사용시, 내부적으로 생성자가 "_cleanup()" 이라고 하는 함수를 호출하는데, 이 함수가 global 이라는 것이 문제였다.

단순히 python 버전을 업그레이드하면 해결이 될 것 같았지만, python 업그레이드가 쉬운일은 아니였다.

결국 stdout 을 다른 temp 파일로 redirect 하여 어느 정도의 시간이 흐른 뒤에 결과값을 확인하는 방법으로 문제를 해결하였다. <source lang=python> subprocess.call(cmd, stdout=fp) sleep(5) fp.flush()

fp.seek(0) res = fp.read() </source>

다음의 버전에서는 패치가 되었다고 한다. Python 2 >= 2.7.2, Python 3.1 >= v3.1.4, Python 3 >= 3.2.4

Useful info

Anaconda

Python package manager. 복잡하고 어려운 파이썬 패키지를 쉽게 관리할 수 있게 해주는 툴이다. 패키지 관련 문제가 생겼을 때 한번 참고해보자.

See also

References

<references />