▼ CS50 Python - Lecture 0

Gavan·2025년 7월 9일

Study Journal

목록 보기
5/6
post-thumbnail

■ Functions, Variables

본 포스트는 필자의 파이썬 공부 기록에 관한 글입니다.
Harvard CS50’s Introduction to Programming with Python의 영상으로 학습합니다.

URL(출처) : https://youtu.be/JP7ITIXGpHk?si=wcZSk5hMw-XRQ67P




[1] Introduction

  1. Core Messages

  • 컴퓨터 과학과 프로그래밍은 문제 해결의 도구이다.
  • Python은 사람이 읽고 쓰기 쉬운 언어이며, 강력한 기능을 제공한다.



[2] hello.py

  1. "hello, world" 출력

>>> print("hello, world")

hello, world



[3] Command-line Interface (CLI)

  1. Core Messages

  • 명령줄 인터페이스
  • 명령줄에서 python 파일명.py로 프로그램 실행 가능
  • CLI는 개발자가 컴퓨터와 직접적으로 소통할 수 있는 수단



[4] Python Interpreter

  1. Core Messages

  • 파이썬 인터프리터
  • .py 파일 없이도 인터프리터를 실행시켜 Python 코드를 실시간으로 테스트할 수 있다.

  2. 실행 코드

>>> print("hi")

$ hi



[5] Functions, Arguments, Side Effects

  1. Core Messages

  • 함수, 인수, 부수 효과
  • print()는 side effect를 일으키는 함수이다. (화면에 무언가를 출력함)
  • 함수를 호출할 때는 괄호를 사용하며, 그 안에 인수를 넣는다.
  • Python에서는 함수를 직접 정의할 수도 있다.

  2. 실행 코드

>>> def hello():
>>>     print("hello")
>>>     
>>> hello()

$ hello



[6] Bugs and Debugging

  1. Core Messages

  • 버그 및 디버깅
  • 버그는 코드에 존재하는 실수이며, 디버깅은 그것을 찾고 수정하는 과정
  • 프로그램을 부분적으로 실행하면서 문제를 찾는 전략을 소개한다.

  2. 실행 코드(오류 예시)

>>> print("hello, world"

$ File "c:\Python\Ch.1 - Fuction, Variables\1_hello.py", line 1
$     print("hello, world"
$          ^
$ SyntaxError: '(' was never closed

괄호를 닫지 않고 실행해보았다.
결과(Terminal)에서 SyntaxError과 함께 괄호가 닫히지 않았다고 알려준다.

  • 정상 결과만을 실행시키는 것이 아닌 이에 따른 발생할 수 있는 오류에 대해 파악을 해두는 것에 대한 중요성을 말한다.



[7] VS Code and IDEs

  1. Core Messages

  • VS Code 및 통합 개발 환경
  • VS Code는 강력한 통합 개발 환경(IDE)으로, 자동 완성, 파일 관리, 디버깅 기능 제공
  • Python 확장 프로그램을 설치하면 VS Code에서 Python 개발이 쉬워진다.

    1) Question.(IDEs)

Q) 터미널 없이 프로그램을 실행시킬 수 있나요?
A) 이 환경(VS Code)에서는 터미널 창을 통해서만 Python 프로그램을 실행할 수 있습니다.
① 이건 프로그래머에게는 좋은 일이지만
② 소프트웨어를 출시하여 다른 사람들이 여러분의 실제 코드를 사용하게 하려는 경우에는
좋지 않습니다.

  • CLI(명령줄 인터페이스)가 아닌 GUI(그래픽 사용자 인터페이스)같은 매커니즘이
    코드 작성하기에 좋다.



[8] Return Values & Variables

  1. Core Messages

  • 반환 값 및 변수
  • 함수는 결과 값을 반환할 수 있으며, 이 값을 변수에 저장 가능
  • 예: input()은 사용자 입력을 문자열로 반환한다.

  2. 실행 코드

    1) First

- Input

>>> input("What's your name? ")
>>> print("hello, world")

$ What's your name? **gavan**
$ hello, world

Input함수를 통해 질문을 하였고, 이에 따른 답변을 진행했으나 대답은 World로 고정되어 있다.
그럼 내가 원하는 답변인 hello, gavan이 나오도록 해보자.

    2) Second

>>> input("What's your name? ")
>>> print("hello, gavan")

$ What's your name? **gavan**
$ hello, gavan

→ 답변을 world에서 gavan으로 변경.

  • 문제 상황 : hello, gavan이라는 답변만을 반복
    (입력값을 받아 이에 따라 변하는 답변을 하지 못하는 "Hard Coding"이 됨.)
  • 목적 : 그럼 "Soft Coding"이 되도록 변경.
  • 방법 : 그래서 우리는 궁극적으로 사용자의 입력을 실제로 얻고,
    이를 활용해 어떤 일을 할 수 있는 방법이 필요함에 따라
    다음과 같은 성질을 이용할 것이다.
  • 함수도 Return Value(반환 값)를 가질 수 있다.
  • Variables(변수)는 값을 저장할 수 있다.

    3) (), "", =,

  • (), "" - 괄호와 따옴표는 함수에 입력을 전달할 때
  • = - 할당 연산자 (같다, 평등 의미 X, 많은 다른 언어에서도 해당)
    - 저장 가능
    - 재사용 가능



[9] Comments & Pseudocode

  1. Core Messages

  • 주석 및 의사 코드
  • 주석(### 또는 #)은 사람이 읽기 위한 코드 설명
  • 의사코드(pseudocode)는 실제 문법 대신 논리 중심으로 흐름을 설명

  2. 실행코드 - Commests(주석)

  • 기호 : #, """, '''
  • 코드를 손상시키지 않고 메모 작성 가능
    (User-Human만 인지, 컴퓨터는 이를 무시하고 실행)

    1) First

# #은 한 줄씩 주석처리하기에 용이
# Ask user for their name

>>> name = input("What's your name? ")

# Say hello to user
>>> print("hello, " )
>>> print(name)

$ What's your name? **gavan**
$ hello, 
$ gavan

    2) Second

# """ / '''로 묶으면 범위 단위의 주석처리가 가능
"""
Ask user for their name
Say hello to user
"""

>>> name = input("What's your name? ")
>>> print("hello, " )
>>> print(name)

$ What's your name? **gavan**
$ hello, 
$ gavan

  2. Pseudocode

  • 의사코드
  • 인간의 언어를 통해 간결, 체계적, 알고리즘적으로 생각을 표현하는 것
  • 주로 프로그램의 개요를 작성할 때 사용
  • To do list랑 유사

    1) 실행코드(Pseudocode)

# Ask user for their name

>>> name = input("What's your name? ")

# Say hello to user
>>> print("hello, " )
>>> print(name)

$ What's your name? **gavan**
$ hello, 
$ gavan



[10] Multiple Function Arguments

  1. Core Messages

  • 다중 함수 인수
  • print()는 여러 인수를 받으며, 기본 구분자는 공백
  • sep, end 등의 매개변수로 출력 형식을 제어할 수 있음

  2. 실행 코드

    1) First - Outline

>>> print("hello", "world")
>>> print("hello", "world", sep="...")
>>> print("hello", end="")
>>> print("world")

$ hello, world
$ hello...world
$ helloworld

    2) Second - 같은 줄 출력을 통해 가독성 확보

[문제 상황] "hello,"와 name이 다른 줄에 출력된다.
[시도] 같은 줄에 출력함으로써 가독성을 높이고 싶다.

# Ask user for their name
>>> name = input("What's your name? ")

# Say hello to user
>>> print("hello," + name)

$ What's your name? **gavan**
$ hello,gavan

    3) Third - 띄어쓰기를 통해 가독성 확보

[문제 상황] "hello,"와 name가 붙어있어 가독성이 좋지 않다.
[시도] ","뒤에 띄어쓰기를 넣어주고 싶다.

>>> name = input("What's your name? ")
>>> print("hello, " + name)

$ What's your name? **gavan**
$ hello, gavan

    4) Fourth - +와 ,의 차이

함수의 인수(입력) 쉼표로 구분하면, 여러 개의 정보를 전달할 수 있다.
이에 해당하는 인수는 변수도 문장도 포함한다.

[확인] + → ,로 변경하여도 같은 출력이 나오는지 확인해보자.

>>> name = input("What's your name? ")
>>> print("hello, ", name)

$ What's your name? **gavan**
$ hello,  gavan

[결과] hello, 와 name 사이에 공백이 한 칸 더 생겼다.
[시도] 작성 시, "," 다음에 공백을 두면 안될 것 같다.

>>> name = input("What's your name? ")
>>> print("hello, ",name)

$ What's your name? **gavan**
$ hello,  gavan

[결과] Terminal 상의 결과가 같다.
[추측] 명령문 작성 시, 공백의 문제가 아닌거 같다.
[시도] 모든 공백을 없애보겠다.

>>> name = input("What's your name? ")
>>> print("hello,",name)

$ What's your name? **gavan**
$ hello, gavan

[결론] "+"를 통한 다수의 인수 삽입 시 : 공백 자동삽입 X
     ","를 통한 다수의 인수 삽입 시 : 공백 자동삽입 O

    4) 공백의 이유

name = input("What's yout name? ")

위 명령문에서 노란색 부분에 공백을 넣어둔 이유는 사용자의 커서를 한 칸 오른쪽으로 옮기기 위함이다.

    5) Question

Q) 코드에서 여러 번 접하는 특정 문제를 해결하기 위해 함수를 여러 번 사용할 수 있을까요?
A) 네, 가능합니다. 뒤의 내용에서 알 수 있겠지만, 같은 방식으로 문제를 계속해서
반복하다보면 언어에 기본적으로 내장된 함수를 재사용하지 않고도
자신만의 함수를 만들 수 있습니다.




[11] Named Parameters

  1. str

  • 이름 지정 매개변수
  • str(string) : 문자열

  2. print 구문을 두 번 사용하고 싶다면?

    1) Case-1

>>> name = input("What's your name? ")
>>> print("hello,")
>>> print(name)

$ What's your name? **gavan**
$ hello,
$ gavan

print문 내부에 자동 줄바꿈이 있는 듯하다.

    2) Checking

설명서의 읽는 법을 배우고, 활용하는 것이 좋다.
Python 함수 설명서 URL : https://docs.python.org/3//library/functions.html

이 링크에 들어가면 Python 함수의 내부구조를 알 수 있다.

print(*objects, sep=' ', end='\n', file=None, flush=False)

  • *objects : 다수의 객체 수용 가능
  • sep=' ' : 인수 전달 시, 공백으로 구분
  • end='\n' : \n(줄바꿈)으로 끝냄

    3) Updating of case-1

>>> name = input("What's your name? ")
>>> print("hello,", end="")
>>> print(name)

$ What's your name? **gavan**
$ hello, gavan

이처럼 함수의 기본 구조 또한 변경할 수 있다.
print문에서는 end로 함수 마무리를, sep으로 구분자를 필요시 변경이 가능하다.

  • Parameter(함수의 매개변수) : 함수에 전달할 수 있는 내용과 해당 입력
                        (인수, 각 단어를 사용할 때는 문제를 다른 관점에서 보는 것)
  • Argument(인수) : 함수를 사용하고 괄호 안의 값을 전달할 때, 해당 입력/값
  • Position Parameter(위치 매개변수) : "처음 전달한 값이 먼저 출력된다."를 의미
                            (순서대로 출력)
  • Named Parameter(명명된 매개변수) : sep, end



[12] Escaping Characters

  1. Core Messages

  • 문자 이스케이프
    문자열 내부에서 특수 문자를 포함하고 싶을 때는 "\" 사용
    예: 따옴표(") → /", "" 역슬래시() → \, "\"

  2. 따옴표 안에 따옴표 구현

    1) Solutions

>>> print('hello, "friend"')
$ hello, "friend"
>>> print("hello, \"friend\"")
$ hello, "friend"

  3. 따옴표 안에 매개변수 구현

    1) Solution

# Ask user for their name
>>> name = input("What's your name? ")
            
# Say hello to user
>>> print(f"hello, {name}")

$ What's your name? **gavan**
$ hello, gavan



[13] f-String

  1. Core Messages

  • f-문자열
  • 문자열 내 변수 포함 가능
  • 가독성이 높고 권장되는 방법

  1. 대화문에 변수넣기

    1) {}

  • [목적] 대화문 속 input(입력)을 name(출력)으로 받고싶다.
  • [방안] 대화문 속 naem의 변수처리를 위해 "{}"로 묶어보았다.
#Ask user for their name
>>> name = input("What's your name?")

#Say hello to user
>>> print("hello, {name}")

$ What's your name?gavan
$ hello, {name}
  • [결과] "{name}"이 그대로 출력된 모습.

    2) {} & f

  • [목적] 대화문 속 변수처리를 위해 "{}"로 묶고, (와 "사이에 "f"를 넣어보았다.
#Ask user for their name
>>> name = input("What's your name?")

#Say hello to user
>>> print(f"hello, {name}")

$ What's your name?gavan
$ hello, gavan
  • [결과] "{name}"이 변수를 받아 목적대로 gavan을 출력.



[14] Strings Methods(문자열 메서드)

  1. Remove whitespace for str (Left & Right)

    1) name = name.strip()

[참조 URL] : https://docs.python.org/3//library/stdtypes.html#stringmethods

  • [목적] 사용자의 입력의 좌우 공백을 제거하고 싶다.
# Ask user for their name
>>> name = input("What's your name?")

# Remove whitespace from str
>>> name = name.strip()

# Say hello to user
>>> print(f"hello, {name}")


$ What's your name?        gavan    
$ hello, gavan
  • [결과] 불필요한 좌우 공백이 제거되었다.

  2. Capitalize user's name

    1) name = name.capitalize()

  • [목적] 사용자의 입력의 첫 글자를 대문자화하고 싶다.
# Ask user for their name
>>> name = input("What's your name?")

# Capitalize the first letter of the user's name
>>> name = name.capitalize()

# Say hello to user
>>> print(f"hello, {name}")

$ What's your name?       gavan  
$ hello, Gavan
  • [결과] 사용자의 단어의 첫 글자가 대문자화되었다.

    2) name = name.title()

  • [목적] 사용자의 입력의 단어마다의 첫 글자를 대문자화시키고 싶다.
# Ask user for their name
>>> name = input("What's your name?")

# Capitalize each letter of the user's name
>>> name = name.title()

# Say hello to user
>>> print(f"hello, {name}")

$ What's your name?scoper gavan 
$ hello, Scoper avan
  • [결과] 사용자의 단어마다 첫 글자가 대문자화되었다.
  • [분석} title은 주제, 제목과 같은 의미를 지니고 있다.
    - 각 단어마다 주제화, 제목화를 하여 대문자화시키는 것으로 사료된다.

  3. Remove whitespace & Capitalizing

    1) First Road

  • [목적] 사용자의 입력을 다음과 같이 변화시키고싶다.
    1) 좌우 공백 제거
    2) 단어 앞글자 대문자화
    3) 입력해야하는 명령문을 줄이고 싶다.
# Ask user for their name
>>> name = input("What's your name?")

# Remove whitespace + Capitalize the first letter of the user's name
>>> name = name.strip().capitalize()

# Say hello to user
>>> print(f"hello, {name}")

$ What's your name?       scoper gavan  
$ hello, Scoper Gavan
  • [결과]
    1) 사용자의 단어의 첫 글자가 대문자화
    2) 좌우 공백 제거
  • [결론] 두 명령을 동시에 한 줄로 작성하고 싶다면,
    "name = name.strip().capitalize()"로 작성하면 된다.
    (만약 "title()"을 사용하고 싶다면 "capitalize()"를 대체하면 된다.)

    2) Second Road

  • [목적] First road에서 작성해야할 명령문을 줄이는데에 성공했다.
    더 줄이고 싶다면 어떤 방법이 있을까? 이를 알아보자.
#Ask user for their name
>>> name = input("What's your name?").strip().capitalize()

#Say hello to user
>>> print(f"hello, {name}")

$ What's your name?       scoper gavan  
$ hello, Scoper Gavan
  • [결과]
    1) 사용자의 단어의 첫 글자가 대문자화
    2) 좌우 공백 제거
  • [결론] 아예 한 줄로 표현하는 방법은 위와 같다.
    (만약 "title()"을 사용하고 싶다면 "capitalize()"를 대체하면 된다.)
  • [Plus] 좌, 우의 공백 중 한 쪽만 제거하고 싶다면, lstrip/rstrip을 기호에 맞게 사용하면 된다.



[15] Style

  1. Core Messages

  • 코드 스타일은 일관성과 가독성이 중요
  • 이와 같은 고민은 더 좋은 개발자가 되기 위한 발판

  2. Thinking Point

[15] String Methods의 Frist/Second Road의 방법을 알아보았다.
 가독성을 위해서 First Road와 Second Road 중 어떤 것을 사용하는 것이 좋을까?
 개발자의 코딩은 협업이 중요하거나, 내가 해당 프로젝트를 맡지 않게 되었을 때, 다음 프로젝트 담당자가 가독하게 가독성을 높여야한다. 두 방안 중 어떤 것을 사용하여도 작성자가 가독성을 높여야 한 것은 동일하다.
 실제 강의에서도 이에 대해 학생투표를 진행했는데, 반반으로 나뉘었다. 가장 좋은 것은 이런 합의가 필요한 점을 공통의 룰로 규정해주는 회사가 업무를 진행하기에 수월할 것이다.
▶ 좋은 프로그래머/개발자가 되기 위해서는 이러한 의문에 대해 사고하는 것이 중요하다고 생각한다.




[16] Split

  1. Core Messages

  • 분할
  • .split()은 문자열을 공백 또는 특정 구분자로 나눠 리스트로 반환

  2. 실행 코드

# Ask user for their name
>>> name = input("What's your name?")

# Remove whitespace from str
>>> name = name.strip()

# Capitalize the first letter of the user's name
>>> name = name.capitalize()

# Divide user's name to whitespace of between first and last name
>>> first, last = name.split(" ")

# Say hello to user
>>> print(f"hello, {first}")


$ What's your name?scoper gavan
$ hello, scoper



[17] Integers & Operators

  1. Core Messages

  • 정수 및 연산자

    1) Integers Define

  • Int(Integer) : 정수형 (-1, -2, 0, 1, 2, 3, ...)

    2) Operators Define

  • Operator : 연산자 (+, -, *, /, %, **, //, ...)

    3) Interackive Mode(대화형 모드)

      ① Realizing

  • Terminal 창에 입력 (Terminal 창만 사용)
  • "Python" 입력
  • ">>>"뒤에 입력하도록 나옴 (Interactive Mode 진입)
  • code에 입력할 것을 ">>>"뒤에 입력
  • exit()로 종료

      ② Features

  • User가 매번 실행할 필요 없음 (Enter 입력과 동시에 자동실행)
  • Bug point searchig 용이 (User가 수동으로 오류 찾기 용이)



[18] Caculator.py

  • 강의 영상 참조. (Calculator.py의 영상 내용은 다루지 않을 예정)

  1. 계산기 만들기

  • 강의 영상에서는 간단한 계산기를 만든다.
  • 하기는 이를 이용하여 나름대로의 계산기 프로그램을 만들어보았다.

    1) First Try

print("Welcome to the Calculator Upgrade!")

print("First Step!")                                                            # 정수형, 실수형 구분 입력
print("Please enter the form of the number you want to calculate")
print("If you want enter Integers, you can enter \"I\"")                        # 정수형 입력 : I
print("If you want enter Floats, you can enter \"F\"")                          # 실수형 입력 : F

number_type = input("Number Type : ")

print("# "*100)

print("Second Step!")                                                           # 계산할 숫자 입력
print("Please enter the numbers you want to calculate")

X = int(input("X : "))
Y = int(input("Y : "))

print("# "*100)

print("Last Step!")                                                              # 연산자 입력
print("Please enter the type of operator you want to calculate")
print("If you want to add, you can enter \"+\"")                                 # 더하기 : +
print("If you want to subtract, you can enter \"-\"")                            # 빼기 : -
print("If you want to multiply, you can enter \"*\"")                            # 곱하기 : *
print("If you want to divide, you can enter \"/\"")                              # 나누기 : /
print("If you want to divide and get the integer part, you can enter \"//\"")    # 몫 : //
print("If you want to get the remainder, you can enter \"%\"")                   # 나머지 : %
print("If you want to raise to the power, you can enter \"**\"")                 # 거듭제곱 : **

operator = input("Operator : ")

print("# "*100)

print("Calculating the result...")

if number_type == "I":
    if operator == "+":
        I-result = int(X) + int(Y)
    elif operator == "-":
        I-result = int(X) - int(Y)
    elif operator == "*":
        I-result = int(X) * int(Y)
    elif operator == "/":
        I-result = int(X) / int(Y)
    elif operator == "//":
        I-result = int(X) // int(Y)
    elif operator == "%":
        I-result = int(X) % int(Y)
    elif operator == "**":
        I-result = int(X) ** int(Y)
    else:
        I-result = "Invalid Operator"

if number_type == "F":
    if operator == "+":
        F-result = float(X) + float(Y)
    elif operator == "-":
        F-result = float(X) - float(Y)
    elif operator == "*":
        F-result = float(X) * float(Y)
    elif operator == "/":
        F-result = float(X) / float(Y)
    elif operator == "//":
        F-result = float(X) // float(Y)
    elif operator == "%":
        F-result = float(X) % float(Y)
    elif operator == "**":
        F-result = float(X) ** float(Y)
    else:
        F-result = "Invalid Operator"

print("# "*100)

if number_type == "I":
    print(f"The result of {X} {operator} {Y} is: {I-result}")

if number_type == "F":
    print(f"The result of {X} {operator} {Y} is: {F-result}")

      <디버깅 분석>

구분문제해결 방법
변수 이름I-result, F-result → 파이썬에서 하이픈은 연산자로 인식되어 SyntaxError 발생밑줄(_)을 사용하거나 하나의 result로 통합
입력 처리X = int(input())를 무조건 사용 → 실수 입력 시 오류숫자 형식 선택 이후에 int() 또는 float()로 분기
중복 코드연산자별 if 사슬 딕셔너리(ops)로 매핑해 코드 간결화
예외 처리잘못된 형식·연산자 입력 시 계속 진행오류 메시지를 출력하고 SystemExit로 종료

    2) Second Try - (by "Claude AI")

print("Welcome to the Calculator Upgrade!")
print("First Step!")                                                            # 정수형, 실수형 구분 입력
print("Please enter the form of the number you want to calculate")
print("If you want enter Integers, you can enter \"I\"")                        # 정수형 입력 : I
print("If you want enter Floats, you can enter \"F\"")                          # 실수형 입력 : F
number_type = input("Number Type : ")
print("# "*100)

print("Second Step!")                                                           # 계산할 숫자 입력
print("Please enter the numbers you want to calculate")

# 숫자 타입에 따라 적절한 변환 함수 사용
if number_type == "I":
    X = int(input("X : "))
    Y = int(input("Y : "))
elif number_type == "F":
    X = float(input("X : "))
    Y = float(input("Y : "))
else:
    print("Invalid number type! Please enter 'I' or 'F'")
    exit()

print("# "*100)
print("Last Step!")                                                              # 연산자 입력
print("Please enter the type of operator you want to calculate")
print("If you want to add, you can enter \"+\"")                                 # 더하기 : +
print("If you want to subtract, you can enter \"-\"")                            # 빼기 : -
print("If you want to multiply, you can enter \"*\"")                            # 곱하기 : *
print("If you want to divide, you can enter \"/\"")                              # 나누기 : /
print("If you want to divide and get the integer part, you can enter \"//\"")    # 몫 : //
print("If you want to get the remainder, you can enter \"%\"")                   # 나머지 : %
print("If you want to raise to the power, you can enter \"**\"")                 # 거듭제곱 : **
operator = input("Operator : ")
print("# "*100)

print("Calculating the result...")

# 계산 수행
if operator == "+":
    result = X + Y
elif operator == "-":
    result = X - Y
elif operator == "*":
    result = X * Y
elif operator == "/":
    if Y == 0:
        result = "Error: Division by zero"
    else:
        result = X / Y
elif operator == "//":
    if Y == 0:
        result = "Error: Division by zero"
    else:
        result = X // Y
elif operator == "%":
    if Y == 0:
        result = "Error: Division by zero"
    else:
        result = X % Y
elif operator == "**":
    result = X ** Y
else:
    result = "Invalid Operator"

print("# "*100)

# 결과 출력
if isinstance(result, str):                                                        # 오류 메시지인 경우
    print(result)
else:
    print(f"The result of {X} {operator} {Y} is: {result}")

      <변경점>

  • [변수명 오류 수정]
    - I-result와 F-result는 파이썬에서 쓸 수 없는 변수명
    - 하이픈(-)은 변수명에 못 쓰니까 result로 통일
  • [입력 처리 개선]
    - 사용자가 선택한 숫자 타입에 맞춰서 적절한 변환 함수(int() 또는 float())를 쓰도록 수정
  • [코드 중복 제거]
    - 정수형이랑 실수형에 대해 똑같은 연산을 두 번씩 안 쓰고, 하나로 단순화
  • [0으로 나누기 오류 처리]
    - 나누기, 몫, 나머지 연산에서 0으로 나누면 오류 발생에 대한 처리
  • [잘못된 입력]
    - 검증사용자가 "I"나 "F" 말고 다른 걸 입력했을 때 오류 처리
  • [결과 출력 최적화]
    - 오류 메시지랑 정상 결과를 구분해서 출력하도록 개선



[19] Type Conversion

  • Type Conversion : 형 변환

  1. 불필요한 변수 제거와 행 줄이기

    1) 첫번째 변경

- 변경 전

>>> x = input("What's x? ")
>>> y = input("What's y? ")

>>> z = int(x) + int(y)

>>> print(z)

- 변경 후

>>> x = int(input("What's x? "))
>>> y = int(input("What's y? "))

>>> print(x + y)

    2) 변경점

변경 내용변경 전 코드변경 후 코드장점
입력 즉시 형변환x = input(...)
int(x)로 나중에 변환
x = int(input(...))
입력과 동시에 변환
- 코드 간결성 증가
- 변수의 자료형이 명확해짐
불필요한 변수 제거z = int(x) + int(y)
print(z)
print(x + y)- 변수 z 제거로 메모리 절약
- 직관적인 코드 흐름
코드 라인 수 감소총 5줄총 3줄- 유지보수 용이
- 가독성 향상

    3) 추가 고찰

  • 가독성을 높이기 위해 행을 줄이고, 불필요한 변수를 제거하였다.
  • 위의 두 코드를 보며, 한가지 방법이 더 떠올라 적어보고자 한다.
>>> x = input("What's x? ")
>>> y = input("What's y? ")

>>> print(int(x) + int(y))
  • 2)와 4)는 코드 작성 면에서는 스타일 차이라고 보인다. 하지만 시스템 적으로는 어떤 코드가 서버 과부하 혹은 로딩 속도 같은 면에서 차이가 있을 수도 있겠다는 생각이 든다.
  • 나는 아직 경험이 많지 않아 2)와 4)의 시스템 면에서 이득점이 무엇이 있고, 어떤 것이 어떤 상황에서 더 나은가는 아직 잘 모르겠다.

      ① 비교 (chatGPT)

항목① 입력 즉시 변환② 입력 후 변환
코드 간결성✅ 더 간결함⛔ 약간 장황함
가독성✅ 숫자형임이 즉시 드러남x, y가 문자처럼 보일 수 있음
디버깅 용이성⛔ 오류 위치 추적 어려움
(입력과 변환 동시에 발생)
✅ 형변환 시점이 분리되어 있어 추적 쉬움
예외 처리⛔ 입력과 변환이 결합되어 try/except 분리 어려움✅ try/except를 입력과 변환에 따로 적용 가능
재사용성✅ 이미 정수이므로 숫자 연산 재사용 편리x, y는 문자열이므로 매번 변환 필요
교육적 명확성✅ 흐름이 명확 (입력 → 정수 → 연산)✅ 흐름 구분 가능 (입력, 변환, 연산)

    4) 두 번째 변경

- 변경 전

>>> print(int((input("What's x? ")) + input("What's y? ")))
  • 문자열에서의 +로 인식. (1 + 2 = 12)

- 변경 후

>>> print(int(input("What's x? ")) + int(input("What's y? ")))
  • 정상 결과값 출력 (1 + 2 = 3)
  • 그렇다면, 이 짧기만 한 코드는 어떤 장점과 단점이 있을까?

      ② 비교 (chatGPT)

항목한 줄 버전여러 줄 버전
코드 길이짧고 간결조금 더 길지만 명확
가독성복잡한 구조로 초보자에게는 어려울 수 있음입력, 처리, 출력이 분리되어 가독성이 좋음
디버깅 용이성문제 발생 시 원인 추적이 어려움중간 변수 확인 가능 → 디버깅 쉬움
재사용성입력값을 재사용할 수 없음x, y를 여러 번 쓸 수 있음
에러 처리모든 것이 한 줄에 있어 예외 처리 어렵고 복잡함입력마다 try/except를 적용하기 쉬움
교육적 가치파이썬에 익숙한 사람에게 유용초보자에게 데이터 흐름을 잘 보여줌
  • chatGPT에게 1)의 변경 후 코드와 4)의 변경 후 코드를 비교해달라고 하였다.
  • 정답은 없겠지만, 현업에서는 다양한 사람(초보자~고수)과 협업을 진행하기에 여러 줄 버전이 좋아보인다고 생각한다.
  • 또한 가독성과 행 줄이기는 항상 비례하지 않다는 생각도 들었다. 한 줄 코드의 경우 깔끔해 보이기는 하나 구조 해석이 여러 줄 코드에 비해 어려워 작성/변경에 실수(논리적 오류, 전술적 실수)가 나오기 쉬울 거 같다.



[20] Floating Point Values

  • 부동 소수점 값의 중점 가치

  1. float

  • 부동 소수점의 입력을 받을 수 있다.

- Input

x = float(input("What's x? "))
y = float(input("What's y? "))

print(x + y)

    1) Round(반올림)

      ① 구조

  • round(number, ndigits=None), round(number[, ndigits])
    - number : positional parameter
    - ndigits :
      > ndigits가 생략되거나 이면 입력값에 가장 가까운 정수를 반환
      > 표현하고자 하는 자리 수 입력

      ② 적용

- First Try

>>> x = float(input("What's x? "))
>>> y = float(input("What's y? "))

>>> print(round(x + y))

- Second Try

>>> x = float(input("What's x? "))
>>> y = float(input("What's y? "))

>>> z = round(x + y)

>>> print(z)

    2) Thousands Separator




[21] Numeric Formatting

  1. Three-digit commas

>>> x = float(input("What's x? "))
>>> y = float(input("What's y? "))

>>> z = round(x + y)					# Rounding

>>> print(f"{z:,}")						# f-string



[22] Division

  • 나누기

  1. Rounding

>>> x = float(input("What's x? "))
>>> y = float(input("What's y? "))

>>> z = x / y                        # Change Plus to Divide

>>> print(z)


$ What's x? 2
$ What's y? 3
$ 0.6666666666666666
  • 2 / 3 = 0.666666...으로 소수점 두번째 자리까지 반올림하여 표현하고 싶다.

    1) "Round Function" to Rounding

>>> x = float(input("What's x? "))
>>> y = float(input("What's y? "))

>>> z = round(x / y, 2)              # 소수점 둘째 자리까지 반올림

>>> print(z)


$ What's x? 2
$ What's y? 3
$ 0.67

    2) "f-string" to Rounding

>>> x = float(input("What's x? "))
>>> y = float(input("What's y? "))

>>> z = x / y

>>> print(f"{z:.2f}")                # f-string을 사용하여 소수점 둘째 자리까지 출력


$ What's x? 2
$ What's y? 3
$ 0.67



[23] Defining Functions

  • 함수 정의하기
  • def
  • 코드 맨 앞에 사용.

  1. hello()

    1) Text

>>> name = input("What's your name? ").strip().title()

>>> print(f"hello, {name}")

    2) Edit

      ① First Try

>>> name = input("What's your name? ")
>>> hello()
>>> print(name)

가독성면에서 후자가 더 좋아보인다. 이렇게 사용하려면 어떻게 해야할까?

      ② Second Try

>>> def hello():                  # [의미] 이 코드 줄 아래의 들여쓰기한 모든 코드를 이 함수의 의미로 취급
>>>     print("hello")

>>> name = input("What's your name? ")
>>> hello()
>>> print(name)


$ What's your name? Gavan
$ hello
$ Gavan

하기의 사항들이 의도와 다르게 출력되는 모습.

  • 한줄로 표현
  • "," 부재

    3) Conclusion

      ① First Try

>>> def hello():                        # [의미] 이 코드 줄 아래의 들여쓰기한 모든 코드를 이 함수의 의미로 취급
>>>     print("hello, ", end="")        # [의미] 이 함수가 호출되면 "hello, "를 출력, 줄 바꿈 X

>>> name = input("What's your name? ")
>>> hello()
>>> print(name)


$ What's your name? Gavan
$ hello, Gavan

      ② Second Try

>>> def hello(to):                      # [의미] 이 코드 줄 아래의 들여쓰기한 모든 코드를 이 함수의 의미로 취급
>>>     print("hello, ", to)            # [의미] 이 함수가 호출되면 "hello, "를 출력, 줄 바꿈 X

>>> name = input("What's your name? ")
>>> hello(name)                         # [의미] hello() 함수에 name 변수를 인자로 전달

 
$ What's your name? Gavan
$ hello, Gavan

      ③ Third Try(Upgrade ver.)

user가 답변을 입력하지 않을 시 "world" 출력

>>> def hello(to="world"):              # [의미] 이 코드 줄 아래의 들여쓰기한 모든 코드를 이 함수의 의미로 취급
>>>     print("hello, ", to)            # [의미] 이 함수가 호출되면 "hello, "를 출력, 줄 바꿈 X

>>> hello()
>>> name = input("What's your name? ")
>>> hello(name)                         # [의미] hello() 함수에 name 변수를 인자로 전달



[24] Scope

>>> def main():
>>>     hello()
>>>     name = input("What's your name? ")
>>>     hello(name)


>>> def hello(to="world"): 
>>>     print("hello, ", to)

>>> main()


$ hello,  world
$ What's your name? gavan
$ hello,  gavan



[25] Return Values

  • 입력함수는 사용자가 입력한 문자열인 값을 반환한다.

  1. Square Calculator

    1) 3 Ways of Squaring

      ① First Try

>>> def main():
>>>     x = int(input("What's x? "))
>>>     print("x squeared is", square(x))

>>> def square(n):
>>>     return n * n

>>> main()


$ What's x? 3
$ x squeared is 9

      ② Second Try

>>> def main():
>>>     x = int(input("What's x? "))
>>>     print("x squeared is", square(x))

>>> def square(n):
>>>     return n ** 2

>>> main()


$ What's x? 4
$ x squeared is 16

      ③ Third Try

>>> def main():
>>>     x = int(input("What's x? "))
>>>     print("x squeared is", square(x))

>>> def square(n):
>>>     return pow(n, 2)

>>> main()


$ What's x? 5
$ x squeared is 25



The End.




profile
탁월함을 위한 한걸음, 사고의 중요성

0개의 댓글