no image
<Python 코딩 도장> day 6~7
[day 6]UNIT.9 여러줄 문자열 사용하기''' ''' 여러 줄로 된 문자열 사용하기'''(문자열)''' or """(문자열)""" ex)print('''check this out나는 정 상 수 백발백중하는명 사 수''') -> check this out 나는 정 상 수 백발백중하는명 사 수​문자열 안에 따옴표 포함하기문자열 안에 작은 따옴표를 넣고 싶을 때문자열을 큰 따옴표로 묶어준다. 문자열 안에 큰 따옴표를 넣고 싶을 때문자열을 작은 따옴표로 묶어준다. 세 개의 따옴표로 묶인 문자열의 경우 종류에 상관없이 문자열에 따옴표를 포함시킬 수 있다. 이스케이프(escape) 시퀀스\뒤에 따옴표를 붙이면 된다. cf) 이스케이프 시퀀스란?프로그래밍 언어 특성상 표현할 수 없는 문자를 표현하거나 제어에 ..
2025.01.11
no image
[Khan Academy] Position, velocity, acceleration VS. time graph
Position vs. time graph(S-T graph)It represents the position of an object as a function of time. S-T graph's slopeIt means object's velocity $v=\frac{\Delta x}{\Delta t}$[case 1] S-T graph is linear graphIt represents the object is moving with constant velocity.[case 2] S-T graph isn't linear graphslope of it's tangent line = velocity of the object(instantaneous velocity) What is instantaneous v..
2024.12.20
no image
[Khan Academy] Visual models of motion
Object modelIgnoring internal structureWhen the interested quantities aren't affected by the object's size, shape, or internal structure, we can ignore them.∴ It is useful to define an object as something whose internal structure is negligible. Object model1. ignore internal structure of the object.2. Define object as a particle. ex) We can define a car as a particle. Using the object modelParti..
2024.12.08
no image
[Khan Academy] Scalars and Vectors in 1D
목차 Phycist's goal- precisely define quantities in the universe- find relationships between those quantitiesSo, vectors and scalars are needed. ScalarsOnly magnitude existsex) mass, distance, speed, volume, temperature, energy VectorMagnitude and direction existsex) position, displacement, velocity, acceleration cf) Position and temperatureYou can misunderstand position as scalar. But position is..
2024.12.05
no image
<Python 코딩 도장> day 4
목차[day 4]UNIT.7 출력 방법 알아보기sep, \n, end입력값 사이 무언가를 넣기(sep)띄어쓰기print(값1, 값2, 값3)-> 값1 값2 값3​문자 삽입print(값1, 값2, sep = '문자')# sep은 seperator에서 따옴# sep 뒤의 문자를 '구분자'라고 함 ex)print('010', '1234', '5678', sep='-')-> 010-1234-5678 출력 줄바꿈(\n)단순 Enter단순히 Enter를 이용하여 줄을 바꿀 수 있다.print(값1)print(값2)​제어문자 \nprint 한 번으로 줄바꿈을 넣을 수 있다.print(값1, 값2, sep='\n') 또는 print(값1\n값2) ​end 사용print(값1, end='구분자')print(값2, end..
2024.12.04
no image
<Python 코딩 도장> day 3
목차[day 3]UNIT.6 변수와 입력 사용하기변수, del, None, +=, input(), split(), map()변수 제작'='를 이용해서 변수에 값을 할당할 수 있다.ex) x = 10 y = '뉴진스'cf) Python 연산자 중 등호는 '=='이다. 변수명1. 숫자가 앞에 와선 안된다.2. 예약어(이미 함수, 변수 등으로 지정되어있는) 사용 금지3. _제외한 특수문자 사용 금지 변수 여러 개를 한 번에 제작다른 값들을 각각의 변수들에 한 번에 할당변수1, 변수2, 변수3 = 값1, 값2, 값3 같은 값을 여러 변수에 할당변수1 = 변수2 = 변수3 = 값1 변수 값 바꾸기변수1, 변수2 = 변수2, 변수1ex) x = 10, y = 20x, y = y, xprint(x) print(y) ..
2024.12.03
no image
<Python 코딩 도장> day 1~2
목차 Python을 공부하는 목적: 데이터 분석, 인공지능 분야 활용 가능 등인프런 강의를 수강하는데 너무 지엽적이라 내 목적과는 맞지 않아 보여서Python 공부 첫 단계로 이라는 책을 시립도서관에서 빌려왔다.하루에 2day씩 총 20일동안 공부할 예정이다.[day 1]UNIT 3. Hello, World!프로그램 실행 단축키는 ctrl + D키로 정했다.친구 김 모 군이 말하길, 이게 딱히 겹치는게 없다고 한다.​에서는 심사 사이트를 따로 제공한다.심사 사이트: https://dojang.io[day2]UNIT 4. 기본 문법 알아보기, 주석 작성 방법, 들여쓰기기본 문법주석코드를 설명해주는 부분# 뒤에 작성 들여쓰기Python은 들여쓰기 자체가 문법이다.스페이스 바 두 칸 혹은 네 칸, tab 한 ..
2024.12.03

[day 6]

UNIT.9 여러줄 문자열 사용하기

''' '''

 

여러 줄로 된 문자열 사용하기


'''(문자열)''' or """(문자열)"""

 

ex)

print('''check this out

나는 정 상 수 백발백중하는

명 사 수''')

->

check this out

나는 정 상 수 백발백중하는

명 사 수

문자열 안에 따옴표 포함하기


문자열 안에 작은 따옴표를 넣고 싶을 때

문자열을 큰 따옴표로 묶어준다.

 

문자열 안에 큰 따옴표를 넣고 싶을 때

문자열을 작은 따옴표로 묶어준다.

 

세 개의 따옴표로 묶인 문자열의 경우

종류에 상관없이 문자열에 따옴표를 포함시킬 수 있다.

 

이스케이프(escape) 시퀀스

\뒤에 따옴표를 붙이면 된다.

 

cf) 이스케이프 시퀀스란?

프로그래밍 언어 특성상 표현할 수 없는 문자를 표현하거나 제어에 이용되는 방식

\n(줄바꿈) \t(tab) \' \" 등이 있다. 

[day 7]

UNIT.10 리스트와 튜플 사용하기

list, range( ), tuple, list( ), tuple( ), 패킹, 언패킹

type: 리스트


리스트란?

말그대로 목록이다. 값들을 일렬로 늘어놓은 형태이다.

리스트를 왜 사용하는가?

만약, 값 30개를 저장하려면 어떻게 해야할까?

a1 = 값1

a2 = 값2

...a30 = 값30 / 끔찍하다.

이런 경우 리스트를 사용하면 편리하다.

리스트 제작

리스트 = [값1, 값2, 값3...] / 값1, 값2, 값3을 요소(element)라 부른다.

 

ex)

a = [1, 2, 3]

리스트에는 모든 type의 자료를 저장할 수 있으며, 섞어 저장해도 된다.

 

ex)

a = [1, 1.5, 'NewJeans', True]

print(a)

-> [1, 1.5, 'NewJeans', True]

빈 리스트 제작

a = [] or b = list()

print(a, b)

-> [] []

 

range를 사용한 리스트 제작


​range: 연속된 숫자를 생성한다.

- range(n): 0부터 n-1까지 숫자를 생성

- range(a, b): a부터 b-1까지 숫자를 생성

 

ex)

print(range(5)) -> range(0, 5)

print(range(5, 8)) -> range(5, 8)

list()에 range 넣어보기

print(list(range(n))) -> [0, 1, 2 ... n-1]

일정한 증가폭으로 숫자 생성

리스트 = list(range(시작, 끝, 증가폭))

 

ex)

print(list(range(10, 0, -2)))

-> [10, 8, 6, 4, 2]

type: 튜플


튜플이란?

리스트처럼 요소를 일렬로 저장하지만, 안에 저장한 요소를 변경, 추가, 삭제할 수 없다.

튜플 제작

튜플 = (값1, 값2, 값3)

튜플 = 값1, 값2, 값3

 

ex)

print((1, 2, 3)) -> (1, 2, 3)

튜플에도 리스트와 마찬가지로 모든 type의 자료를 사용할 수 있다.

 

빈 튜플 제작

리스트와 동일

 

튜플을 왜 사용하는가?

요소가 변경되면 안될 때 사용/반면 요소를 변경해야 할 때는 리스트 사용

요소가 한 개 들어있는 튜플


제작법

(값) - (X)

(값,) or 값, - (O)

 

ex)

print(('값')) -> 값(튜플로 출력되지 않음)

print(('값',)) -> (값,)(튜플로 출력됨)

 

왜 사용할까?

때때로 값 말고 튜플을 사용해야 하는 경우가 있기 때문이다.

range로 튜플 제작


list와 동일

튜플, 리스트 간의 변환


tuple( )과 list( )를 이용해 서로 변환할 수 있다.

 

ex)

a = [1, 2, 3]

print(tuple(a)) -> (1, 2, 3)

b = (1, 2, 3)

print(list(b)) -> [1, 2, 3]

문자 리스트/튜플


ex 1) 문자 리스트

print(list('Hanni')) -> ['H', 'a', 'n', 'n', 'i']

 

ex 2) 문자 튜플

print(tuple('Haerin')) -> ('H', 'a', 'e', 'r', 'i', 'n')

tuple( )과 list( )의 역할 총정리


list( )

빈 리스트 제작

range를 이용한 리스트 제작

튜플을 리스트로 변환

문자 리스트 생성

 

tuple( )

빈 튜플 제작

range를 이용한 튜플 제작

리스트를 튜플로 변환

문자 튜플 생성

패킹(packing), 언패킹(unpacking)


패킹

짐을 싼다: 리스트/튜플 안에 값을 넣는다.

패킹 예시

a = [1, 2, 3]

b = (1, 2, 3)

c = 1, 2, 3

패킹의 목적

한 변수에 리스트, 튜플을 할당시켜주는 것

언패킹(unpacking)

짐을 풀다: 리스트/튜플의 값을 밖으로 빼낸다.

언패킹 예시

a, b, c = [1, 2, 3]

d, e, f = (1, 2, 3)

g, h, i = 1, 2, 3

(변수 여러 개를 한 번에 제작하는 법은 사실 튜플 언패킹이었던 것이다.)

언패킹 목적

변수 여러 개에 리스트, 튜플 내의 값을 할당시켜주는 것

tip) 제발 input으로 입력받은 값은 str이라는 것을 잊지 말자(int 사용 중요)

'Python > <Python 코딩 도장>' 카테고리의 다른 글

<Python 코딩 도장> day 4  (0) 2024.12.04
<Python 코딩 도장> day 3  (1) 2024.12.03
<Python 코딩 도장> day 1~2  (0) 2024.12.03

Position vs. time graph(S-T graph)


It represents the position of an object as a function of time.

 

S-T graph's slope

It means object's velocity

 

$v=\frac{\Delta x}{\Delta t}$

[case 1] S-T graph is linear graph
It represents the object is moving with constant velocity.

[case 2] S-T graph isn't linear graph
slope of it's tangent line = velocity of the object(instantaneous velocity)

 

What is instantaneous velocity?

 

Instantaneous speed and velocity


Instantaneous speed

the speed of an object at a particular moment in time.

 

Instantaneous velocity

instantaneous speed + direction

 

$v_{inst}=\frac{small\,displacement}{short\,time\,interval}$

 

How to find instantaneous velocity

 

[case 1] calculous

To find correct instantaneous velocity, 

we should use much smaller displacement and much shorter time interval.

Sir Isaac Newton developed calculous to figure out answers to 0/0 questions.

With applying calculous, formula of instantaneous velocity is..


$v_{inst}=\frac{\delta x}{\delta t}$

[case 2] slope of S-T graph's tangent line
By drawing tangent line of S-T graph, we can know instantaneous velocity.
Slope of tangent line means instantaneous velocity.

 

[case 3] kinematic formula(When the acceleration is constant)


$v=v_0+at$


$\Delta x=v_0 t+\frac{1}{2}at^2$

 

cf) Average velocity

the average velocity of an object over an interval
: the slope of the line connecting the endpoints of the interval.

 

Acceleration


How quickly your velocity is changing


$a=\frac{\Delta v}{\Delta t}$


so, the unit of the acceleration is m/s^2

 

Direction of acceleration


[case 1] The object is speeding up

Direction of the acceleration and direction of the velocity is same

[case 2] The object is slowing down

Direction of the acceleration and direction of the velocity is opposite.


[case 3] The object's velocity is constant
acceleration is 0

cf) The object that moves on curve track with constant speed

Because its direction changes, the velocity changes too.

It means, the motion above is uniformly acclerated motion.

 

Velocity vs. time graph


It represents the velocity of an object as a function of time.


V-T graph's slope

It means object's acceleration

[case 1] V-T graph is linear graph
It represents the object is moving with constant acceleration.

[case 2] V-T graph isn't linear graph
slope of it's tangent line = acceleration of the object(instantaneous acceleration)


V-T graph's area

It means the object's displacement during that time interval.

 

배운 영단어


뜻을 몰랐던 영단어

slanted: 사선의

interval: 구간, 간격

quadratic function: 이차함수

initially: 처음에

rest: 정지

 

물리적 용어

A VS. B graph: A - B 그래프

tangent line: 접선

 

'Khan Academy > AP physics I' 카테고리의 다른 글

[Khan Academy] Visual models of motion  (0) 2024.12.08
[Khan Academy] Scalars and Vectors in 1D  (0) 2024.12.05

    Object model


    Ignoring internal structure

    When the interested quantities aren't affected by the object's size, shape, or internal structure, we can ignore them.

    ∴ It is useful to define an object as something whose internal structure is negligible.

     

    Object model

    1. ignore internal structure of the object.

    2. Define object as a particle.

     

    ex) We can define a car as a particle.

     

    Using the object model


    Particle diagram

    step 1. Apply 'object model' to the object.

    Than, there would be many particles which describe object's motion.

     

    step 2. [step 1]'s particles are qualitative.

    So we need to add quantitative information

    : 1) reference frame and 2) the elapsed time between each successive set of dots.

     

    Motion diagram

    : combine particle diagrams with vector arrows

    (You should write the physical quantity under the vector to denote what it is.

     

    cf) $vector's\,length=velocity's\,magnitude=\frac{distance\,during\,\Delta t}{\Delta t}$

     

    Example of particle & motion diagram

    step 1. There is running rabbit. We can apply object model to the rabbit.

    so cute

    step 2. Add reference frame of distance and the elapsed time between dots.

    Now the particle diagram about rabbit is complete.

     

    step 3. Add vector arrows about rabbit's velocity.

    $vector's\,length=velocity's\,magnitude=\frac{distance\,during\,3s}{3}$

     

    You can see the rabbit is doing 'uniformly accelerated motion'

     

    배운 영단어


    뜻을 몰랐던 영단어

    particle: 입자, 질점

    negligible: 불필요한

    qualitative: 질적인, 정성적인

    cf) 정성 실험: 증감 등의 경향성을 파악

    quantitative: 양적인, 정량적인

    cf) 정량 실험: 정확한 수치를 파악

    elapsed: (시간이)경과된

    denote: 표시하다, 나타내다

     

    물리적 용어

    uniformly accelerated motion: 등가속도 운동

    object model: 객체 모델

    목차

       

      Phycist's goal

      - precisely define quantities in the universe

      - find relationships between those quantities

      So, vectors and scalars are needed.

       

      Scalars


      Only magnitude exists

      ex) mass, distance, speed, volume, temperature, energy

       

      Vector


      Magnitude and direction exists

      ex) position, displacement, velocity, acceleration

       

      cf) Position and temperature

      You can misunderstand position as scalar. But position is vector.

      In defined coordinate system, [10m, right] and [10m, left] are different.

      (Complicated explanation about position is 

       

      You can also misunderstand temperature as vector. But temperature is scalar.

      There's no quantity like [36.5℃, left].

       

      Through these two cases, we can distinguish vectors and scalars much easier.

       

      <To The Left~ method>

      step 1. Put the word 'left' to certain quantity.

      step 2. If it's weird, that quantity is scalar.

      step 3. If it makes sense, that quantity is vector. 

       

      How to expressing vector 


      Vector notation

      - Draw an arrow over the quantity.

      - Or write the quantity in bold text.

      quantity vector
      position $\vec x$
      displacement $\Delta\vec x$
      velocity $\vec v$
      acceleration $\vec a$

       

      Expressing direction

      step 1. Defined coordinate system is essentially needed.

      step 2. with '+' & '-' sign

       

      Drawing a vector

      We can draw a vector with arrow.

      - length: magnitude of a vector

      - direction: direction of a vector

       

      cf) Vectors can be drawn proportionally appropriately.

      ex) velocity vectors [+6m/s] and [+4m/s] can be drawn with arrows which is ratio of 3:2.

       

      Visually adding & subtracting vectors


      <tip-to-tail> method

      step 1. Put 1st vector's tip to 2nd vector's tail.

      step 2. Connect 1st vector's tail to 2nd vector's tip.

       

      This method works for any number of vector in 1, 2, 3 dimentions.

       

      Adding

      by <tip-to-tail> method

       

      Subtracting

      step 1. Put '-' sign to the vector you want to subtract.

      step 2. Apply <tip-to-tail> method.

       

      Numerically adding & subtracting vectors


      We can do adding or subtracting vectors without drawing.

       

      step 1. Define a coordinate system.

      step 2. Just calculate like calculating numbers.

       

      Position, velocity, and speed


      Position(vector)

      length: distance in relation to an arbitary reference origin

       

      Displacement(vector)

      : change in position

       

      $\Delta\vec x=\vec x-\vec x_0$

       

      Velocity(vector)

      : How quickly the position changes.

       

      $\vec v=\frac{\Delta\vec x}{\Delta t}$

       

      +) relative velocity

      What is important in measuring velocity is 'where you are'.

       

      Speed(scalar)

      : How quickly the distance(: 이동거리) is travelled.

       

      $speed=\frac{distance}{\Delta t}$

       

      Difference of position vector and displacement vector

      $\vec r_2-\vec r_1=\vec d$

       

      Practice


      Practice - Scalars and vectors

      [case 1]

      step 1. Calculate the average velocity at time 0 ~ 10s and 10s ~ 20s.

      step 2. Calculate the average of step 1's average velocities.

       

      [case 2]

      step 1. Calculate displacement.

      step 2. Divide displacement by the amount of time.

       

      [case 2] is more efficient.

       

      배운 영단어


      물리적 용어

      position: 위치

      displacement: 변위

      coordinate system: 좌표계

       

      목차

        [day 4]

        UNIT.7 출력 방법 알아보기

        sep, \n, end

        입력값 사이 무언가를 넣기(sep)


        띄어쓰기

        print(값1, 값2, 값3)

        -> 값1 값2 값3

        문자 삽입

        print(값1, 값2, sep = '문자')

        # sep은 seperator에서 따옴

        # sep 뒤의 문자를 '구분자'라고 함

         

        ex)

        print('010', '1234', '5678', sep='-')

        -> 010-1234-5678

         

        출력 줄바꿈(\n)


        단순 Enter

        단순히 Enter를 이용하여 줄을 바꿀 수 있다.

        print(값1)

        print(값2)

        제어문자 \n

        print 한 번으로 줄바꿈을 넣을 수 있다.

        print(값1, 값2, sep='\n')

        또는 print(값1\n값2)

         

        end 사용


        print(값1, end='구분자')

        print(값2, end='구분자')

        -> 값1구분자값2구분자

         

        ex)

        print('New', end='/')

        print('Jeans', end='~')

        -> New/Jeans~

        cf) 원래 형태를 이렇게 생각하면 이해가 쉽다.

        print('값1', end='\n')

         

        <심사 문제: 날짜와 시간 출력하기>


        step 1. 제작 단계 구상

        i) 입력을 받아야 하므로 연, 달, 일, 시, 분, 초를 변수로 둔다.

        ii) 한 줄로 출력되게 한다.

        iii) 날짜는 /로 구분, 시간은 :로 구분되게 한다.

        step 2. 제작

         

        i) 변수 설정

         

        1. 변수들의 이름을 설정

        2. input과 split을 통해 입력값을 한 번에 입력할 수 있게 한다.

        ii) 한 줄 출력, 구분자

         

        1. end = ' '를 통해

        띄어쓰기를 기준으로 네 줄의 출력이 구분되며/한 줄로 출력되게 한다.

        2. sep = '/', sep = ':'을 통해 출력값들을 구분되게 한다.

        step 3. 결과

        year, month, day, hour, minute = input('날짜, 시간을 입력하세요').split('/')
        print('오늘의 날짜는', end = ' ')
        print(year, month, day, sep = '/', end = ' ')
        print('현재 시각은', end = ' ')
        print(hour, minute, sep = ':' )
         
        -> 날짜, 시간을 입력하세요2024/12/04/13/08
        오늘의 날짜는 2024/12/04 현재 시각은 13:08

         

        i) 시행착오

        1. input, split, end, sep 등의 괄호 안에 str을 넣을 때, print와 마찬가지로 ' '을 신경써야 한다.

        'Python > <Python 코딩 도장>' 카테고리의 다른 글

        <Python 코딩 도장> day 6~7  (0) 2025.01.11
        <Python 코딩 도장> day 3  (1) 2024.12.03
        <Python 코딩 도장> day 1~2  (0) 2024.12.03

        목차

          [day 3]

            UNIT.6 변수와 입력 사용하기

            변수, del, None, +=, input(), split(), map()

            변수 제작


            '='를 이용해서 변수에 값을 할당할 수 있다.

            ex)

            x = 10 y = '뉴진스'

            cf) Python 연산자 중 등호는 '=='이다.

             

            변수명

            1. 숫자가 앞에 와선 안된다.

            2. 예약어(이미 함수, 변수 등으로 지정되어있는) 사용 금지

            3. _제외한 특수문자 사용 금지

            변수 여러 개를 한 번에 제작


            다른 값들을 각각의 변수들에 한 번에 할당

            변수1, 변수2, 변수3 = 값1, 값2, 값3

             

            같은 값을 여러 변수에 할당

            변수1 = 변수2 = 변수3 = 값1

             

            변수 값 바꾸기

            변수1, 변수2 = 변수2, 변수1

            ex)

            x = 10, y = 20

            x, y = y, x

            print(x) print(y) -> 20 10

            변수 삭제, 빈 변수


            변수 삭제하기

            'del 변수'를 통해 변수를 삭제할 수 있다.

            ex) x = 10

            del x

            print(x) -> ERROR

             

            빈 변수 제작

            변수 = None

            ex) x = None

            print(x) -> None

            산술 연산 후 할당 연산자 사용


            ex) 변수 x의 값을 20 증가시킨채로 저장하려 할 때

            x = 20

            print(x) -> 20

            ----------

            x = x + 20

            print(x) -> 40(20에 20이 더해진 값)

             

            x를 두 번 써줘야하니 번거롭다. 이를 해결할 순 없을까?

            간단하다. 'x = x + 20'을 'x += 20'으로 축약하면 된다.

            이는 -=, *=, /=, //=, %= 도 같은 방식이다.

            고정된 값이 아닌 다양한 값을 변수에 할당하려면?


            input 함수를 사용

            ex) name = input('너의 이름은?')

            print('내 이름은' + name)

            -> '너의 이름은?'이라 묻는 창이 뜨고 거기에 대답을 입력하면

            '내 이름은 (대답)'이 출력된다.

             

            프롬프트(prompt)

            input(프롬프트)

            사용자에게 입력받는 값의 용도를 알려준다.

             

            VScode에서 input함수를 실행

            별도의 작업이 필요하다.

            1. 왼쪽 탭에서 Run and Debug 탭을 클릭

            2. Python File Debug the currently active Python file을 클릭

            3. TERMINAL에서 input값을 입력할 수 있게 된다.

             

            input 함수에 대한 대답은 str로 간주

            ex1)

            a = input()

            print(type(a)) -> a에 정수, 실수를 입력해도 str이 출력된다.

             

            ex2) 숫자 세 개를 입력하면 더해주는 프로그램

            a, b, c = input('숫자 1: '), input('숫자 2: '), input('숫자 3: ')

            print(int(a) + int(b) + int(c))

            -> 숫자 세 개를 하나하나 입력하면 더해준다.

            input 한 번에 값 여러개를 입력받으려면?


            split 함수

            입력값을 공백 기준으로 구분해준다.

            ex) print('I have an apple'.split())

            -> 'I' 'have' 'an' 'apple'

             

            split을 input과 함께 사용

             

            ex1) a, b = input('문자열 두 개를 입력해라: ').split()

            여기서 input에 'New Jeans'를 입력해주면

            step1. split이 입력받은 문자열을 'New'와 'Jeans'로 나눈다.

            step2. 'New'는 a에, 'Jeans'는 b에 할당된다.

             

            ex2) 숫자 세 개를 한 번에 입력하면 더해주는 프로그램

            a, b, c = input('숫자 3개를 입력해').split()

            print(int(a) + int(b) + int(c))

            -> 숫자 세 개를 띄어 쓰면 split이 a, b, c에 각각 저장하여 더해준다.

             

            각각 int 붙여주는게 귀찮다+ int는 float -> int, str -> int 기능은 있으나 list는 변환 불가능

            객체의 type을 한번에 int로 변환하기 위해

            list도 int로 변환할 수 있게 -> map 함수를 사용

            map(변환해줄 type, input().split())

             

            ex) 숫자 세 개를 한 번에 입력하면 더해주는 프로그램

            a, b, c = map(float, input('숫자 3개를 입력해').split())

            print(a + b + c)

            -> 숫자 세 개를 띄어 쓰면 split이 a, b, c에 각각 저장하고

            map은 이를 str에서 float로 변환해 더해준다.

            split의 입력값 구분을 다른 문자로 해보고싶다면?


            .split(구분자)

            여기서 중요한 것은, '구분자'

             

            ex) 숫자 세 개를 한 번에 입력하면 더해주는 프로그램

            a, b, c = map(float, input('숫자 3개를 입력해').split('+'))

            print(a + b + c)

            -> a+b+c를 입력하면 split이 a, b, c에 각각 저장하고

            map은 이를 str에서 float로 변환해 더해준다.

            UNIT.6의 중심 내용, '숫자 세 개 더하기 프로그램' 변천사


            노란색: 전 단계 대비 개선점

             

            step 1

            a, b, c = input('숫자 1: '), input('숫자 2: '), input('숫자 3: ')

            print(int(a) + int(b) + int(c))

            1. 숫자 1, 숫자 2, 숫자 3에 각각 값을 입력

            2. 아직 str값이므로 하나하나 int로 변환시켜준 후

            3. 더해서 출력

             

            step 2

            a, b, c = input('숫자 3개를 입력해').split()

            print(int(a) + int(b) + int(c))

            1. 숫자 세 개를 띄어쓰며 한 번에 입력

            2. 아직 str값이므로 하나하나 int로 변환시켜준 후

            3. 더해서 출력

             

            step 3

            a, b, c = map(float, input('숫자 3개를 입력해').split())

            print(a + b + c)

            1. 숫자 세 개를 띄어쓰며 한 번에 입력

            2. 아직 str값이므로 map으로 한 번에 int로 변환시켜준 후

            3. 더해서 출력

             

            step 4

            a, b, c = map(float, input('숫자 3개를 입력해').split(+))

            print(a + b + c)

            1. 숫자 세 개를 +으로 연결해 입력

            2. 아직 str값이므로 map으로 한 번에 int로 변환시켜준 후

            3. 더해서 출력

             

            tip) 멀티 커서: Alt를 누른 채로 커서를 클릭하면 그 자리에 커서가 남는다.

             

            'Python > <Python 코딩 도장>' 카테고리의 다른 글

            <Python 코딩 도장> day 6~7  (0) 2025.01.11
            <Python 코딩 도장> day 4  (0) 2024.12.04
            <Python 코딩 도장> day 1~2  (0) 2024.12.03

            목차

                     

                    Python을 공부하는 목적: 데이터 분석, 인공지능 분야 활용 가능 등

                      인프런 강의를 수강하는데 너무 지엽적이라 내 목적과는 맞지 않아 보여서

                      Python 공부 첫 단계로 <Python 코딩 도장>이라는 책을 시립도서관에서 빌려왔다.

                      하루에 2day씩 총 20일동안 공부할 예정이다.

                      [day 1]

                      UNIT 3. Hello, World!

                      프로그램 실행 단축키는 ctrl + D키로 정했다.

                      친구 김 모 군이 말하길, 이게 딱히 겹치는게 없다고 한다.

                      <Python 코딩 도장>에서는 심사 사이트를 따로 제공한다.

                      심사 사이트: https://dojang.io


                      [day2]

                      UNIT 4. 기본 문법 알아보기, 주석 작성 방법, 들여쓰기

                      기본 문법


                      주석

                      코드를 설명해주는 부분

                      # 뒤에 작성

                       

                      들여쓰기

                      Python은 들여쓰기 자체가 문법이다.

                      스페이스 바 두 칸 혹은 네 칸, tab 한 칸으로 들여쓰기를 해준다.

                       

                      ex)

                      if a == 20:

                      print('20이네요')

                       

                      코드 블록

                      특정 동작을 위해 코드가 모여 있는 상태, 들여쓰기를 동일하게 해줘야 한다.

                       

                      ex)

                      if a == 20

                      print(20)

                      print('입니다') (두 print문의 들여쓰기가 동일)


                      UNIT 5. 숫자 계산하기
                      type의 존재, 연산자

                      사칙연산


                      + - * / 를 통해 사칙연산이 가능

                      버림 나눗셈(floor division)(//)

                      나눗셈의 결과에서 몫만 표시

                       

                      cf) 버림 나눗셈이 필요한 이유

                      ​'정수 / 정수'의 경우 Python 2에서는 정수로만 값이 나오고, 3에서는 실수로만 값이 나옴

                       

                      ex)

                      print(5/2) (2) -> 2 (3) -> 2.5

                      print(4/2) (2) -> 2 (3) -> 2.0

                      ----------

                      Python3에서 '정수 / 정수'의 값이 정수로 나오게 하려면 // 사용

                       

                      ex)

                      print(5//2) -> 2(.5 생략)

                      print(4//2) -> 2(.0 생략)

                      모듈로 연산자(%)

                      나눗셈의 결과에서 나머지만 표시

                      divmod 연산자

                      몫과 나머지를 전부 표시​​

                      divmod(나눠지는 값, 나누는 값)

                      # 이때 괄호로 묶은 형태를 튜플(tuple)이라 한다.(나중에 다룰 예정)

                      거듭제곱 연산자(**)

                      ex) print(2**10) -> 1024

                      2진수, 8진수, 16진수 표현

                      각각 0b, 0o, 0x를 앞에 붙여 표현한다.

                       

                      ex)

                      print(0b101) -> 5

                      type


                      Python의 객체들에는 type이 존재한다.

                      int: 정수, float: 실수, complex: 복소수, str: 문자열, tuple: 튜플 등

                       

                      숫자 type

                      Python에선 숫자를 정수(int), 실수(float), 복소수(complex)로 구분

                      개체를 정수, 실수로 변환하는법


                      int(정수로 변환하려는 숫자/계산식/문자열)

                      소수점 아래는 버린다.

                       

                      ex)

                      print(int(2.5)) -> 2

                      print(int('20') -> 20

                      float(실수로 변환하려는 숫자/계산식/문자열)

                      'Python > <Python 코딩 도장>' 카테고리의 다른 글

                      <Python 코딩 도장> day 6~7  (0) 2025.01.11
                      <Python 코딩 도장> day 4  (0) 2024.12.04
                      <Python 코딩 도장> day 3  (1) 2024.12.03