파이썬에서 문자열은 ""를 이용하여 정의할 수 있다.

s = "Hello World"
print(s)


Accesing array elements

대괄호를 이용하여 문자열의 요소에 엑세스

print(s[0])


String Slicing

파이썬에서는 문자열을 범위를 지정하여 Substring 할 수 있다.

문자열을 자를 인덱스 범위를 3가지 방법으로 지정 할 수 있다.

>>> s = "Hello World"
>>> s[:3]
'Hel'
>>> s[3:]
'lo World'
>>> s[1:3]
'el'
>>> slice = s[0:5]
'hello'


'프로그래밍 > Python' 카테고리의 다른 글

Python Tutorial : Comments [15]  (0) 2016.04.16
Python Tutorial : Date and Time [14]  (0) 2016.04.16
Python Tutorial : Modules [13]  (0) 2016.04.16
Python Tutorial : Line charts [12]  (0) 2016.04.16
Python Tutorial : Statistics [11]  (0) 2016.04.15

다른 프로그래밍 언어들과 마찬가지로 파이썬에서도 주석을 달 수 있는데,

주석은 컴퓨터가 읽을 수 없고 실행 하지도 않는 텍스트이다.

주석이 중요한 이유는 규모가 크던 작던 하나의 프로젝트에서 개발자 본인을 포함해서

같은 팀의 다른 개발자들을 위해서 해당 소스코드가 어떤 기능을 하는지,

그리고 수정된 코드 내용 이라던지를 코멘트를 달음으로써 코드의 유지보수 및 팀원들과의 협업에도 중요한 힌트가 된다.


파이썬에서는 #와 '''를 이용하여 한 줄 및 여러 줄의 주석을 달 수 있다.

# This is a comment
print('Hello')
''' This is a multiline 
Python comment example.'''
x = 5


컴퓨터는 ticks을 이용하여 시간을 처리한다.

일반적으로 UNIX 기반 운영체제가 설치 된 컴퓨터는 1970년 1월 1일 00:00 을 기준으로 시간을 계산한다.

파이썬에서 날짜 및 시간을 얻기 위해서는 standard time module을 이용한다.

import time 

ticks = time.time()
print "Ticks since epoch:", ticks
output : Ticks since epoch: 1460782927.19


Local time

컴퓨터 시스템 상의 현재 시간을 얻으려면 localtime함수를 이용한다.

import time

timenow = time.localtime(time.time())
print "Current time :", timenow
output : Current time : time.struct_time(tm_year=2016, tm_mon=04, tm_mday=16, tm_hour=15, tm_min=42, tm_sec=0, tm_wday=5, tm_yday=353, tm_isdst=0)


해당 배열의 각 요소들에 엑세스를 할 수도 있고,

import time

timenow = time.localtime(time.time())
print "Year:", timenow[0]
print "Month:", timenow[1]
print "Day:", timenow[2]


다른 서식을 이용 할 수도 있다. 예를 들면 asctime 함수를 이용

import time

timenow = time.asctime(time.localtime(time.time()))
print(timenow)
output : Sat Apr 16 15:44:40 2016


파이썬 프로그래밍을 하다가 보면 파이썬 자체 모듈 및 외부 모듈을 사용 할 일이 많은데

math모듈을 사용하는 예제를 살펴보자.

import math

print(math.pi)
x = math.sin(1)
print(x)


아래 코드는 해당 모듈에서 사용 가능한 함수들의 리스트를 보여준다.

import math

content = dir(math)
print(content)
$ python example.py
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 
'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 
'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']


Create your own module

필요한 기능을 메인 파일 내에 함수로 구현 할 수도 있지만,

아래 방법은 특정한 기능을 가진 함수를 외부 모듈로 저장하여 필요 할 때 가져와서 쓸 수도 있음을 보여준다.


hello.py 라는 파일에 아래와 같은 코드를 작성하고

def hello():
    print("Hello World")

아래와 같이 import하여 해당 모듈을 호출한다.

# Import your module
import hello

# Call of function defined in module
hello.hello()


matplotlib 라이브러리를 통해 라인 차트를 만들수 있다.

x, y축 라벨을 정의하고 list를 차트화 시킬 수 있다.

import numpy as np
import matplotlib.pyplot as plt

x = [2,3,4,5,7,9,13,15,17]
plt.plot(x)
plt.ylabel('Sunlight')
plt.xlabel('Time')
plt.show()



dots를 포함하는 차트를 그리려면,

plt.plot(x, 'ro-')


파이썬의 math 라이브러리를 통해 다양한 통계 값을 계산 할 수 있다.

최소, 최대, 평균, 평균과 표준편차

import math
import numpy

x = [1,2,15,3,6,17,8,16,8,3,10,12,16,12,9]

print(numpy.min(x))
print(numpy.max(x))
print(numpy.std(x))
print(numpy.mean(x))
print(numpy.median(x))


그래프로 표현

import matplotlib.pyplot as plt
import numpy as np

x = [1,2,15,3,6,17,8,16,8,3,10,12,16,12,9]

plt.boxplot(x)
plt.show()


'프로그래밍 > Python' 카테고리의 다른 글

Python Tutorial : Modules [13]  (0) 2016.04.16
Python Tutorial : Line charts [12]  (0) 2016.04.16
Python Tutorial : Read and Write File [10]  (0) 2016.04.15
Python Tutorial : Dictionary [9]  (0) 2016.04.15
Python Tutorial : Tuples [8]  (0) 2016.04.15

Reading files

파이썬은 readlines() 함수를 통해 파일 전체를 읽을 수 있다.

#!/usr/bin/env python
 
filename = "readme.txt"
 
with open(filename) as fn:
    content = fn.readlines()
 
print(content)


Writing files

w 파라미터는 파일을 쓰기 위함을 파이썬에게 알려주는 것이고,

write()함수를 통해 파일에 데이터 기록 후 close()로 파일을 닫는다.

#!/usr/bin/env python
 
f = open("output.txt","w")
f.write("Pythonprogramminglanugage.com, \n")
f.write("Example program.")
f.close()


'프로그래밍 > Python' 카테고리의 다른 글

Python Tutorial : Line charts [12]  (0) 2016.04.16
Python Tutorial : Statistics [11]  (0) 2016.04.15
Python Tutorial : Dictionary [9]  (0) 2016.04.15
Python Tutorial : Tuples [8]  (0) 2016.04.15
Python Tutorial : Lists [7]  (0) 2016.04.15

파이썬에서는 중괄호를 이용하여 딕셔너리를 이용한 key-value 코드 작성이 가능하다.

k라는 dictionary 정의:

k = { 'EN':'English', 'FR':'French' }
print(k['EN'])


k에 key-value pair 추가

k['DE'] = 'German'


key-value pair 삭제

k = { 'EN':'English', 'FR':'French' }

del k['FR']
print(k)


'프로그래밍 > Python' 카테고리의 다른 글

Python Tutorial : Statistics [11]  (0) 2016.04.15
Python Tutorial : Read and Write File [10]  (0) 2016.04.15
Python Tutorial : Tuples [8]  (0) 2016.04.15
Python Tutorial : Lists [7]  (0) 2016.04.15
Python Tutorial : Functions [6]  (0) 2016.04.15

파이썬에서 튜플은 수정할 수 없는 콜렉션이다. 튜플은 괄호를 사용하여 정의한다.

하나의 아이템을 가지는 튜플

x = (1,)


여러 개의 아이템을 가지는 튜플

x = (1,2,3,4)


Accessing tuples

튜플의 개별 요소에 접근하려면 대괄호를 이용한다.

print(x[0])


튜플의 마지막 요소에 접근하려면 리스트와 같이 -1번째 인덱스로 접근 가능하다.

print(x[-1])

'프로그래밍 > Python' 카테고리의 다른 글

Python Tutorial : Read and Write File [10]  (0) 2016.04.15
Python Tutorial : Dictionary [9]  (0) 2016.04.15
Python Tutorial : Lists [7]  (0) 2016.04.15
Python Tutorial : Functions [6]  (0) 2016.04.15
Python Tutorial : While loop [5]  (0) 2016.04.15

파이썬은 list 라고 알려진 컬렉션을 지원한다. list는 대괄호를 사용하여 정의한다.

c = [5,2,10,48,32,16,49,10,11,32,64,55,34,45,41,23,26,27,72,18]


Accessing elements

list의 요소에 접근하려면 같은 대괄호 방식을 사용한다.

print(c[0])


list의 마지막 요소에 접근하려면 다음과 같은 방식도 가능하다.

print(c[-1])


Size of the list

list의 길이를 알려면 len함수를 사용한다.

c = [5,2,10,48,32,16,49,10,11,32,64,55,34,45,41,23,26,27,72,18]
print(len(c))


Datatypes

list는 텍스트, 정수, 부동소수점등 다양한 변수 타입을 포함할 수 있다.

텍스트 변수 리스트의 예:

fears = ["Spiders","Ghosts","Dracula"]


'프로그래밍 > Python' 카테고리의 다른 글

Python Tutorial : Dictionary [9]  (0) 2016.04.15
Python Tutorial : Tuples [8]  (0) 2016.04.15
Python Tutorial : Functions [6]  (0) 2016.04.15
Python Tutorial : While loop [5]  (0) 2016.04.15
Python Tutorial : For loops [4]  (0) 2016.04.15

+ Recent posts