2.python 이론

4 minute read

1. Data Types of Python

1.1 variable

variable : 변수 , 우리 정보를 넣는 곳, 데이터를 저장하는 곳

  • 파이썬에서의 변수 선언은 값에 의해 타입이 정해진다.
a = 2
b = "안녕"
print(a)
# int
print(b)
# str
  • 긴 변수명을 작성할때 단어끼리 분리되길 원하는데, 파이썬에서는 snake case로 작성한다.
a_string = "like this"
a_number = 3
a_float = 3.12
a_boolean = False
a_none = None

1.2 문자열타입(string)

문자열(string)은 반드시 따음표나, 쌍 따음표에 둘러쌓여 있어야한다.

  • 주의할점 : 쌍따음표로 시작했으면 쌍따옴표로 끝나야하며, 따옴표로 시작했으면 따옴표로 끝나야한다.

  • bad example

a = "like this'
b = 3
  • good example
a = "like this"
b = 'like that'

1.3 boolean 타입(True or False)

boolean 타입은 참과 거짓을 나타내는것이다.

  • 주의할점

    • boolean 타입은 single quote(‘’) 나 two quote(“”) 로 나타낼경우, boolean 타입이 아닌 문자열이 된다.

    • true와 false는 대문자로 앞을 대문자로 써줘야한다.

    • boolean 타입에서 0을 제외한 모든 정수는 True이다.

  • bad example : 문자열로 인식함

a = "true";
b = "false";
  • good exmaple : 주의할점은 , 파이썬에서는 첫글자를 대문자로 써야한다.
a = True
b = False

1.4 정수와 실수

  • int : 정수는 소수점이 없는 자연수

  • float : 실수는 소수점이 있는 수

a_number = 3
a_float = 3.12
print(type(a_number))
# result : int
print(type(a_float))
# reulst : float

1.5 None 타입

  • None 은 존재하지 않는다, 참 또는 거짓이라는 뜻도 아닌 아무것도 없다라는 뜻이다.
a_none = Nome:
print(type(a_none))
#result : NoneType

2. Lists in Python

  • List를 쓰는 이유는 무엇일까?

리스트는 가변 시퀀스로, 일반적으로 비슷한 항목들의 모음을 저장하는 데 사용됩니다

  • List는 Mutable한 배열이다.

    • Mutable : 값을 바꿀수 있다. 기존에 값도 바뀐다.

    • Immutable : 원래의 기존의 값이 바뀌지 않는다.

days = ["Mon","Tue","Wed","Thur","Fri"]

print(type(days));
# reulst : list
print(days)
# result : ["Mon","Tue","Wed","Thur","Fri"]
days.append("Sat");
print(days)
# result : ["Mon","Tue","Wed","Thur","Fri","Sat"]

3. Tuples and Dicts

3.1 Tuples

  • Tuples를 쓰는 이유는 무엇일까?

튜플은 불변 시퀀스인데, 보통 이질적인 데이터의 모음을 저장하는 데 사용됩니다.

  • Tuples 는 immutable 하다.
days = ("Mon","Tue","Wed","Thur","Fri")

print(type(days));
# result : tuples

3.2 Dicts(Dictionary)

  • Dicts 를 쓰는 이유는 무엇일까?

관련된 데이터들의 모음

  • Dicts 는 객체이다. key와 value로 이루어짐

person = {
  "name" : "Jung",
  "age" : 27,
  "nation" : "Korea",
  "fav_food" :["Kimch","Sashimi"]
}

print(person["name"])
# result : Jung
person["handsome"] = True

print(person)

# {
#   "name" : "Jung",
#   "age" : 27,
#   "nation" : "Korea",
#   "fav_food" :["Kimch","Sashimi"],
#   "handsome" : True
# }


4. Built in Functions

  • 함수를 사용하는 이유는 무엇일까?

함수에는 하나의 기능만이 들어가며, 함수를 통해 그 기능을 반복해서 재사용할수 있기에, 함수를 사용한다.

5. Creating a Your First Python Function

  • 파이썬에서 함수 정의하는 법

    • 함수를 정의할때 def(define)으로 시작한다.

    • 파이썬은 들여쓰기로 function의 시작과 끝을 판단한다.(다른언어들은 {}를 사용함)

    • 만약 들여쓰기를 하지 않을경우, 오류 발생

def say_hello():
  print("hello")

say_hello();

#result : hello

6. Function Arguments

  • 함수의 아규먼트를 통해 값 전달하기
def say_hello(who):
  print("hello",who)

say_hello("Yosup");

#result : hello
  • 전달되는 아규먼트의 값이 정해지지 않을경우 오류가 발생한다.

bad example :

def plus(a,b):
  print(a+b)

def minus(a,b):
  print(a-b)

plus(2,5)
minus(2)
# result : TypeError: minus() missing 1 required positional argument: 'b'
  • 그러나 다음과 같이 default값을 추가함으로써 문제를 해결할수 있다.
def plus(a,b):
  print(a+b)

def minus(a,b=0):
  print(a-b)

plus(2,5)
minus(2)
# result : TypeError: minus() missing 1 required positional argument: 'b'
def say_hello(name ="anonymous"):
  print("hello",name)

say_hello()
# hello anonymous
say_hello("nico")
# hello nico

7. returns

  • 값을 돌려주는 return
def p_plus(a,b):
  print(a+b)

def r_plus(a,b):
  return a+b

p_result = p_plus(2,3)
r_result = r_plus(2,3)

print(p_result, r_result)
# None 5
  • return 다음에 선언한 문장은 실행되지 않는다, return 되는 순간 그 함수는 종료 된다 , 오직 한번에 하나의 값만 return 할수 있다.
def r_plus(a,b):

  return a+b
  print("안녕하세요")


r_result = r_plus(2,4)

print(r_result)
# result : 6

8. Keyworded Arguments

8.1 인자의 순서를 신경쓸 필요없이, 인자의 이름만으로도 인자가 전달된다.

def plus(a,b):
  return a-b

result = plus(b=30, a=1)
print(result)

# result : -29

8.2 string안에 변수를 포함시키기 위한 방법

  • 첫번째, plus를 이용하여 concat을 한다

def say_hello(name,age):
  return "Hello " + name + " you are " + age + "years old"

hello = say_hello("nico","12")
print(hello)

#result : Hello nico you are 12 years old

  • 두번째, string 안에 변수를 포함시키기 위해서는 f(format)를 사용한다.

def say_hello(name,age):
  return f"Hello {name} you are {age} years old"

hello = say_hello("nico","12")
print(hello)

#result : Hello nico you are 12 years old

9. if else and or

  • 조건문

    • 파이썬에서는 else if 대산 elif를 사용한다.
def age_check(age):
  print(f"you are {age}")
  if age < 18:
    print("you can't drink")
  elif age==18 or age == 19:
    print("you are new to this!")
  elif age> 20 and age<25:
    print("you are still kind of young")
  else:
    print("enjoy your drink")

age_check(29)

10. for in

  • for in 문 순환하면서 각각 하나씩 값을 받기 위한 방법

days = ("Mon", "Tue", "Wed", "Thu", "Fri")

for day in days:
  print(day)

# result
# Mon
# Tue
# Wed
# Thu
# Fri
  • for문을 중단할때 사용하는 break 문

days = ("Mon", "Tue", "Wed", "Thu", "Fri")

for day in days:
  if day is "Wed":
    break
  else:
    print(day)

  • String 도 이론적으로는 배열이기 때문에, for문을 사용하여 문자형을 하나씩 뺄수 있다.

for letter in "nicolas":
  print(letter)

# n
# i
# c
# o
# l
# a
# s

11. Modules

  • 파이썬에는 module이라는것이 내장되어 있는데, 기능의 집합으로 프로그램에서 import 해서 사용할수 있다.

11.1 모든 수학적 기능을 다 import 하고 싶을때

  • 그러나 전부 불러오면 용량이 커진다거나 실행 속도가 느리다거나 하는 문제가 생김
import math

print(math.ceil(1.2))

# 2

print(math.fabs(-1.2))

# 1.2

11.2 수학적 기능중 특정 기능(함수)만 가져오고 싶을때

from math import ceil, fsum

print(ceil(1.2))
print(fsum([1,2,3,4,5,6,7]))

11.3 수학적 기능중 특정 기능의 이름을 내가 원하는 이름으로 바꾸고 싶을때

from math import fsum as yosup_sum

print(ceil(1.2))
print(yosup_sum([1,2,3,4,5,6,7]))

Leave a comment