Variables, Function, Console & I/O, Conditinals, Loops
변수(Variable)은 data, 값을 저장하기 위한 메모리 공간의 프로그래밍 상 이름.
a = 5
b = 3
a + b
8
그럼 변수는 어디에, 어떻게 저장되는 걸까?
"a = 5" -> Application -> OS -> CPU -> Memory
변수는 메모리 주소를 가지고 있고,
변수에 들어가는 값은 메모리 주소에 할당이 되는 방식이다.
data type 이란 파이썬이 처리할 수 있는 데이터 유형이다.

각 자료형마다, 차지하는 메모리의 공간이 다 다르다.
파이썬은 동적 타이핑 언어이다.
이는 코드 실행시점에 데이터의 type을 결정해주는 언어라는 뜻이다.
예를 들어, 변수에 정수형 값을 넣을 때,
파이썬은 그냥 "a = 1" 을 적는데,
다른 언어와 다르게 integer라고 굳이 적어주지 않아도 된다.
1) 형 변환
10.3과 10.7을 정수형으로 형변환 후, 덧셈하면 어떤 결과가 나올까?
a = 10.7
b = 10.3
a = int(a)
b = int(b)
print(a+b)
20
int형으로 자료형 변환 시, 소수점 버림.
2) 컴퓨터의 반올림 오차
아래와 같이 결과가 나오는 이유는 뭘까?
c = 38.8
print(c)
38.8
c
38.799999999999997
왜지?
컴퓨터의 모든 값은 이진수로 변환되어 메모리에 저장되기 때문
3) 0.1을 이진수로 변환하라
0.1 x 2 = 0.2 -> 0
0.2 x 2 = 0.4 -> 0
0.4 x 2 = 0.8 -> 0
0.8 x 2 = 1.6 -> 1
0.6 x 2 = 1.2 -> 1
0.2 x 2 = 0.4 -> 0 .........
0.00011001100110011 ... ... (2)
단순한 실수도 이진수로 변환하면 무한소수가 된다.
반올림 오차는 충분히 작아서 반올림을 하여 일반적으로 문제가 되지는 않는다.
integer - 32bit
float - 64bit
컴퓨터는 왜 이진수를 쓰는가?
컴퓨터는 실리콘이라는 재료로 만든 반도체로 구성.
반도체란, 특정 자극을 주었을 때 전기가 통할 수 있도록 하는 물질
도체와 부도체에 반해, 반도체는 전류의 흐름의 제어가 가능
전류가 흐를 때, 1 그리고 흐르지 않을 때, 0으로 표현할 수 있음.
이진수 한자리를 bit라 칭하고 8개의 bit는 1byte
만약 데이터가 100개가 있다면 이를 어떻게 관리할 것인가?
100개의 변수를 만들어 관리하나?
list 자료형을 사용하면, 하나의 변수를 만들어 관리할 수 있다.

1) indexing
2) slicing
3) list 연산
4) 원소 추가, 삭제
5) 메모리 저장 방식
a = [5, 4, 3, 2, 1]
b = [1, 2, 3, 4, 5]
b = a
print(b)
[5, 4, 3, 2, 1]
a.sort()
print(b)
[1, 2, 3, 4, 5]
6) packing & unpacking
t = [1, 2, 3]
a, b, c = t
print(t, a, b, c)
[1, 2, 3] 1 2 3
7) 이차원 list
kor_score = [49, 79, 20, 100, 80]
math_score = [43, 59, 85, 30, 90]
eng_score = [49, 79, 48, 60, 100]
midterm_score = [kor_score, math_score, eng_score]
print(midterm_score[0][2])
20
import copy
midterm_copy = copy.deepcopy(midterm_score)
midterm_score[0][0] = 100
midterm_copy[0][0]
49
midterm_score[0][0]
100
함수란? 어떤 일을 수행하는 코드의 덩어리.
def 함수이름(parameter #1, ..., ) :
수행문 #1(statements)
수행문 #2(statements)
return <반환값>
parameter은 함수의 input값 인터페이스
indentation 들여쓰기 이후, 함수의 statements를 작성
return value(optional) 반환값을 설정할 수 있는데 이는 선택적임.
argument는 실제 parameter에 대입된 값을 의미함.

0단계)
def calculate_rectangle_area(x, y):
return x * y
함수 정의 부분을 먼저 읽고 저장.
1단계)
rectangle_x = 10
rectangle_y = 20
print("사각형의 x 길이: ", rectangle_x)
print("사각형의 y 길이: ", rectangle_y)
메인 코드 실행 시작
함수 밖의 코드가 실행되기 시작함.
2단계)
print("사각형의 넓이: ", calculate_rectangle_area(rectangle_x, rectangle_y))
함수 호출 발견하면 바로 이전에 저장했던 함수로 돌아옴.
3단계)
def calculate_rectangle_area(x, y):
return x * y
함수 실행.
x에는 rectangle_x 값이 들어가고, y에는 rectangle_y 값이 들어감.
4단계)
print("사각형의 넓이: ", #return값 : 200)
메인 코드로 복귀. 마저 나머지 코드 실행.

parameter의 유무,return 값의 유무에 따라 함수의 형태를 구분할 수 있음.
shell 특성상, print문이 없어도 그 값을 보여줄 수 있다.
(앞전에 언급했던, sort vs sorted 떠올려보라)
어떻게 프로그램과 데이터를 주고 받을 것이냐??
input()함수는 콘솔창에서 문자열을 입력 받는 함수이다.
기본적으로 문자열로 입력받기 때문에,
형변환을 통해 내가 원하는 자료형으로 수정해서 입력받을 수 있다.
print문에서 type이 다른 경우 사이에 ','를 넣어주면 연결이 된다.
프린트문은 기본적인 출력 외에 출력의 양식의 형식을 지정할 수 있다.
1) % string
%-format 함수를 사용함.
print("I eat %d apples." %3)
print("I eat %s apples." % "five")
number = 3
day = "three"
print("I ate %d apples. I was sick for %s days." % (number, day))
print("Product : %s, Price per unit : %f." % ("Apple", 5.243))

"%datatype" %(variable) 형태로 출력 양식을 표현함.
(variable)안에는 두 개 이상의 값이 들어갈 수 있다.
2) str.format()
"~{datatype}~".format(argument)
age = 29
name = "Seung Beom"
print("I'm {0} years old".format(age))
print("My name is {0} and {1} years old.".format(name, age))
print("Product : {0}, Price per unit : {1:.3f}.".format("Apple", 5.243))
{} 안에 처음 들어오는 숫자는 뒤에 argument의 인덱스라고 볼 수 있고,
추가로, : 뒤에 data type도 정해줄 수 있다.

#%5s -> 5자리를 두고 거기에 채워라
print("Product : %5s, Price per unit: %.5f" % ("Apple", 5.243))
#{0:5s} -> 0번 인덱스를, 5자리 두고 거기에 채워라
print("Product : {0:5s}, Price per unit : {1:.5f}."format("Apple", 5.243))
#%10.3f -> 소수점 세자리 까지 표기하고 10자리 두고 거기에 채워라
print("Product : %10s, Price per unit : %10.3f." % ("Apple", 5.243))
#{0:>10s} -> 10자리 두고 거기에 채우되, 오른쪽 정렬하라
print("Product : {0:>10s}, Price per unit : {1:10.3f}.".format("Apple", 5.243))
#%d 나 %s 이런거 들어갈 자리에 변수를 넣어주고 뒤에{}에서 변수:값을 넣어줌 like dictionary
print("Product : %(name)10s, Price per unit : %(price)10.5f." % {"name" : "Apple", "price" : 5.243})
#{ 뒤에 인덱스 번호가 아닌 변수를 넣어서 출력할 수 있음. 해당 변수는 뒤에 argument 에서 변수 = 값 꼴로 넣어줌.
print("Product : {name:>10s}, Price per unit : {price:10.5f}.".format(name = "Apple", price = 5.243))
3) f-string
name = "Seung Beom"
age = 29
print(f"Hello, {name}. You are {age}.")
#Hello, Seung Beom. You are 29.
print(f"{name:20}")
#Seung Beom
print(f"{name:>20}")
# Seung Beom
print(f"{name:*<20}")
#Seung Beom**********
print(f"{name:*>20}")
#**********Seung Beom
print(f"{name:*^20}")
#*****Seung Beom*****
number = 3.14159265358979
print(f"{number:.2f}")
#3.14
조건문이란? 조건에 따라 특정한 동작을 하게 하는 명령어

a = 256
b = 256
print(a is b) #True
a = 257
b = 257
print(a is b) #False
>>>if 1 :
... print("True")
...else :
... print("False")
...
True
a = 8
b = 5
if a == 8 and b == 4 :
print("True")
else :
print("False")
#False

value = 12
is_even = True if value % 2 == 0 else False
print(is_even)
#True
boolean_list = [True, True, True, True]
all(boolean_list) # True
any(boolean_list)
반복문이란? 정해진 동작을 반복적으로 수행하게 하는 명령문
반복 범위를 지정하여 반복문을 수행하는 for 문
for i in "abcdefg" :
print(i)
#a
#b
#c
#d
#e
#f
#g
for i in ["americano", "latte", "frafuchino"] :
print(i)
#americano
#latte
#frafuchino
for i in range(1, 10, 2) :
print(i)
#1
#3
#5
#7
#9
for i in range(10, 1, -1) :
print(i)
range() 함수를 이용하여 반복 범위를 정해줄 수 있기 때문에 많이 사용된다.
조건이 만족하는 동안 반복 명령문을 수행하는 while 문
반복 실행횟수가 명확하지 않을 때, while문을 사용한다.
break는 특정 조건에서 반복을 종료할 수 있도록 함.
for i in range(10) :
if i == 5 : break
print(i)
print("EOP")
continue는 특정 조건에서 남은(아래 코드) 반복 명령을 skip함.
for i in range(10) :
if i == 5 : continue
print(i)
print("EOP")
else 문을 이용해서, 반복 조건이 만족하지 않을 경우 반복 종료 시 수행하는 구문을 설정할 수 있다.
#for with else
for i in range(10) :
print(i,)
else :
print("EOP")
#while with else
i = 0
while i < 10 :
print(i, )
i += 1
else :
print("EOP")
#1
sentence = "I love you"
reverse_sentence = ""
for char in sentence :
reverse_sentence = char + reverse_sentence
print(reverse_sentence)
#2
decimal = 10
result = ""
while (decimal > 0) :
remainter = decimal % 2
decimal = decimal // 2
result = str(remainder) + result
print(result)
#debugging loop
print("input decimal number : ")
decimal = int(input())
result = ""
loop_counter = 0
while (decimal > 0) :
temp_decimal_input = decimal
temp_result_input = result
remainder = decimal % 2
decimal = decimal // 2
result = str(remainder) + result
print("----------", loop_counter, "loop value check ----------")
print("Initial decimal:", temp_decimal_input,
", Remainder : ", remainder,
", Initial result", temp_result_input)
print("Output decimal : ", decimal,
"Output result: ", result)
print("--------------------------------------------------")
print("")
loop_counter += 1
print("Binary number is", result)
#숫자 맞추기
import random
guess_number = random.randint(1, 100)
print("숫자를 맞춰보세요 (1~100)")
user_input = int(input())
while (users_input is not guess_number) :
if users_input > guess_number :
print("숫자가 너무 큽니다.")
else :
print("숫자가 너무 작습니다.")
user_input = int(input())
else :
print("정답입니다.", "입력한 숫자는 ", user_input, "입니다.")
#구구단
print ("구구단 몇 단을 계산할까요(1~9)?")
x = 1
while (x is not 0):
x = int(input())
if x == 0: break
if not(1 <= x <= 9):
print ("잘못 입력하셨습니다", "1부터 9사이 숫자를 입력해주세요")
continue
else:
print ("구구단 " + str(x) +"단을 계산합니다.")
for i in range(1,10):
print (str(x) + " X " + str(i) + " = " + str(x*i))
print ("구구단 몇 단을 계산할까요(1~9)?")
print ("구구단 게임을 종료합니다")
#이차원 리스트 처리하기
student_score = [0,0,0,0,0]
i = 0
for subject in midterm_score:
for score in subject:
student_score[i] += score # 각 학생마다 개별로 교과 점수를 저장
i += 1 # 학생 index 구분
i = 0 # 과목이 바뀔 때 학생 인덱스 초기화
else:
a, b, c, d, e = student_score # 학생 별 점수를 unpacking
student_average = [a/3,b/3,c/3,d/3,e/3]
print (student_average)
#trapezium_area.py
def addition(x, y) :
return x+y
def multiplication(x, y) :
return x*y
def divided_by_2(x)
return x/2
def main() :
print(addition(10, 5))
print(multipication(10, 5))
print(divided_by_2(50))
#아래 코드는 파이썬 환경에서 실행하면 제일 먼저 실행한다는 뜻.
#python shell 환경에서는 __name__ 묶어놓으면 main함수가 자동으로 실행 x.
if __name__ == "__main__" :
main()
#shell 환경
>>>import trapezium_area as ta
#name으로 묶어놓았기 때문에 main함수 실행 x.
ta.addition(10, 5)
#15
ta.multiplication(10, 5)
#50
ta.divided_by_2(50)
#25
출처
https://www.boostcourse.org/precourse1/lecture/1547333?isDesc=false