본문 바로가기

코딩과 교육/파이썬

02강 프로그램기초 - 상수, 변수, 문자열, 연산자 등


◆ 주석 - # 문자 뒤에 따라오는 짧은 문장


print('hello world') # Note that print is a statement

# Note that print is a statement


◆ 리터럴 상수

- 5

- 1.23

- ‘This is a book’

- “Sting”


◆ 숫자형

- 정수형 : 5

- long 형이 없다


import sys


t1 = sys.maxsize

# t1 = sys.maxint


t2 = t1+1 #int범위를 넘으면 long 자동 형 변환

t3 = t2**10


print(t1)

print(t2)

print(t3)


print(type(t1))

print(type(t2))

print(type(t3))


- 소수점 숫자형 : 4.16, 52.3E-3 (= )


◆ 문자열


◆ 작은 따옴표(‘’)와 큰 따옴표(“”)


◆ 따옴표 세 개


◆ 문자열 수정은 불가


◆ format()

str_format.py


age = 26

name = 'Python'


print('{0} was {1} years old'.format(name, age))

print('{0} is easy'.format(name))



◆ format() 대신 문자열 더하기


print(name + ' is ' + str(age) + ' years old')


※ 위의 형식보다는 format()을 사용하는 것을 추천


◆ 중괄호 숫자 생략 가능


age = 19

name = 'Baram'


print('{} was {} years old'.format(name, age))

print('Why is {} playing with that python?'.format(name))



◆ format() 의 또 다른 사용법


# 소수점 이하 셋째 자리까지 부동 소숫점 숫자 표기 (0.333)

print('{0:.3f}'.format(1.0/3))

# 밑줄(_)로 11칸을 채우고 가운데 정렬(^)하기 (___hello___)

print('{0:_^11}'.format('hello'))

# 사용자 지정 키워드를 이용해  표기

print('{name} wrote {book}'.format(name='Baram', book='Easy Arduino'))



◆ print() 사용시 줄바꿈을 막으려면,


print("Hello ", end='')

print("World")



◆ 특수(Escape) 문자

\'

"'"

'"'

\"

\\

\n

\t


◆ 순문자열 

r"Newlines are indicated by \n“


◆ 변수


- 식별자의 첫 문자는 알파벳 문자 (ASCII 대/소문자 혹은 유니코드 문자)이거나 밑줄 (_)


- 나머지는 문자 (ASCII 대/소문자 혹은 유니코드 문자), 밑줄 (_), 또는 숫자 (0-9)


- 식별자는 대/소문자를 구분. 예를 들어, myname 과 myName 은 다르다.


- 올바른 식별자 이름은 i, name_2_3 등과 같고, 올바르지 않은 식별자 이름은 2things, this is spaced out, my-name, >a1b2_c3 등입니다.



◆ 명시적 행간결합


s = ' Hello \

World'


print(s)


◆ 들여쓰기 – 4칸 들여쓰기


◆ 연산자


>>> 2 + 3

5

>>> 3 * 5

15

>>>



+ (덧셈 연산자)

- (뺄셈 연산자)

* (곱셈 연산자)

** (거듭제곱 연산자)

/ (나눗셈 연산자)

% (나머지 연산자)

<< (왼쪽 시프트 연산자)

>> (오른쪽 시프트 연산자)

& (비트 AND 연산자)

| (비트 OR 연산자)

^ (비트 XOR 연산자)

~ (비트 반전 연산자)

< (작음)

> (큼)

<= (작거나 같음)

>= (크거나 같음)

== (같음)

!= (같지 않음)

not (불리언 NOT 연산자)

and (불리언 AND 연산자)

or (불리언 OR 연산자)


◆ 연산 및 할당 연산자


a = a*3 은

a *= 3 과 동일


◆ 연산순서


● lambda

● if – else

● or

● and

● not x

● in, not in, is, is not, <, ⇐, >, >=, !=, ==

● |

● ^

● &

● <<, >>

● +, -

● *, /, //, %

● +x, -x, ~x

● **

● x[index], x[index:index], x(arguments…​), x.attribute

● (expressions…​), [expressions…​], {key: value…​}, {expressions…​}



◆ ( ) 이용한 연산순서 변경

● 2 + 3 * 4 + 5

● 2 + 3 * (4 + 5)

● 2 + (3 * (4 + 5))