조코링 2022. 7. 4. 12:04

Data Types

variable(변수): 데이터를 저장하는 곳, 변수명 = 데이터
변수명을 여러 단어로 지을 경우 _로 연결하는 것이 일반적(snake case)

None Sequence Types

  • integer a_int = 3
  • float b_float = 2.5
  • boolean d_bool = True
  • none = e_none = None

Sequence Types

  • string c_str = "Hello World" --- ", ' 둘 다 가능
  • list f_list = ["Mon", "Tue", "Wed", "Thur", "Fri"] --- mutable(수정 가능)
  • tuple g_tuple = ("Mom", "Dad", "Me") --- immutable(수정 불가능)
  • dictionary h_dict = {"name": "Nico", "age": 29}

    서로 다른 타입의 값들을 하나의 변수에 넣을 수 있음


Function

특정 기능을 반복할 수 있도록 만든 것

Built-in Functions

  • Python에서 기본적으로 제공하는 함수들
  • print(): 콘솔에 출력
  • len(): 길이를 구함
  • type(): 타입을 알려줌
  • int(), float(), str(), bool(), list(), tuple(), dict(): 다른 타입의 값을 해당 타입으로 변환

Define Function

# name의 기본값을 Anonymous로 지정
def hello(name="Anonymous", age):
    # String에 변수를 삽입하려면 f를 따옴표 앞에 붙이고 변수를 중괄호로 감싸줌
    print(f"Hello {name} you are {age} years old")
    result = f"Bye {name}"
    return result
    # return이 실행되면 함수는 그대로 종료되어 이후의 코드를 실행하지 않음
    print("No")

# Positional arguments --- 입력한 순서대로 인자를 넘김
greeting1 = hello("Nico", 29)

# Keyword arguments --- 인자 이름 = 값으로 넘겨서 순서에 상관 없음
greeting2 = hello(age=29, name="Nico")

print(greeting1)
print(greeting2)

# 결과는 똑같음
# Hello Nico --- hello 함수 내부의 print
# Bye Nico --- hello 함수의 return값이 저장된 greeting을 print

들여쓰기로 함수 코드를 판단하므로 들여쓰기에 주의! 들여쓰기는 tab과 spacebar를 섞어서 쓰지 말 것!


Conditionals

if-elif-else

def age_check(age):
    if age < 18:
        print("you can\'t drink")
    elif age == 18:
        print("you are new to this")
    else:
        print("enjoy your drink")

age_check(17)
age_check(18)
age_check(19)

and, or, not 등을 사용해서 여러 조건을 연결할 수 있고, elif는 여러 번 사용할 수 있음


Loops

for in

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

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

Sequence 타입의 요소를 순차적으로 하나씩 사용해서 반복 작업 수행


Modules

from math import ceil, fabs
from math import fsum as fs

print(ceil(1.2))
print(fabs(-1.2))
print(fs([1, 2, 3, 4, 5, 6]))
  • 함수들의 집합, import해서 사용할 수 있음
  • 자주 사용하는 모듈: math, datetime, json, csv 등
  • 사용하지 않는 기능들을 모두 import하는 것은 비효율적이기 때문에 사용할 것만 import하기
  • as를 사용해 이름을 바꿔서 사용할 수 있음

※ 더 많은 내용은 공식문서 참고
※ 강의 링크: https://nomadcoders.co/python-for-beginners