2개 이상의 프로젝트를 개발하게 될 경우 버전 등의 호환성 문제가 발생을 방지하기 위한 것으로
각 프로젝트마다 독립적인 환경을 구성하여 호환성 문제를 최소화 시킬 수 있습니다.
# snake_case는 변수/함수명의 단어와 단어 사이에 _(under_bar)를 넣는다
in_python_snake_naming = 'snake_case'
#PascalCase는 변수/함수명의 단어와 단어 사이의 알파벳을 대문자로 구분짓는다
class PythonPascalNaming:
def naming:
...
python을 포함한 대부분의 언어에는 '변수 유효 범위'라는 개념이 있다.
변수가 선언된 위치나 키워드에 따라 변수를 사용할 수 있는 범위가 달라지게 되는데,
이를 변수 유효 범위 혹은 variable scope라고 부른다.
유효 범위에 따라 지역변수(local variable) , 전역변수(global variable)로 나뉜다.
지역 변수는 함수 내부에서 선언되며 다른 함수에 영향을 끼치지 않는다.
#지역변수(local variable)로 해당 변수는 함수 밖에서 호출 할 수 없다.
def func_is:
local_var = 'local_variable'
print(local_var) #NameError : name 'local_var' is not defined
전역 변수는 함수 밖에서 선언되며 어디서든 접근할 수 있다.
#전역변수(global variable)은 어디서든 호출 가능하다.
global_var = 'global_variable'
def func_is:
print(global_var)
print(global_var)
주의할 점
함수 내에서 전역 변수의 값을 바꾸려 할 경우
number = 10
def func():
global number # 함수에서 number 변수를 다시 할당할 수 있도록 해줍니다.
number = 5 # global 키워드를 사용했기 때문에 전역 변수의 값이 변경됩니다.
func()
print(number) # 5
전역변수의 사용을 권장하지 않는 이유
integer = 10
float_ = 1.23
string = "hello world!!"
print(type(integer)) # <class 'int'>
print(type(float_)) # <class 'float'>
print(type(string)) # <class 'str'>
# split은 string.split("구분자")로 구성되어 있습니다.
string = "hello/python/world!!"
string_list = string.split("/") # split() 안에 들어간 값을 기준으로 문자를 나눈다.
print(string_list) # ['hello', 'python', 'world!!']
# join은 "사이에 들어갈 문자".join(리스트) 로 구성되어 있습니다.
string_list = ["hello", "python", "world"]
string = "!! ".join(string_list)
print(string) # hello!! python!! world
# replace는 "변경할 문자".replace("변경 전 문자", "변경 후 문자")로 구성되어 있습니다.
before_string = "hello world!!!"
after_string = before_string.replace("!", "~") # !를 ~로 변경
print(after_string) # hello world~~~
# pprint는 pretty print의 약자이며, 데이터를 더 예쁘게 출력해 줍니다.
from pprint import pprint
sample_data = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{"id": "1001", "type": "Regular"},
{"id": "1002", "type": "Chocolate"},
{"id": "1003", "type": "Blueberry"},
{"id": "1004", "type": "Devil's Food"}
]
},
"topping":
[
{"id": "5001", "type": "None"},
{"id": "5002", "type": "Glazed"},
{"id": "5005", "type": "Sugar"},
{"id": "5007", "type": "Powdered Sugar"},
{"id": "5006", "type": "Chocolate with Sprinkles"},
{"id": "5003", "type": "Chocolate"},
{"id": "5004", "type": "Maple"}
]
}
pprint(sample_data)
# 난수 생성, 임의의 번호 생성 등 랜덤한 동작이 필요할 때 사용
import random
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
random.shuffle(numbers) # numbers를 무작위하게 섞기
print(numbers) # [2, 8, 6, 4, 3, 7, 1, 5]
random_number = random.randint(1, 10) # 1 ~ 10 사이의 무작위 번호 생성
print(random_number) # 4
import time
start_time = time.time() # 현재 시간 저장
time.sleep(1) # 1초간 대기
end_time = time.time()
# 코드가 종료된 시간 - 코드가 시작된 시간으로 실행 시간 구하기 (단위 : 초)
print(f"코드 실행 시간 : {end_time-start_time:.5f}") # 코드 실행 시간 : 1.00100
from datetime import datetime, timedelta
# 현재 날짜 및 시간 출력
print(datetime.now()) # 2023-02-22 15:55:32.277095
# datetime의 format code 더 제세한건 여기서 확인 가능합니다.
'''
%y : 두 자리 연도 / 20, 21, 22
%Y : 네 자리 연도 / 2020, 2021, 2022
%m : 두 자리 월 / 01, 02 ... 11 ,12
%d : 두 자리 일 / 01, 02 ... 30, 31
%I : 12시간제 시간 / 01, 02 ... 12
%H : 24시간제의 시간 / 00, 01 ... 23
%M : 두 자리 분 / 00, 01 ... 58, 59
%S : 두 자리 초 / 00, 01 ... 58, 59
'''
# string을 datetime 날짜로 변경하기
string_datetime = "23/12/25 13:20"
datetime_ = datetime.strptime(string_datetime, "%y/%m/%d %H:%M")
print(datetime_) # 2023-12-25 13:20:00
# datetime 날짜를 string으로 변환하기
now = datetime.now()
string_datetime = datetime.strftime(now, "%y/%m/%d %H:%M:%S")
print(string_datetime) # 22/09/04 04:04
# 3일 전 날짜 구하기
three_days_ago = datetime.now() - timedelta(days=3)
print(three_days_ago) # 2023-02-19 16:27:52.526502