컴퓨터는 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

함수를 이용하여 특정한 동작을 하는 코드를 반복 할 수 있다.

예를 들어, 피타고라스의 정리를 수행하는 함수는 다음과 같이 정의하여 호출한다.

import math

def pythagoras(a,b):
    value = math.sqrt(a *a + b*b)
    print(value)

pythagoras(3,3)


함수의 계산 결과를 변수에 저장하여 호출하는 것도 가능하다.

import math

def pythagoras(a,b):
    value = math.sqrt(a*a + b*b)
    return value


result = pythagoras(3,3)
print(result)


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

Python Tutorial : Tuples [8]  (0) 2016.04.15
Python Tutorial : Lists [7]  (0) 2016.04.15
Python Tutorial : While loop [5]  (0) 2016.04.15
Python Tutorial : For loops [4]  (0) 2016.04.15
Python Tutorial : Variables [3]  (0) 2016.04.15

파이썬은 while 키워드로 반복 코드 작성이 가능하다.

다음은 5 라는 숫자를 예측하는 게임

x = 0
while x != 5:
   x = int(input("Guess a number:"))
   
   if x != 5:
      print("Incorrect choice")

print("Correct")


게임 방식을 확장하여 입력한 숫자에 대한 힌트를 추가

x = 0
while x != 5:
   x = int(input("Guess a number:"))
   
   if x != 5:
      print("Incorrect choice")
   if x > 5:
      print("Please enter a smaller number")
   if x < 5:
      print("Please enter a larger number")

print("Correct")


주의 할 점은 while 루프의 조건이 충족되지 않을 경우 무한 루프에 빠지는 문제를 발생시킬 수 있다.

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

Python Tutorial : Lists [7]  (0) 2016.04.15
Python Tutorial : Functions [6]  (0) 2016.04.15
Python Tutorial : For loops [4]  (0) 2016.04.15
Python Tutorial : Variables [3]  (0) 2016.04.15
Python Tutorial : If statements [2]  (0) 2016.04.15

+ Recent posts