Sister Nosilv story

2. 프로그래밍 핵심개념 in Python

by 노실언니

*1.프로그래밍 시작하기는 컴퓨터개론Course의 1토픽과 정확하게 일치하여 생략

프로그래밍기초Course

  📺플밍기초 in Python📺 - 🎖수료증

  • 프로그래밍 시작하기-Getting started with python - 📺   📝
  • ▶ 프로그래밍 핵심개념-Core concept of python programming - 📺   📝
  • 프로그래밍과 데이터-Python programming and data - 📺   📝
  • Python 응용하기-Making use of python - 📺   📝

*Link : 📺인강  📝정리노트

10년 안에 프로그래밍을 모르면 문맹이 되는 시대가 올 것입니다. 인공지능, 로봇, 사물인터넷, 가상현실, 스마트카 등 다가오는 미래 산업에 프로그래밍을 빼고 말할 수 있는 것은 없습니다. 그렇다면, 어떤 언어로 시작하는 게 좋을까요? 코드잇에서는 파이썬을 가장 추천합니다. 파이썬은 실리콘벨리를 비롯 세계 유수 기업에서 가장 많이 쓰는 언어이며, 미국 대학 상위 39개 컴퓨터 학과에서 선호하는 언어 1위이기도 합니다. 데이터 사이언스, 웹 개발 등 어디 하나 빠지지 않고 쓰이지요. 파이썬과 함께 프로그래밍의 세계에 첫 걸음을 내딛어 보세요.

Python을 배우면서 프로그래밍 자체도 배워보자


 

Topic 2. 프로그래밍 핵심 개념 in Python

이제부터 코딩이 왜 강력한 도구인지 알게 될 것입니다.

우리는 코딩을 왜 할까요? → 사람이 힘들어하는 것을 기계에게 대신 시키려고! [정밀 반복 계산, etc.]

 

프로그래밍의 세계는 넓고 깊지만, 결국 모두 몇 가지 핵심 개념에서 시작됩니다.

-'자료형'을 알면 데이터를 어떤 형태로 저장하고 활용하는지 이해할 수 있습니다.

-'추상화'를 알면 코드를 더 간결하고 근사하게 작성할 수 있습니다. 프로그래밍을 하나의 예술로 본다면,이게 바로 그 예술의 영역이라고 할 수 있죠.

-'제어문'을 알면 조건에 따라 동작을 나눌 수 있고, 반복적인 일을 처리할 수 있습니다. 컴퓨터를 반복적이고 어려운 일을 처리하는 똑똑한 비서로 활용할 수 있는 거죠.

이 토픽을 공부하고 나면, 세상에 많은 프로그램들이 대충 어떻게 돌아가는지 파악할 수 있습니다. 그리고 컴퓨터를 이용해서 어떤 문제를 해결하면 좋을지 아이디어가 마구 샘솟기 시작할 거라고 확신합니다.

 

⑴ 자료형

①자료형과 형변환

def. Data type [en.wiki]:컴파일러나 인터프리터에게 알려주는 '값의 의미' → 이에 따라, 값을 저장하는 방식이 결정된다.

- [자료형]

- [형변환]

형변환 : 원하는 타입(값)    Ex. bool("A") → True

- [Function : type()] : Returns the type of value → 파라미터값의 자료형을 반환하는 함수

💣함정 : return값 ≠ print결과 (print의 return값 = None)

더보기

- Type() 함수 사용해보기

# Function : type(□) → Returns the type of value
    print(type(1))			# <class 'int'>
    print(type(1.0))		# <class 'float'>
    print(type('1'))		# <class 'str'>
    print(type(True))		# <class 'bool'>

    print(type("True"))		# <class 'str'>
    print(type(None))		# <class 'NoneType'> ★bool 아님
    print(type(1==1.0))		# <class 'bool'>
    print(type(()))			# <class 'tuple'> ★?
    print(type({}))			# <class 'dict'> ★?
    print(type([]))			# <class 'list'> ★?

배운 Type 외에, NoneType tuple dict list도 반환

 

- Type() 함수 : 값과 변수뿐만 아니라 function & method도 parameter로 받음

print(type(print))		# <class 'builtin_function_or_method'> 내장함수
    print(type(format))		# <class 'builtin_function_or_method'> 메소드

    def hello():
    	print("Hello")

    print(type(hello))		# <class 'function'>
    print(type(hello()))	# 1. Hello : 함수실행
    						# 2. <class 'NoneType'> : 함수 리턴값의 type 출력

💣함정 : return값 ≠ print결과 (print의 return값 = None)

어떤 함수의 입력값으로 "함수명(입력값)"을 입력하면, 해당 함수가 실행된다.

 

- 형변환 Type Conversion

# Conversion : Int → Float
    a = 3
    b = float(a)
    print("a :", a, "=", type(a))	# a : 3 = <class 'int'>
    print("b :", b, "=", type(b))	# b : 3.0 = <class 'float'>
# Conversion : Float → Int
    a = 3.9
    b = int(a)
    print("a :", a, "=", type(a))	# a : 3.9 = <class 'float'>
    print("b :", b, "=", type(b))	# b : 3 = <class 'int'> → 소숫점이하 버림

    c = -3.9
    d = int(a)
    print("a :", a, "=", type(a))	# a : -3.9 = <class 'float'>
    print("b :", b, "=", type(b))	# b : -3 = <class 'int'> →

실수→정수:정수 외의 값은 버려지는 것이 포인트

상용로그의 지표와 가수가 생각나서 혹시나 int(-3.9)는 -4가 되나 싶었는데 아니었다.

# Conversion : Int → Str
    a = 3
    b = str(a)
    print("a :", a, "=", type(a))	# a : 3 = <class 'int'>
    print("b :", b, "=", type(b))	# b : 3.0 = <class 'str'>
    print(a * 2)	# 6  (= 3 × 2)
    print(b * 2)	# 33 (= 문자3을 2회 출력)

문자도 연산자가 적용된다는 것이 포인트(+, *)

# Conversion : Str → Int
    a = "1"
    b=  float(a)
    print("a :", a, "=", type(a))	# a : 1 = <class 'str'>
    print("b :", b, "=", type(b))	# b : 1.0 = <class 'float'>
    print(a * 2)	# 11  (= 문자1을 2회 출력)
    print(b * 2)	# 2.0 (= 1.0 × 2)

고맙게도, 숫자형태의 문자형은 숫자로 전환이 가능하다.

# Conversion : □ → Bool
    a = 0		# int	   → False
    b = 1.9		# float	   → True
    c = "False"	# str	   → True ★생긴건 False지만, 값이 있으므로 bool로는 True
    d = ""		# str	   → False
    e = []		# list	   → False
    f = None	# NoneType → False

    print(bool(a))	# False
    print(bool(b))	# True
    print(bool(c))	# True
    print(bool(d))	# False
    print(bool(e))	# False
    print(bool(f))	# False

값이 있으면 True로, 없으면 False로 변환

# Conversion : Bool → □
    a = 1==1	# True
    b = 1!=1	# False

    print(int(a))	# 1			# 숫자로는 1 / 0 로 변환
    print(float(b)) # 0.0
    print(str(a))	# "True"	# 문자로는 True / False 로 변환
    print(str(b))	# "False"

True → 1 or "True"

False → 0 or "False"

 

②연산자

연산자 : + - × ÷ , 제곱, 몫&나머지, 명제사용 + 반올림

- "와 '가 다 들어간 문자열의 경우,

# Life is too 'short', we need "python".
print("""Life is too 'short', we need "python".""")   # 3번묶기
print('Life is too \'short\', we need "python".')     # 역슬래쉬 

 

- 0.5이상부터 올리는, 진정한 반올림!? → decimal모듈 + ROUND_HALF_UP

float(부동소수점수)의 본질적인 문제를 해결하고, 실수를 정확히 표현/연산하기 위해 지원된 모듈

Infinity ~ -Infinity, -0, NaN(Not a Number)형태도 다룰 수 있음

# 반올림 round = ROUND_HALF_EVEN 짝수가 되도록 반 올/내 림
print(round(0.135))    # 0.14 [올림]
print(round(0.125))    # 0.12 [내림] → 끝자리가 짝수가 되는 방향으로


# REAL 반올림 → decimal module
import decimal					# decimal module
from decimal import Decimal		# Decimal class

mode = decimal.getcontext()
print(mode.rounding)					# ROUND_HALF_EVEN : 현재 반올림모드 확인
mode.rounding = decimal.ROUND_HALF_UP 	# 반올림모드 변경
print(mode.rounding) 					# ROUND_HALF_UP
print(Decimal("0.135").quantize(Decimal("1.00"))) # 0.14 [올림]
print(Decimal("0.125").quantize(Decimal("1.00"))) # 0.13 [올림] ★

Decimal("숫자"를).quantize(Decimal(반올림하여 "n째자리까지" 구할 것))

문자형식으로 담아야 제기능을 함

 

③문자열 포맷팅

  f-string string format() method %
Trend Cutting edge 現 General Outdated
Syntex f "string & {변수명}" "string&{}".format(val1, val2, ··) "string&%" % (val1, val2, ··)
Type string
소수점n째 { 변수명.nf } { .nf } %.nf
{ } Index   named  numbered  empty  
값변경 재정의 가능 정의 후 값 변경 X 재정의 가능

 

a. string format() method

- 변수 선언 : 변수명 = "{}를 포함한 문자열".format( val1, val2, ··· ) → 추후 값 변경 불가(WHY?)

- 바로 출력 : print("{}를 포함한 문자열".format( val1, val2, ··· ))

- 소수점N째자리표시 : { : . Nf }

- { } 속 Index : ①named ②numbered ③empty

# named indexes 결과 → 알파벳:ABC 숫자:8.8
txt1 = "알파벳:{one} 숫자:{two}".format(one = "ABC", two = 8.8)

# numbered indexes 결과 → 숫자:2.29 정수:1.3
txt2 = "숫자:{1} 정수:{0:.1f}".format(1.19, 2.29)

# empty indexes 결과 → 알파벳:ABC 숫자:9
txt3 = "알파벳:{} 숫자:{:.0f}".format("ABC", 8.8)

* def. method : ko.wiki  en.wiki blog → 객체에 종속된 함수, 객체명.메소드명(파라미터) 형식

[함수⊃메소드] 그냥 함수는 함수명(파라미터)로 독립호출이 가능하지만,

메소드는 메소드명 만으로 호출할 수 없고, 객체.메소드(파라미터)로 호출해야함

# 메소드의 파라미터에 변수삽입 → 성공
one = "ABC"
two = 8.8
print("알파벳:{} 숫자:{}".format(one, two))
# 값 변경
one = "ABC"
two = 8.8
txt1 = "1. 알파벳:{} 숫자:{}".format(one, two)
txt2 = "2. 알파벳:{one} 숫자:{two}".format(one = one, two = two)
print(txt1)
print(txt2)

two += 0.2
print(txt1)                        		 # 변경불가
print(txt1.format(one, two))       		 # 변경불가
print(txt2)								 # 변경불가
print(txt2.format(one = one, two = two)) # 변경불가

왜 안 바뀌지?

 

b. f-string

- 변수선언 : 변수명 = f"{변수명}을 포함한 문자열" → 값 변경 가능

- 바로 출력 : print(f"{변수명}을 포함한 문자열")

- 소수점N째자리표시 : { 변수명 : . Nf }

# f-string
name = "ABC"
int_num = 10
float_num = 123.456
txt1 = f"알파벳:{name} 정수:{int_num} 소수:{float_num:.2f}"
print("1.", txt1)  # 1. 알파벳:ABC 정수:10 소수:123.46

# 값 변경 → 실패
name = "EFG"
int_num = 20
print("2.", txt1)   # 2. 알파벳:ABC 정수:10 소수:123.46

# 값 변경 → 성공 [재정의]
txt1 = f"알파벳:{name} 정수:{int_num}"
print("3.", txt1)   # 3. 알파벳:EFG 정수:20

c. %

- 변수선언 : 변수명 = "%n,f,s를 포함한 문자열" % (변수명 or 값) → 값 변경 불가

- 바로 출력 : print("%n,f,s를 포함한 문자열" % (변수명 or 값) )

- 소수점N째자리표시 :  % . N f

# %
name = "ABC"
int_num = 10
float_num = 123.456
txt1 = "알파벳:%s 정수:%d 소수:%.2f" % (name, int_num, float_num)
print("1.", txt1)  # 1. 알파벳:ABC 정수:10 소수:123.46

# 값 변경 → 실패
name = "EFG"
int_num = 20
print("2.", txt1)   # 2. 알파벳:ABC 정수:10 소수:123.46

# 값 변경 → 성공 [재정의]
txt1 = "알파벳:%s 정수:%d 소수:%.2f" % (name, int_num, float_num)
print("3.", txt1)   # 3. 알파벳:EFG 정수:20

[오답]

int(2.5) + int(3.8) > int(str(1) + str(2)) → [ True/False ]

 

⑵ 추상화

Abstraction:중요한 특징만 Tag화하여 사용 - 변수/함수/객체

① 변수/상수, =, Syntactic sugar

a. 변수

def. 변수 : 값의 위치(=주소)를 기억하는 저장소(address)

값의 위치 : 값이 위치하고 있는 메모리 주소(Memory address)

즉, 변수란 값이 위치하고 있는 메모리 주소에 접근하기 위해서

사람이 이해할 수 있는 언어로 명명한 식별자(Identifier)이다.

 

b. 상수

상수(constant) : 대문자로 표시 → But, 프로그램상의 강제성은 없는, 그냥 프로그래머들만의 룰

만든 이유, 1. 변수/상수를 구분하기위해서 2. 상수이니 재정의하는 실수를 줄이기 위하여

PI = 3.14

# 원의 넓이 계산 : 파이 알 제곱
def calculate_area(r):
	return (PI * (r**2))


radius = 4
print(f"r={radius} → s={calculate_area(radius):.1f}")
# r=4 → s=50.2


radius += 1
print("r={} → s={}".format(radius, calculate_area(radius)))
# r=5 → s=78.5

* TIP : print()함수에서, end = "□string type data□" → 다음 출력값과 붙이기

print("Life is too short,", end=" ")
print("You need Python.")

# Life is too short, You need Python.

c. 지정연산자 =

지정연산자 ②오른쪽:재정의←①왼쪽:계산

1) 변수 X가 가리키는 Memory address에 찾아가서 살고있는 값을 만난다.

2) 그 값1을 더한다.

3) 계산값을 다른 Memory address에 넣어둔다.

4) 변수 X가 가리키는 Memory address를 업데이트한다.

 

d. Syntactic sugar

Read ability ↑

x = 1

x += 1		# 합 	  x = x + 1 = 2
x *= 2		# 곱 	  x = x * 2 = 4
x **= 2		# 거듭제곱 x = x ** 2 = 16
x /= 2		# 나누기   x = x / 2 = 8.0 [Float 변환]
x //= 2		# 몫		  x = x // 2 = 4.0
x %= 2		# 나머지	x = x % 2 = 0.0

 

② 함수의 실행순서

- 정의는 Skip

- return : 해당 함수 즉시 종료 & 원 위치

실행순서 예시 + Dead code를 굳이?

③ Optional parameter

- Optional parameter : 파라미터의 기본값 = 별다른 입력이 없으면 자동으로 채울 값

- 중요 규칙 : Optional은 무조건 positional parameter의 뒤여야 함

[remark] 함수명 ≠ 함수명(···)

- print(□) : 주소값 출력 ≠ 리턴값 출력

- type(□) : <class 'function'> ≠ <class '리턴값의 타입'>

- 함수() : 함수(□의 주소값) 실행 & 함수(리턴값)

- type(return) : 실행불가 Err

print(type(return))  # SyntaxError: invalid syntax

④ Scope : global & local

- scope : 변수의 사용가능범위

- 동명이인인 변수들 중 어떤 상황에 누가 불려가는지 살펴보자

x = 10					# global x


def scope_x(x):  		# local x
    print(f"x : {x}")  	# local x > global x
    x += 1				# local
    print(f"x : {x}")	# local


scope_x(1)
#>> x : 1   → local x
#>> x : 2   → local x

print(f"x : {x}")
#>> x : 10  → global x

"""
x : 1
x : 2
x : 10
"""

 

- 동명이인없이, Local 구역에서 global 변수를 사용하려면?

1. global 변수를 print( )로만 사용하는 경우 - OK

x = 10					# global x


def scope_x():          # 파라미터가 없음
    print(f"x : {x}")  	# global x : 로컬변수없으니까


scope_x()               # global x
print(f"x : {x}")       # global x

"""
x : 10
x : 10
"""

2-1. global 변수의 값을 변경하는 경우 - 그냥 변경 → Err

# UnboundLocalError : local variable 'x' referenced before assignment

x = 10					# global x


def scope_x():          # 파라미터가 없음
    print(f"x : {x}")  	# Err : <로컬변수>를 할당도 안해놓고 호출
    x += 1
    print(f"x : {x}")


scope_x()

2-2. global 변수의 값을 변경하는 경우 - global 변수명 → 해결

# [해결] UnboundLocalError : local variable 'x' referenced before assignment

x = 10					# global x


def scope_x():			# local x 없음(=동명이인 없이 global만 있는 경우)
    global x            # ★
    print(f"x : {x}")
    x += 1
    print(f"x : {x}")


scope_x()
print(f"x : {x}")

"""
x : 10		# global x
x : 11		# global x
x : 11		# global x
"""

2-3. global, local 동명이인이 동시에 존재하는 경우 - Err

# SyntaxError: name 'x' is parameter and global

x = 10					# global x


def scope_x(x):         # local x (parameter)
	global x

⑤ return VS print

⑥ Style Guide

PEP8 Style Guide for Python Code

바로 번역을 해보려했는데, 파이썬 지식이 얕아서 번역이 불가했음....

파이썬에 대해서 적어도 문법적으로 다 알 때쯤, 꼭 한번 쏵 번역해보고싶음.

코드잇에서 간략히 언급해 준 스타일과, 내가 대충 이해한 스타일 가이드

[Naming]

- 여러 단어가 이어질 경우 _로 띄어 줄 것 ← 다닥다닥 붙이기X

- 변수&함수는 소문자, 상수는 대문자

- 의미있는 이름 : 이름만 보고도 전세계 프로그래머들이 그것의 역할을 가늠할 수 있도록

[Indentation] 들여쓰기

- 들여쓰기 1Lv = 스페이스바 4개

[Blank Lines] 개행

- 함수 정의는 위/아래로 빈 줄 2개 = 뾱뾱이 감싸기

Surround top-level function and class definitions with two blank lines.

Method definitions inside a class are surrounded by a single blank line.

[Whitespace] 띄어쓰기

- 괄호 안 쪽은 붙여쓰기

Immediately inside parentheses(), brackets[], or braces{}

- 함수명과 괄호 사이 붙여쓰기(+Index나 Slice할 때에도 붙여쓰기)

Immediately before the open parenthesis that starts the argument list of a function call

Immediately before the open parenthesis that starts an indexing or slicing

- , ; : 의 앞은 붙여쓰기 = 앞 붙 뒤 띄

Immediately before a comma, semicolon, or colon ( before = '앞' 前)

* list index slice에 관한 스타일가이드는 일단 skip함

However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted.

 

- 이항연산자는 앞뒤로 띄어쓰기 : Surround with a single space (* = 는 예외가 있음: assign VS indicate)

이항 연산자가 여러 개 있다면, 우선순위 높은 연산은 붙여쓰기(먼저 해야한다는 의미로)

Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).

If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator.

Don't use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter.

- = 의 역할이 assignment 할당이 아니라, indicate 인 경우는 다 붙일 것: Don't use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter.

- Between a trailing comma and a following close parenthesis : omit whitespace

[Comment]

- 코드와 모순되는 코멘트는 안 하니만 못 함, 코드 변경 시 꼭! 관련 코멘트도 업데이트 할 것

Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!

- 첫 글자는 대문자 & 완벽한 문장형 ; identifier(항상 소문자로 써야하는) 가 아닌 이상 첫 글자는 대문자

Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).

- Block comment (덩어리)의 경우, 마침표로 끝나는 완벽한 문장들로 이뤄진 문단으로 구성되어야 함.

Block comments generally consist of one or more paragraphs built out of complete sentences, with each sentence ending in a period.

- 여러 문장의 경우, 문장 사이는 2칸 띄어줄 것

You should use two spaces after a sentence-ending period in multi- sentence comments, except after the final sentence.

- 영어로 / 간단명료하게/ 이해하기 쉽게

Ensure that your comments are clear and easily understandable to other speakers of the language you are writing in.

Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don't speak your language.

- # Block Comments : # + single space + comment

- # Inline Comments : 코드와 comment를 한 줄에 사용 정말 도움될 때만 쓰자 Use inline comments sparingly.

- """ Documentation Strings(a.k.a. "docstrings") : """ 할말 """

public module, function, class, method를 정의할 때, def 앞에 먼저 써두기

Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.

PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself.

 

[읽고 싶은 책 발견] : Effective Python 2nd 이펙티브 파이썬 : 파이썬 코딩의 기술

⑶ 제어문

조건부동작 & 반복동작

a. while "반복"

b. if (elif / else) "조건부수행"

몫은 quotient, 나머지 modulo & remainder

[Keyword]

#자료형:type/연산자/반올림/포맷팅

- 자료형&형변환 : int, float, str, bool (★ float→int내림)

- func.returns the type of value : type()

- 연산자 : + - * / ** // % + and or not 논리 + == != >= <= 비교

- 문자열에 개행 " ' \ 을 저장하고 싶은 경우 : \n \" \' \\

- 반올림 : round & decimal

- String formatting : ①.format() method ②f-string ③%

#추상화:변상수/함수순서/리턴≠출력/end="str"

- 변수 : 지정연산자 = / Syntactic sugar += / Scope G&L / optional parameter 後 / CONSTANT

- 함수 : 처리순서 #dead code / return ≠ print

- PEP8 스타일 가이드 잘 지켜

+ end="str"

#제어문:while반복/if,elif,else조건

- 반복 수행 : while (+break, continue) & 조건부 수행 : if elif else

+ 변수연속정의 (x, y, x) = (1, 2, 3)

+ False None 0 "" '' () {} []

 

[Remark]

#갑자기 빡세졌어

 


컴퓨터개론Course

 컴퓨터개론 - 📺   📝 - 🎖수료증

*Link : 📺인강  📝정리노트

 

반응형

블로그의 정보

노력하는 실버티어

노실언니

활동하기