파이썬 Study

2. 추상화

유요남 2022. 1. 16. 10:55

#def

 

ex.1)

def hello() :

     print("Hello!")

     print("Welcome to Codeit!"

print("함수 호출 전")

hello()

print("함수 호출 후")

 

함수 호출 전

Heppo!

Welcome to Codeit!

함수 호출 후

 

ex.2)

def square(x):

     return x * x

print("함수 호출 전")

print(square(3) + square(4))

print("함수 호출 후"

 

#return

 

- 역할 : 함수 즉시 종료, 값 돌려주기

 

def square(x):

     print('함수 시작")

     return x * x

     print("함수 끝")

print(square(3))

print("Hello World!")

 

3입력하면 return 값으로 x로 입력 (값 돌려주기)

return 3 * 3 = 9 이하 print("함수 끝")은 나오지 않음 (함수즉시 종료)

 

def print_square(x):

     print(x * x)

 

def get_sqrare(x):

     return x* x

 

print(get_square(3))

print(print_square(3)) 리턴값 없으면 None 로 출력

 

#파라미터

 

'기본갑(default value)" 설정 가능

옵셔널 파라미터(optional parameter) : 필수로 넘겨 줄 필요가 없어서 "옵셔널"

 

ex.1)

del myself(name, age, nationality="한국")

     print("내 이름은 {}".format(name))

     print("나이는 {}살".format(age))

     print("국적은 {}".format(nationality))

 

myself("코드익", 1, "미국") # 옵셔널 파라미터를 제공하는 경우

print()

myself("코드잇", 1) # 옵셔널 파라미터를 제공하지 않는 경우

 

내 내이름은 코드잇

나이는 1살

국적은 미국

 

내 이름은 코드잇 

나이는 1살

국적은 한국

 

참고)

옵셔널 파라미터는 모두 마지막에 있어야 한다

중간에 넣으면 오류 발생

 

def myself(name, nationality="한국", age): 

- 옵셔널 파라미터 뒤에 일반이 오면 안된, 여러개 가능

 

# Syntactic Sugar

자주 쓰이는 표현을 더 간략하게 쓸 수 있게 해주는 문법

 

다음 두 줄은 같습니다.

 

x = x + 1

x += 1

 

x =  x + 2

x += 2

 

x = x * 2

x *= 2

 

x = x - 3

x -= 3

 

x = x / 2

x /= 2

 

x = x % 7

x %= 7

 

 

#scope(범위)

 

ex.1) 로컬변수

def my_function(): #로컬변수 범위내에서 x=3 이 유효

     x = 3  (로컬 변수)

     print(x)

my function()

print(x) (error)

 

ex.2) 글로벌변수

x = 2 (글로벌 변수)

def my_function():

     print(x)

my_function()

print(x)

 

ex.3)

x = 2

def my _function():

     x = 3

     print(x)

my_function()  -> 3

print(x)  -> 2

 

ex.4) 파라미터도 로컬변수

def square(3):

     return x * x

print square(3)

 

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

- 로컬 변수 : 변수를 정의한 함수 내에서만 사용 가능

- 글로벌 변수 : 모든 곳에서 사용 가능

- 함수에서 변수를 사용하면, 로컬 변수를 먼저 찾고 나서 글로벌 변수를 찾음

 

ex.5)

x = 2

 

def my(x):

     x = x + 1

     print(x)

 

my()

 

 

#상수(constant)

 

대문자로 표기 : 이름을 바꾸지 않겠다.

일반변수가 아닌 상수

 

PI = 3.14

 

def calculate_area(r):

     return PI = r* r

 

radius = 4  # 반지름

print("반지름이 {}면, 넓이는 {}".format(radius, calculate_area(radius)))

 

 

#스타일

 

#PEP8 규칙

이름

이름 규칙

모든 변수와 함수 이름은 소문자로 써 주시고, 여러 단어일 경우 _로 나눠 주세요.

# bad
someVariableName = 1
SomeVariableName = 1

def someFunctionName():
    print("Hello")


# good
some_variable_name = 1

def some_function_name():
    print("Hello")

모든 상수 이름은 대문자로 써주시고, 여러 단어일 경우 _로 나눠주세요.

# bad
someConstant = 3.14
SomeConstant = 3.14
some_constant = 3.14


# good
SOME_CONSTANT = 3.14

의미 있는 이름

# bad (의미 없는 이름)
a = 2
b = 3.14
print(b * a * a)


# good (의미 있는 이름)
radius = 2
pi = 3.14
print(pi * radius * radius)
# bad (의미 없는 이름)
def do_something():
    print("Hello, world!")


# good (의미 있는 이름)
def say_hello():
    print("Hello, world!")

화이트 스페이스

들여쓰기

들여쓰기는 무조건 스페이스 4개를 사용하세요.

# bad (스페이스 2개)
def do_something():
  print("Hello, world!")


# bad (스페이스 8개)
i = 0
while i < 10:
        print(i)


# good (스페이스 4개)
def say_hello():
    print("Hello, world!")

함수 정의

함수 정의 위아래로 빈 줄이 두 개씩 있어야 합니다. 하지만 파일의 첫 줄이 함수 정의인 경우 해당 함수 위에는 빈 줄이 없어도 됩니다.

# bad
def a():
    print('a')
def b():
    print('b')

def c():
    print('c')



# good
def a():
    print('a')


def b():
    print('b')


def c();
    print('c')

괄호 안

괄호 바로 안에는 띄어쓰기를 하지 마세요.

# bad
spam( ham[ 1 ], { eggs: 2 } )


# good
spam(ham[1], {eggs: 2})

함수 괄호

함수를 정의하거나 호출할 때, 함수 이름과 괄호 사이에 띄어쓰기를 하지 마세요.

# bad
def spam (x):
    print (x + 2)


spam (1)


# good
def spam(x):
    print(x + 2)


spam(1)

쉼표

쉼표 앞에는 띄어쓰기를 하지 마세요.

# bad
print(x , y)


# good
print(x, y)

지정 연산자

지정 연산자 앞뒤로 띄어쓰기를 하나씩만 해 주세요.

# bad
x=1
x    = 1


# good
x = 1

연산자

기본적으로는 연산자 앞뒤로 띄어쓰기를 하나씩 합니다.

# bad
i=i+1
submitted +=1


# good
i = i + 1
submitted += 1

하지만 연산의 "우선 순위"를 강조하기 위해서는, 연산자 앞뒤로 띄어쓰기를 붙이는 것을 권장합니다.

# bad
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)


# good
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

코멘트

일반 코드와 같은 줄에 코멘트를 쓸 경우, 코멘트 앞에 띄어쓰기 최소 두 개를 해 주세요.

# bad
x = x + 1# 코멘트


# good
x = x + 1  # 코멘트
 

# 원의 둘레, 넓이 계산

 

PI = 3.14

 

# 반지름이 r인 원의 둘레 계산

def calculate_circumference(r):

     return 2 * PI * r

 

# 반지름이 r인 원의 넓이 계산

def calculate_area(r):

     return PI * r * r

 

radius = 4 # 반지름

print(calculate_circumference(radius))

print(calculate_area(radius))

 

radius = 8

print(calculate_circumference(radius))

print(claculate_area(radius))

 

# 짝수, 홀수 

 

def is_evenly_divisible(number):

     return number % 2 == 0  # 불리 개념

 

print(is_evenly_divisible(3))

print(is_evenly_divisible(7))

print(is_evenly_divisible(8))

print(is_evenly_divisible(218))

print(is_evenly_divisible(317))

 

# 거스름돈 계산기

 

def calculate_change(payment, cost):
     change = payment - cost  # 코드를 작성하세요.
    
     fifty_count = change // 50000  # 50,000원 지폐
     ten_count = (change % 50000) // 10000  # 10,000원 지폐
     five_count = (change % 10000) // 5000 # 5,000원 지폐
     one_count = (change % 5000) // 1000 # 1,000원 지폐
    
     print("50000원 지폐: {}장".format(fifty_count))
     print("10000원 지폐: {}장".format(ten_count))
     print("5000원 지폐:{}장".format(five_count))
     print("1000원 지폐:{}장".format(one_count))
    
# 테스트
calculate_change(100000, 33000)
print()
calculate_change(500000, 378000)

'파이썬 Study' 카테고리의 다른 글

[Python] 파이썬 모듈  (0) 2022.02.03
4. 토픽  (0) 2022.01.21
3. 제어문  (0) 2022.01.17
1. 자료형  (0) 2022.01.05