티스토리 뷰

python/Lecture

python 기초 #1 : 기본 문법

jinozpersona 2021. 2. 22. 18:10

INTRO

0. 용어설명 : Class/Object, Method/Function, Library/Package/Module

1. python code 작성에 필요한 기본 문법

    print(), type(), format() : print()는 함수, .format() 형태로 사용되는 함수는 메서드(method)라 구분

    annotation, indentation, colon, semi-colon, comma

    single/double/triple quotes(quotation mark)

    escape sequences for special charactors : \n, \t, \\, \', \"

 

0. 용어

Class/Object(or Instance)

출처 : http://www.trytoprogram.com/python-programming/python-object-and-class/

Class(클래스)

: Object를 만들어내는 설계도에 비유되며 일반적으로 variable(변수)와 method(메서드)의 집합으로 구성

 

Object(오브젝트, 객체)

: Class에서 구현(생성)된 실체(대상)으로 Class의 instance라고도 부름

  추상화된 Class에서 구체화(or 할당)된 실체(Object)

 

 

Method/Function

출처 : https://i.ytimg.com/vi/zoePX7QN4eM/maxresdefault.jpg

Method(메서드)

: Class or Object로 구성되며 default parameter 'self'를 포함하는 객체(object)로 호출되는 함수(function)

  Class.function()의 object 형태로 호출하여 function으로 작동

 

Function(함수)

: 독립적으로 정의되어 특정 기능을 수행하는 code의 집합체로 입력값(매개변수)에 따른 출력값(return)을 얻음

  내장함수(built-in function) : import 없이 사용 가능

  ex> print(), type(), dir(), len(), sum(), str(), chr(), int(), float(), list(), tuple()...

  "def function():" 처럼 직접 code를 구성하거나 .py와 같은 module(모듈)로 구성하여 import 하여 사용함

 

 

Library/Package/Module

출처 : https://thinkreen.github.io/python/py-FunctionModuleClass/

Library(라이브러리)

: package와 더불어 module들의 묶음이며, package와 module을 묶어 library라고 함

  library.module의 형태로 import하여 사용

  Python Standard Library(표준라이브러리) : python 설치 시 기본 제공

  ex> platform, os, sys, time, pickle, grob, random, math, urllib, ... 

  Third Party Library(외부라이브러리) : python.org가 아닌 서드파티(3rd party)에서 개발

  ex> numpy, pandas, scipy, requests, ... 

 

Package(패키지)

: 여러개의 module을 포함하는 상위 묶음(folder, directory)으로 하위 묶음을 포함할 수 있음

  package.module의 형태로 import하여 사용

 

Module(모듈)

: 변수(variable), 클래스(class)의 모음 뿐만아니라 이를 포함한 메서드(method), 함수(function) 모음집

  .py로 만들어진 파일명으로 import로 가져와서 사용 가능, script(스크립트)라 부르기도 함

  사용법 -> from folder(library or package).module(.py, 확장자 생략) import function(or class)

 

 

1. python code 작성에 필요한 기본 문법

python code 작성에서 중요한 부분은 입력/출력 feedback을 통해 실행 과정을 이해하는 것이다.

다음 용어 해석은 본질적인 내용을 해치지 않는 범위의 설명이고 상세한 내용은 익히며 공부하기를 추천한다.

#1 ~ #4는 아래 code에 주석을 달아 추가 설명이 되어있으니 내용은 간략하게만 받아들이자.

 

#1 print(), format(), type() : python 내장함수로 import없이 사용이 가능

print 함수는 출력을 바로 확인 할 수 있고 coding deburging에 중요한 함수

print 함수에 format 함수를 더해 출력 방식을 정한다.

type 함수는 개체, 변수 등의 데이터 타입을 확인할 수 있다.

 

#2  annotation, indentation, comma, colon, semi-colon

annotation(주석) : 일반적으로 #(hashtag) 뒤에 쓰여진 code로 run 실행에 영향을 미치지 않음.

                             단축키 (macOS)command+/

indentation(들여쓰기) : python 문법에서 들여쓰기는 강제조건 사항이며, code block(함수, 조건/반복문)에서 구분 필요

                                     단축키 tab or space*4

comma(,), semi-colon(;) : 콤마는 매개변수나 함수 구분을하며, 세미콜론은 단일 행에 문법을 구분할 때 사용하나

                                         일반적으로 enter로 개행하여 사용

colon(:) : 콜론은 함수(def)를 정의할때 indentaion 즉 들여쓰기 시작을 나타내며, 문자열의 index 순서를 나타내거나 숫자의

               start:interval:end의 등차수열을 생성시키는 역할을 함. 0:1:5의 형태의 경우 0부터 1씩 증가하여 4까지를 의미하고

               0,1,2,3,4의 집합으로 이해할 수 있다. interval을 생략할 경우 default로 1을 가짐.

 

#3 single/double/triple quotes(quotation mark)

single/double quotes : " "과 ' '로 쌍따옴표가 홑따옴표를 포괄하며 홑따옴표 출력 시 print(" 'single ' ") 형태로 구성

                                    python에서 문자(string)을 자료형으로 사용 시 사용한다.

triple quotes : """ """ 또는 ''' '''의 형태로 annotation(주석)으로 활용하거나 print에서 출력 내용을 자유롭게 기술 가능

 

#4 escape sequences for special charactors : \n, \t, \\, \', \"

앞에 back slash(백슬래쉬, \)를 가지는 형태로 말그대로 특별한 기능을 가지는 문자로 이해

 

 

SublimeText 화면 : 좌측 code 작성 후 우측에서 SublimeREPL-python-python Run current file 확인

                           <좌측은 python code>                                                    <우측은 SublimeREPL실행결과>

python code : test2.py

#1 print(), format(), type()
## 변수할당  <<-- 주석 사용 방법
A = 'a'		# 변수 A에 string(class 'str') 값(value) a를 할당
B = "b"		# # single/double quotes은 str에서 동일
ABC = 'abc'; XyZ = 'xyz'	# semi-colon 세미콜론 사용
a = 1.25	# 변수 a에 float(class 'float') 값 1.25를 할당
b = 3.542	# python은 대문자 소문자를 구분함

## print, format, type 함수
print('a + b = %d' % (a+b))			# single quotes
print('a + b = %0.2f' % (a+b))
print('%s + %s = %f' % (A,B,a+b))	# comma(,)로 변수 구분
print('Data type A, B is %s, %s' % (type(A),type(B)))
print('Data type a, b is %s, %s' % (type(a),type(b)))
print('Data indexing 0:2 %s' % (ABC[0:2]))	# indexing colon 사용
print('\n')		# escape sequence /n은 개행(행넘기기) /n 한줄
print('a + b = {}'.format(a+b))
print('{} + {} = {:0.2f}'.format(A,B,a+b))	# 출력 형태 colon 사용
print('\n\n')	# /n/n 두줄

#2  annotation, indentation, comma, colon, semi-colon
#### annotation 즉 주석에 해당
def aPLUSb():		# def 함수 끝에 colon(:) 들여쓰기 시작
	return a+b		# 위 행에서 엔터치면 자동으로 indentation 들여쓰기

print(' \tprint object of \"aPLUSb\" function')	# 따옴표 사용
print('\t',aPLUSb)	# escape sequence /t 사용

print(" \t'print return value for aPLUSb function' ")
print('\t',aPLUSb())	# 리턴값을 얻기 위해서는 함수() 형태로 coding

#3 single/double/triple quotes(quotation mark)
#4 escape sequences for special charactors : \n, \t, \\, \', \"
print('''
aPLUSb function print
	free-description	'자유롭게 기술'
	''')
print(" '쌍따옴표 안에 홑따옴표'   \"쌍따옴표 안에 쌍따옴표\"  ") # \" 사용
print(' \'홑따옴표 안에 홑따옴표\' \\쌍따옴표 안에 백스래쉬\\  ') # \\ 사용

 

---- SublimeText python Run test2.py ----

a + b = 4
a + b = 4.79
a + b = 4.792000
Data type A, B is <class 'str'>, <class 'str'>
Data type a, b is <class 'float'>, <class 'float'>
Data indexing 0:2 ab


a + b = 4.792
a + b = 4.79



 	print object of "aPLUSb" function
	 <function aPLUSb at 0x1006370d0>
 	'print return value for aPLUSb function' 
	 4.792

aPLUSb function print
	free-description	'자유롭게 기술'
	
 '쌍따옴표 안에 홑따옴표'   "쌍따옴표 안에 쌍따옴표"  
 '홑따옴표 안에 홑따옴표' \쌍따옴표 안에 백스래쉬\  

***Repl Closed***

 

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함