소스코드에 한글 사용하기

Python 2.7.x 버전의 경우 소스 맨 첫 줄 혹은 두번째 줄에 아래와 같은 구문을 넣어준다.

# -*- coding: utf-8 -*-
print 'Hello World'

Python 3.x 버전의 경우

print('안녕하세요')

파이썬에서 메인함수

파이썬 스크립트에서 메인함수가 필요하면 아래의 구문을 사용한다.

if __name__ == '__main__':
   pass

문서화

__doc__: 모듈, 함수, 클래스를 선언하고 그 다음 줄에 문자열 "...", """ ... """, '...', '''...''' 를 지정하면 __doc__ 에 저장

'''
모듈의 __doc__문자열
'''
class Ham:
    "Ham class의 __doc__문자열"
    def __init__(self):
        self.a = "foo"
        """ a 에 대한 설명 """

    def func(self):
        "func의 __doc__문자열"
        pass

print(mymodule.__doc__)
print(mymodule.Ham.__doc__)
print(mymodule.Ham.func.__doc__)

dir

속성과 메서드의 리스트를 보여준다.

help

help("string".strip)

Help on built-in function strip:
strip(...)
    S.strip([chars]) -
>
 string or unicode

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping
(END)

id

주소값을 확인할 때 사용한다.

>>> id(1)
140361196419848

>>>

>>> id('hello')
4541723920

>>>

사용자에게 입력받기

파이썬에서는 키보드로부터 입력값을 받을 수 있는 raw_input 이라는 내장함수를 제공한다.

기본 형식

raw_input([prompt])

기본 예제

>>> name = raw_input()
Sonic

>>> print name
Sonic

사용자 입력을 기다릴 때 문구를 출력

>>> name = raw_input("What's your name? ")
What's your name? sonic

>>> name = raw_input("What's your name?\n")
What's your name?
sonic

>>> print name
sonic

입력받은 값을 정수로 변환할 수 있다. 이 때 숫자 문자가 아닌 것을 입력하면 오류

>>> value = raw_input()
17

>>> type(value)

<type 'str'>

>>> int(value)
17

>>>
>>> value = raw_input()
hello

>>> int(value)
Traceback (most recent call last):
  File "
<stdin>", line 1, in 
<module>

ValueError: invalid literal for int() with base 10: 'hello'

명령줄 옵션 읽기

파이썬을 시작하면 명령줄 옵션들이 sys.argv 리스트에 저장된다.

  1. 첫번째 원소는"프로그램의 이름"
  2. 나머지 원소들은 프로그램 이름 다음에 나오는 옵션들

테스트 스크립트

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

실행결과

$ python test.py arg1 arg2 arg3

Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

results matching ""

    No results matching ""