내 생각/강의

[Udemy] Python for Beginners

호랑구야 2023. 10. 12. 09:00

* 강의를 듣고 주관적으로 내용을 정리한 글

0. 환경설정

Anaconda 업데이트

  • 아나콘다 업데이트
    • conda update -n base conda
  • 아나콘다 변경 가능한 파이썬 버전 확인
    • conda search python
  • 아나콘다 파이썬 버전 바꾸기
    • conda install python =3.12.0
  • 패키지 업데이트
    • conda update --all
  • Python PIP 업데이트
    • python -m pip install --upgrade pip
  • 파이썬 버전 확인
    • python --version

section3: Strings and Variables

  • Variables and Strings
  • Functions and Printing
  • String Methods
  • String Concatenation
  • Formatting Strings
  • Excercise

Variables and Strings

Variable, 변수는 이름을 가진 저장 장소이다.
변수 이름은 항상 문자로 시작해야 하고, 숫자와 Underscores , _, 를 포함할 수 있다.
Backslash, \, strings에 포함된 큰 따옴표, ", 혹은 작은 따옴표, ', 를 표현하게 하는데 사용된다.
String 은 index가 할당된다.

Functions and Printing

function,  함수는 이름을 가지고, 이름으로 호출되고 실행된다.
print() 함수는 buit-in 함수로 값을 화면에 표시한다.
len() 함수는 buit-in 함수로 string의 문자 수를 반환한다.
Nesting 함수는 data를 변수에 할당하는 중간 작업을 건너뛸 수 있다.

String Methods

객체 지향 프로그래밍 기초 사항, Object-Oriented-Programing.
Python에 있는 모든 것은 객체이다.
모든 객체는 type이 있다.
Methods는 객체 뒤에 Method 이름, 그리고 괄호 ()를 입력하고 매개변수가 있을 경우 괄호 안에 적어 실행한다.
object.method()
string의 lower() string method는 주어진 string의 소문자 형태를 반환한다.
string의 upper() string method는 주어진 string의 대문자 형태를 반환한다.

String Concatenation

plus sign, +, 주어진 string들을 연결하여 합친다.
asterisk, *, 는 반복 연산자다.
the formatted string * N-앞의 문자가 반복하길 원하는 횟수-.
str() 함수는 buit-in 함수로 non-strings을 strings으로 변환한다.

Formatting Strings

format method를 이용해 strings를 연결할 수 있다. 이때, 중괄호, pair of curly braces, {}를 넣고 싶은 위치에, string.format() 중 괄호 안에 넣고 싶은 값을 넣으면 된다.
.format() 내부 항목은 0부터 순서를 가진다. {}안에 숫자가 있을 경우 그 순서에 맞는 format 내부 항목의 값을 그 위치에 활용한다.
.format() 를 활용하면 숫자를 str() function을 이용해 변환하는 과정을 생략할 수 있다.
{}안에 colon, :, 을 활용하면 최소 너비를 문자열 갯수로 가질 수 있다. 콜론 앞의 숫자는 입력되기 바라는 항목의 순서를, 콜론 뒤의 숫자는 최소 너비를 문자열 크기로 나타낸다.
: 뒷쪽 숫자 앞에 다음의 표시를 하면, <은 왼쪽 정렬을, ^은 가운데 정렬을, >은 오른쪽 정렬을 나타낸다.
데이터 type을 실수로 할 때 f를, 소수점 아래 자릿수, N, 을 표현할 때, .Nf로 나타낼 수 있다.
input() 함수는 buit-in 함수로 키보드 타입한 것을 입력값으로 받아들인다.

Excercise #1

# Exercise 1:
animal = "cat"
vegetable = "broccoli"
mineral = "gold"

print("Here is an animal, a vegetable, and a mineral.")
print(animal)
print(vegetable)
print(mineral)

Excercise #2

# Exercise 2:
input("Please type something and press enter: ")
print("You entered:")

Excercise #3

# Exercise 3:
saying = input()
length = len(saying)
print(' ' * 12, '_' * length) # 12
print(' ' * 10, '< {} >'.format(saying)) # 10
print(' ' * 12, '-' * length) # 12
print('           /') # 11
print(' /\\_/\\    /') # 10
print('( o.o )')
print(' > ^ <')

section4: Numbers

  • Numbers
  • Numeric Operations
  • Integers
  • Floats
  • Comments
  • Excercise

Numbers

따옴표 없이 숫자를 쓰면 숫자로 활용할 수 있다.

Numeric Operations

+: 더하기
-: 빼기
*: 곱하기
/: 나누기
**: 거듭제곱하기
%: 나머지 연산하기

Integers

int() 함수에 숫자 혹은 string 타입으로 된 숫자를 넣으면 정수 형태가 된다.

Floats

float() 함수에 숫자 혹은 string 타입으로 된 숫자를 넣으면 실수 형태가 된다.

Comments

#: 을 활용하면 한 줄짜리 주석이 되고, Python은 이것을 무시한다.
""" : 으로 둘러싸인 내용은 여러 줄의 주석이 되고, Python은 이것을 무시한다.
주석을 이용하여 코드의 내용이 무엇인지, 아래의 변수가 무엇을 의미하는지 표현할 수 있다.

Excercise #1

# Exercise 1:

# hosting provider cost per hour
cost = 0.51

# cost of a day
day = cost * 24

# cost of a month
month = day * 31

print('It costs ${} to operate one server per day'.format(day))
print('It costs ${} to operate one server per month'.format(month))

Excercise #2

# Exercise 2:

# saving fund
fund = 918

# hosting provider cost per hour
cost = 0.51

# one server cost of a day
day = cost * 24

# twenty server cost of a day
day20 = day * 20

# one server cost of a month
month = day * 31

# twenty server cost of a month
month20 = month * 20

# days which can operate one server with $918
days = int(fund / day)

print('It costs ${} to operate one server per day'.format(day))
print('It costs ${} to operate one server per month'.format(month))

print('It costs ${} to operate twenty server per day'.format(day20))
print('It costs ${} to operate twenty server per month'.format(month20))

print('There are {} days to operate one server with ${}.'.format(days, fund))

section5: Booleans and conditionals

  • Booleans
  • Comparators
  • Order of Operations
  • Code Bolcks
  • Conditionals
  • Excercise

Booleans

Boolean은 True 혹은 False 값을 가지는 것이다.

Comparators

==: 같다.
>: 더 크다
>=: 더 크거나 작다
<: 더 작다
<=: 더 작거나 같다
!=: 같지 않다.
and: 두 문장이 모두 true 이어야 True로 평가한다.
or: 두 문장 중 하나만 true여도 True로 평가한다.
not: 문장의 반대로 평가한다.

Order of Operations

not → and → or
()로 쌓여있는 것 먼저 하고 나머지를 수행한다.

Code Bolcks

code block을 만드는 데에 2 spaces이거나 4 spaces 이어도 상관없다.
다만 코드 전체에 2 혹은 4로 통일해야 한다.

Conditionals

if-else: if 조건이 만족되면, 아래의 코드 블락에 있는 내용이 실행되고, 만족하지 않을경우 만약 else가 존재하면 아래의 코드 블락에 있는 내용이 실행되고, 만약 else가 없다면 아무것도 실행되지 않는다.
elif: if 조건을 만족하지 않고 elif 조건에 만족한다면 그 아래의 코드 블락에 있는 내용이 실행된다.
if, elif, else 중 순서에 따라 먼저 조건을 만족하는 하나의 코드 블럭만 실행된다.

Excercise #1

# Excercise 1:

# user에게 질문할 내용과 그 입력값을 변수로 함
miles = int(input('How far would you like to travel in miles? '))

# input 함수 실행
miles

if miles < 3:
    transport = 'walking'

# 위 if 조건문을 만족하지 않으므로, miles >= 3 인 조건이 아래에 자동 포함된다.
elif miles < 300:
    transport = 'driving'

# 위 elif 조건문을 만족하지 않으므로, miles >= 300 인 조건이 아래에 자동 포함된다.
else:
    transport = 'flying'
    
print('I suggest {} to your destination'.format(transport))

section6: Functions

  • Functions
  • Function parameters
  • Function documentation
  • Returning data from a function
  • Excercise

Functions

def 키워드를 활용해 자신만의 함수를 만들 수 있다.
def F_name():
    # codeBlock
함수를 부르는 방법:
F_name()

Function parameters

매개변수를 활용하고 싶은 경우 ()안에 매개변수를 넣고 호출할 때 인수값을 넣어야 한다.
F_name(parameterVal)
매개변수에 기본 인수값을 정할 수 있다. ()안에 매개변수 = 인수값을 함께 넣으면 된다.
def F_name(parameter = parameterVal):
    # codeBlock
함수 호출할 때 인수값을 넣지 않으면 기본 인수값이, 인수값을 넣으면 입력한 인수값이 적용된다.
F_name()
F_name(parameterVal)
매개변수가 여러개인 경우, 순서를 맞추어 호출하면 그 자리에 맞는 매개변수의 인수값으로 적용이 된다.
F_name(parameterVal_1, parameterVal_2)
매개변수 순서를 맞추지 않고 변수 이름을 넣어서 호출하는 경우도 가능하다.
F_name(parameter2 = parameterVal_2, parameter1 = parameterVal_1)

Function documentation

help() 함수를 이용하면, 함수의 설명 문서를 볼 수 있다.
이때, 함수의 설명 문서는 함수 내부에 존재하는 """로 둘러쌓인 부분이다.
help(F_Name)

Returning data from a function

함수에서 return 이후 나오는 것은 함수를 호출했을 때 반환되는 것이다.
def F_Name():
    return 'Hi'

> name = F_Name()
> name
>> 'Hi'

Excercise #1

# Excercise 1:

def wordType(Type):
    """Get a word from a user and return it."""
    if Type == 'adjective':
        article = 'an'
    else:
        article = 'a'

    return input('Please type {} {}: '.format(article, Type))


def fillStory(noun, verb, adjective):
    """Fill in the blanks and return a completed story. """

    # \ helps to continue lines and easier to read
    story = "Story starts. " \
            "Someday, {0} started to learn how to {1}. " \
            "{0} has been having some {2} time. " \
            "{0}, finally, did it! " \
            "Story ends. ".format(noun, verb, adjective)

    return story

def displayStory(story):
    """Display Story."""
    print('\nEnjoy the Story you created!!!\n{}'.format(story))
        
def wordGame():
    """ This is the function which can play word game.
        User enter a noun, verb, and an adjective.
        Those responses are used to fill in the balnks and display the story.
    """
    
    noun = wordType('noun')
    verb = wordType('verb')
    adjective = wordType('adjective')
    
    theStory = fillStory(noun, verb, adjective)
    displayStory(theStory)


help(wordType)
help(fillStory)
help(displayStory)
help(wordGame)

wordGame()

section7: Lists

  • Lists
  • Searching in Lists
  • Exception Handling
  • Slices
  • Sorting
  • Ranges
  • For Loop
  • While Loop
  • Excercise

Lists

list는 순서가 있는 항목들의 모음이다.
항목들의 데이터 타입을 다양하게 가질 수 있다.
리스트의 리스트를 가질 수 있다.
> list_Name = [item1, item2]

Searching in Lists

> list_Name[0]
>> item1
> list_Name[0] = item0
> list_Name[0]
>> item0
> list_Name[-1]
>> item2
> list_Name[-2]
>> item0
append() method는 항목 하나를 리스트 끝에 붙여준다.
> list_Name.append(item3)
> list_Name[-1]
>> item3
extend() method는 항목 여러 개를 리스트 끝에 붙여준다.
> list_Name.extend([item4, item5])
> list_Name
>> [item0, item2, item3, item4, item5]
insert() method는 특정 위치에 항목 하나를 리스트에 넣어준다.
> list_Name.insert(0, item1)
> list_Name
>> [item1, item0, item2, item3, item4, item5]

Exception Handling

> list_Name.index(item0)
>> 1
무언가가 존재하지 않을 때 python은 에러 메시지를 출력하고 코드가 멈춘다.
그런 상황을 막기 위해, 에러 메시지가 나올만한 상황일 때를 try-except로 방어한다.
try:

    tmp = list_Name[10]
except:
    tmp = 'Not Found'
print(tmp)

Slices

list_Name[index1:index2]
index1부터 (index2) - 1 순서까지 항목을 반환한다.
list_Name[index1:]
index1부터 끝 순서까지 항목을 반환한다.
list_Name[:index2]
처음부터 (index2) - 1 순서까지 항목을 반환한다.
> 'string'[1:3]
>> 'tr'

Sorting

sorted() 는 내장 함수로, list가 정렬된 버전을 보고 싶을 때 활용한다.
sorted(list_Name)
sort() method는 list가 정렬하고 싶을 때 활용한다.
list_Name.sort()

Ranges

range() 함수는 범위에 맞는 등차수열과 같은 리스트를 만들 수 있다.
range(start, stop, step)
start, start + step, ... (stop 순서가 오면 멈추고 값을 반환하지 않는다.)

For Loop

for문을 이용하면 리스트에 있는 항목에 접근할 수 있다.
for item in list_Name:
    # codeBlock

While Loop

while문을 이용하면 리스트에 있는 항목에 접근할 수 있다.
while condition:
    # codeBlock

Excercise #1

# excercise 1:

def getTask():
    
    """
    Get a task from a user.
    """
    
    # 사용자의 키보드 입력값을 저장하는 변수
    task = input('Enter a task for your to-do list. Press <enter> when done: ')
    
    return task

    
def ToDo():
    
    """
    Make a list within the tasks from getTask().
    """
    
    # task 항목을 저장할 리스트 변수
    todoList = []
    
    # do while문을 흉내냄
    # 일단 상단의 내용을 수행하고 조건문을 만난다.
    while True:
        
        # getTask()함수를 불러오는 변수
        task = getTask()
        
        # 만약 입력값의 길이가 0, 입력된 것이 없다면 반복문을 나가라
        if len(task) == 0:
            break
        
        # 입력값의 길이가 0이 아닌 경우, 입력된 것이 있다면 아래 내용을 수행하고 다시 처음으로 돌아가라
        else:
            todoList.append(task)
            print('Task added.')

    return todoList

def showTask():
    
    """
    Show the To_do List.
    """
    
    # ToDo()함수를 불러오는 변수
    todoList = ToDo()
    todoList
    
    # 출력 문장과 그 문장의 길이 만큼 -를 출력하는 내용
    state = 'Your To-Do List:'
    print()
    print(state)
    print('-' * len(state))

    # ToDo()함수가 반환하는 리스트의 항목을 한개씩 출력하는 반복문
    for task in todoList:
        print(task)


showTask()

section8: Dictionaries

  • Dictionaries
  • Creating
  • Adding and removing items
  • Searching
  • Nesting
  • Looping
  • Excercise

Dictionaries

item이라 불리우는 key-value 짝의 모음 데이터이다.
연관 배열, 해시 테이블, 해시에 활용된다.
value 의 데이터 타입이 동일하지 않아도 된다.
순서가 없는 데이터 타입니다.
그러나 python 3.6 이후부터는 입력 순서를 지키고 있다. 다만 순서가 다른 변수도 동일하다고 하니, 엄격한 비교가 필요할 경우 이 블로그를 참고하여 키워드를 찾아보자.

Creating

dictionary에 내용을 채워서 선언하는 방식
dict_Name = {key1: val1, key2: val2}
dictionary 타입이라는 것을 선언하는 방식
dict_Name = {}

Adding and removing items

추가 / 수정
dict_Name[key] = val
삭제
del dict_Name[key]

Searching

dictionary의 key 항목을 리스트 모양의 객체 형태로 출력하는 것
dict_Name.keys()
dictionary의 value 항목을 리스트 모양의 객체 형태로 출력하는 것
dict_Name.values()
dictionary의 항목 튜플을 리스트 모양의 객체 형태로 출력하는 것
dict_Name.items()
key를 기준으로 동일한 값이 있는지 찾아 Boolean값을 반환
if key1 in dict_Name.keys():
    # codeBlock
value를 기준으로 동일한 값이 있는지 찾아 Boolean값을 반환
if val1 in dict_Name.values():
    # codeBlock

Nesting

dictionary안에 dictionary를 또 가질 수 있다.
선언할 때, {}와 :의 위치를 잘 확인해야 한다.
doct_Name[keyRoot][keyNested] 순서로 접근할 수 있다.

Looping

dict_Name을 기준으로 반복문을 돌리면 key값에 접근한다.
dict_Name.items()를 기준으로 반복문을 돌리면 (key, val)의 형태로 접근한다.
변수를 두 개로 반복문을 돌릴 수 있다.
for key_var, val_var in dict_Name.items():
    # codeBlock
dict_Name.keys()를 기준으로 반복문을 돌리면 key값에 접근한다.
dict_Name.values()를 기준으로 반복문을 돌리면 value값에 접근한다.

Excercise #1

# Excercise 1:

facts = {'Jeff': 'Is afraid of clowns.',
         'David': 'Plays the piano.',
         'Jason': 'Can fly an airplane.'}
    
def changeFacts():
    facts['Jeff'] = 'Is afraid of heights.'
    facts['Jill'] = 'Can hula dance.'
    
def displayFacts():
    for person, fact in facts.items():
        print('{0}: {1}'.format(person, fact))
    print()
    
    
displayFacts()
changeFacts()
displayFacts()

section9: Tuples

  • Creating
  • Deleting
  • Converting
  • Assignment
  • More built-in functions
  • Excercise

Creating

tuple은 수정이 불가능한, 순서가 있는 리스트이다.
tuple은 인덱스로 접근할 수 있다.
tuple_Name1 = (item1, item2)
tuple_Name2 = (item1,)

Deleting

삭제
del tuple_Name

Converting

tuple과 list는 built-in 함수를 통해서 상호 간에 변환할 수 있다.
list로 변환하는 함수, ()안에 해당 객체를 넣는다.
list()
tuple로 변환하는 함수, ()안에 해당 객체를 넣는다.
tuple()
객체의 타입을 반환하는 함수, ()안에 해당 객체를 넣는다.
type()

Assignment

tuple을 활용하여 변수 여러 개를 한 번에 할당한다.
(tuple1, tuple2) = (val1, val2)
(tuple1, tuple2) = [val1, val2]
함수에서 여러 개를 반환할 때 활용할 수 있다.
return (tuple1, tuple2)
반복문에서 여러 요소를 다룰 때 활용할 수 있다.
for (tuple1, tuple2) in someList:

More built-in functions

max()는 built-in 함수로 ()안에 든 것 중 가장 큰 항목을 반환한다.
min()는 built-in 함수로 ()안에 든 것 중 가장 작은 항목을 반환한다.

Excercise #1

# Excercise 1:
airportList = [('O\'Hare', 'ORD'),
               ('Los Angeles', 'LAX'),
               ('Dallas/Fort Worth', 'DFW'),
               ('Denver', 'DEN')]

def Display():
    for (airport, code) in airportList:
        print('The code for {} Airport is {}.'.format(airport, code))
        
Display()

section10: Files: 

  • Reading files
  • Writing to files
  • Opening and closing files
  • File objects
  • String methods
  • Reading files, One line at a time
  • File modes
  • Line endings
  • Esceptions
  • Excercise

Reading files

read() method는 전체 파일을 반환한다.
file_Name.read()
read() method 괄호에 숫자를 넣으면 그 숫자, N, 만큼의 문자를 읽어온다.
file_Name.read(N)

Writing to files

write() method는 파일에 ()내용을 작성한다.
file_Name.write()

Opening and closing files

open()은 built-in 함수로 ()안에 든 파일을 열어 반환한다.
open(pathToFile)
pahtToFile: absolute or relative
윈도우는 \를 구분자로 사용하지만, python은 /도 사용할 수 있다.
seek(offset) method는 offset 위치로 이동한다.
seek(0): 시작 위치로 이동한다.
seek(5): 5번째 byte 위치로 이동한다.
그러나 utf-8으로 인코딩된 파일은 문자가 1 byte보다 더 크다. 한글, 한자, 간자를 쓰는 경우 맞닥뜨린다.
tell() method는 파일에서 현재 위치가 어디인지 반환한다.
close()는 built-in 함수로 ()안에 든 파일을 닫는다.
file_Name.closed는 파일이 닫혀있는가를 Boolean으로 반환하는 함수이다.
with 구문을 사용하고, codeBlock에 있는 내용을 모두 실행하거나, 혹은 어떤 이유로든 interrupt를 받으면 file을 닫는다.
with open(fileToPath) as file_Name:
    # codeBlock

File objects

파이썬 환경에서 텍스트 파일을 읽고 쓸 수 있도록 지원하는 객체로, open() 함수에 의해 반환되는 객체이다.
file_Name = open(pathToFile, mode)

String methods

.rstrip() method는 줄 끝에 line endings를 무시하고, 빈 부분을 없앤다.
for line in the file_Name:
    print(line.rstrip() )

Reading files, One line at a time

for문을 활용하여 한 줄씩 읽을 수 있다.
txt 파일에서 줄 끝에 CR(맨 앞으로 이동, \r) 혹은 줄바꿈 문자(\n)가 존재하면, 한 줄이 출력되고 다음으로 비어있는 줄이 출력된다.
for line in the file_Name:
    print(line)

File modes

open() 함수의 파라미터 중 mode의 종류
r: 읽기위해 연다(default)
w: 쓰기 위해 연다. 우선 지운다.
x: 새로운 파일을 만들고 쓰기 위해 연다.
a: 쓰기 위해 열고, 파일에 추가한다.
+: 파일을 업데이트하기 위해 연다. 읽고 쓰기 가능하다.
b: bianry 모드, 이미지, 비디오, 압축 파일 등 사람이 읽지 못하는, byte의 모음이다.
t: Text 모드로 사람이 읽을 수 있다.(default)
open('filePath', 'rb')

Line endings

맨 앞으로 이동하라는 Carriage Return, CR 문자
\r
줄을 바꾸라는 newline 문자
\n
운영체제마다 line endings를 다르게 가진다.
Unix, Linux, Mac
\n
Windows
\r\n

Esceptions

파일에 읽기가 불가능한 경우 다음과 같이 예외 처리를 한다.
예외문에 빈 문자열을 배정한다.
try:
    variable_Name = open('fileToPath').read()
except:
    varable_Name = ''

Excercise #1

# Excercise 1:

# file.txt를 만드는 부분
with open('data/file.txt', 'x') as File:
    File.write('This is line one.\n')
    File.write('This is line two.\n')
    File.write('Finally, we are on the third and last line of the file.')

# file.txt를 열어서 한 줄씩 출력하는 부분
with open('data/file.txt', 'r') as File:
    for line in File:
        print(line.rstrip())

Excercise #2

# Excercise 2:

# animals.txt를 만드는 부분
with open('data/animals.txt', 'x') as File:
    File.write('man\n')
    File.write('bear\n')
    File.write('pig\n')
    File.write('cow\n')
    File.write('duck\n')
    File.write('horse\n')
    File.write('dog')

# animals.txt의 내용을 따로 저장할 리스트 변수
animals = []

# animals.txt를 열어서 한 줄씩, 줄바꿈 문자 없이 animals 변수에 추가하기
with open('data/animals.txt', 'r') as File:
    for line in File:
        animals.append(line.rstrip())

# animals 리스트 변수를 오름차순으로 재정렬하기
animals.sort()

# animals-sorted.txt를 만들어 animals 변수에 있는 요소를 한 줄씩 적기
with open('data/animals-sorted.txt', 'x') as File:
    for animal in animals:
        File.write('{}\n'.format(animal))

# animals-sorted.txt를 열어 줄바꿈 문자 없이 한 줄씩 읽기
with open('data/animals-sorted.txt', 'r') as File:
    for line in File:
        print(line.rstrip())

section11: Modules

  • Modules
  • More built-in Python functions
  • Module search path
  • Python Standard Library
  • Excercise

Modules

Python Modules는 .py 확장자를 가진 파일로, attributes(variable, 변수), methods(functions, 함수), 그리고 classes(types, 데이터 타입)의 모음을 구현한다.
import 구문을 이용해 다른 Python 프로그램에서 module을 활용할 수 있다.
import module_Name
module_Name.method_Name()
module_Name.attribute_Name
from 구문을 사용하면, module안의 method를 활용할 때 module 이름 없이 호출할 수 있다.
from module_Name imort method_Name1, method_Name2
method_Name()
module의 모든 함수를 개별적으로 활용할 수 있게 부르면, 기존의 것(함수, 변수 등)과 이름이 같을 경우 overwrite을 하는 등의 충돌이 있을 수 있다. 필요한 것을 구분하는 것이 활용할 때 더 좋다.
from module_Name import *

More built-in Python functions

dir()은 built-in 함수로 module 속 attributes, methods, classes에 무엇이 있는지 다 확인할 수 있다.
dir(module_Name)

Module search path

sys.path는 python의 module들이 설치된 곳의 경로를 반환한다. 이때, zip 파일도 포함해서 찾아준다.
import sys
sys.path
파이썬 모듈이 들어가 있는 곳을 추가하여 모듈을 더 확인할 수 있다.
sys.path.append(모듈을 저장한 디렉토리)
PYTHONPATH 환경 변수를 이용해 모듈 경로를 추가해줄 수 있다.
MAC / Linux:
PYTHONPATH = path1:pathN
export PYTHONPATH = 'path'
Windows:
PYTHONPATH = path1;pathN
set PYTHONPATH = 'path'

Python Standard Library

Python은 커다란 Module의 library와 함께 배포된다.
csv, logging, urllib.request, json 등을 활용하는 모듈이 이미 존재한다.
sys module의 exit() method로 프로그램을 깔끔하게 종료할 수 있다.
이때, 출력인자로 str, int 다 된다.
기본적으로 정상 종료일 때는 0을, 에러가 발생했을 때는 1로 설정한다.
> import sys
> sys.exit(출력인자)
>> An exception has occurred, use %tb to see the full traceback.

>> SystemExit: 출력인자
__name__ value를 확인하는 방법으로, Python 프로그램이 실행됨을 확인할 때 사용할 수 있다.
main() 함수에는 프로그램이 실행될 때 동작할 내용이 들어간다.
__name__의 역할과 아래의 코드가 import가 아니라 직접 실행될 때 시작점을 확인하는 용도로 쓰임을 확인하는 블로그 글을 참고했다.
def main():
    #codeBlock

if __name__ = '__main__'():
    main()

Excercise #1

# Exercise 1:

# 모듈 경로를 추가하기 위해 불러옴
import sys
# cat_say.py와 cat_talk.py를 만들어 활용하기 위해, 저장해둔 현재 경로를 확인하기 위해 불러옴
import os

# 현재 경로 저장 변수
cwd = str(os.getcwd())
print(cwd)
# 현재 경로를 모듈경로에 추가함
sys.path.append(cwd)
sys.path

import cat_talk
# 아무일도 일어나지 않는다.

 

# cat_say.py

"""
import this module and promptly take input from user and display a cat and saying.
"""
def cat_say(saying):
    length = len(saying)

    print(' ' * 12, '_' * length) # 12
    print(' ' * 10, '< {} >'.format(saying)) # 10
    print(' ' * 12, '-' * length) # 12
    print('           /') # 11
    print(' /\\_/\\    /') # 10
    print('( o.o )')
    print(' > ^ <')


def main():
    saying = input("What would you like the cat to say? ")
    cat_say(saying)

if __name__ == '__main__':
    main()
# cat_talk.py

"""
import this module and promptly print cat's saying-Feed me. Pet me. Purr.Purr.-
"""

import cat_say

def main():
    cat_say.cat_say('Feed me.')
    cat_say.cat_say('Pet me.')
    cat_say.cat_say('Purr.   Purr.')

if __name__ == '__main__':
    main()
    
# cat_talk.py 직접 실행 시 __name__이 '__main__'과 같은 순간이므로
# 코드 블럭 내용인 main()에 존재하는 내용이 수행된다.
반응형