티스토리 뷰

728x90
반응형

파이썬 문법 정리

용어

표현식 : 값을 만들어내는 코드

273 # 값
10 + 20 30 * 10 # 값

문장 : 표현식이 하나 이상 모인 것

프로그램 : 문장이 모인 것

표현식 -> 문장 -> 프로그램

키워드 : 예약어로도 부름.

>>> import keword
>>> print(keyword.kwlist) # python 키워드들 모두 출력가능

['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

식별자 : 변수 또는 함수.

식별자 생성 시 주의 사항

  • 키워드, 숫자, 공백 사용금지
  • 특수문자는 언더 바(_)만 허용
  • SnakeCase(=단어 사이 언더 바로 추가) 또는 CamelCase(= 단어들의 첫 글자를 대문자 시작)로 주로 작성

식별자 구분하기

CamelCase : 클래스 ex) PrintHello
SnakeCase : 함수, 변수 ex)print_hello(), print.hello

주석 : # 기호로 처리

자료형

  • 문자열, 숫자, 불(boolean)이 있음
  • **type()**로 자료형 확인 가능
>>> type("hh")
<class 'str'>
>>> type(1)
<class 'int'>
>>> type(1.2)
<class 'float'>

문자열 만들기

큰 따옴표로 문자열 만들기

>>> print("hello")
hello

작은 따옴표로 문자열 만들기

>>> print('hello')
hello

문자열 내부에 따옴표 넣기

>>> print("'hello' world")
'hello' world
>>> print('"hello" world')
"hello" world

이스케이프 문자 사용법

이스케이프 문자 : 역 슬래쉬() 기호와 함께 조합해서 사용하는 특수문자

>>> print("\"hello\" world")
"hello" world
\n : 줄바꿈, \t : 탭

문자열 연산자

# + : 문자열 연결 연산자
>>> print('hello' + 'world')
helloworld

# * : 문자열 반복 연산자
>>> print('hello'*3)
hellohellohello

# [] : 문자열 선택 범위 연산자(인덱싱) 
>>> print('helloworld'[0])
h
>>> print('helloworld'[1])
e
>>> print('helloworld'[2])
l

# [:] : 문자열 선택 범위 연산자(슬라이싱) 
# 양수는 문자열 시작점에서 앞으로 이동, 음수는 문자열 시작점에서 뒤로 이동
>>> print('helloworld'[0:5])
hello
>>> print('helloworld'[0:-1])
helloworl
>>> print('helloworld'[0:-4])
hellow
>>> print('helloworld'[0:4])
hell
>>> print('helloworld'[1:]) # 인덱스가 생략될 경우, 처음 또는 끝을 지정함
elloworld
>>> print('helloworld'[:3])
hel

# 범위에 맞지 않는 인덱스 참조를 시도할 경우, IndexError가 발생할 수 있으니 

인덱싱 : 문자를 참조하는 것

슬라이싱 : 문자열 일부를 추출하는 것

문자열 길이 구하기

>>> len('hello')
5

숫자 연산자

# +,-,*,/ :사칙연산자
>>> print("5 + 7 = ", 5 + 7)
5 + 7 =  12
>>> print("5 - 7 = ", 5 - 7)
5 - 7 =  -2
>>> print("5 * 7 = ", 5 * 7)
5 * 7 =  35
>>> print("5 / 7 = ", 5 / 7)
5 / 7 =  0.7142857142857143

# // : 정수나누기 (소수점 버리는 연산)
>>> print("3 // 2 = ", 3 // 2)
3 // 2 =  1

# % : 나머지 연산자
>>> print("3 % 2 = ", 3 % 2)
3 % 2 =  1

# ** : 제곱 연산자
>>> print("3 ** 2 = ", 3 ** 2)
3 ** 2 =  9

# Type이 맞지 않은 자료형과 연산을 수행할 경우, TypeError가 발생할 수 있으니 주의할 것.

변수 만들기

>>> pi = 3.14159 # 변수 선언 및값 할당
>>> print(pi) # 변수 참조
3.14159

# 파이썬은 C/C++, C#, Java와 다르게 변수를 미리 선언하지 않아도 된다.

# +=, -=, *=,/=, %=, **= : 복합 대입 연산자, 기존 연산자의 조합으로 연산 수행
>>> num = 100
>>> print(num)
100
>>> num += 10
>>> print(num)
110
>>> num -= 10
>>> print(num)
100
>>> num *= 2
>>> print(num)
200
>>> num /= 2
>>> print(num)
100.0

사용자 입력받기

# input함수로 사용자 입력 받기
>>> string = input("Enter the keyboard : ")
Enter the keyboard : My name is HoHo
>>> print(string)
My name is HoHo

## input()으로 저장한 모든 값은 문자열이 된다는 것에 주의

문자열을 숫자로 바꾸기

# int(), float() 함수로 문자열을 정수 및 실수로 바꾸기
>>> string = input("Enter the number : ")
Enter the number : 123
>>> print(type(string))
<class 'str'>
>>> string = int(string)
>>> print(type(string))
<class 'int'>

# 자료를 변경할 수 없는 경우 ValueError가 발생할 수 있으므로, 변환하고자 하는 자료를 확인하고 진행할 것

숫자를 문자열로 바꾸기

>>> num = str(123)
>>> type(num)
<class 'str'>

>>> string_a = "{}".format(10) # format 함수를 이용하여 숫자를 문자열로 변환
>>> print(string_a)
10
>>> type(string_a)
<class 'str'>

>>> string = "My name is {}. My age is {}".format("shcheon",33) # {}는 매개변수를 대체하는 역할하는 기호라고 보면 됨
>>> print(string)
My name is shcheon. My age is 33

정수 출력하기

>>> print("{:d}".format(52))	# 정수 출력
52
>>> print("{:10d}".format(52))	# 10칸 안에 52 숫자 출력
        52
>>> print("{:05d}".format(52))	# 빈칸을 0으로 채우고 숫자 출력
00052

# 기호 붙혀서 정수 출력하기
>>> print("{:+d}".format(52))
+52
>>> print("{:-d}".format(52))
52
>>> print("{: d}".format(52))
 52
>>> print("{: d}".format(-52))
-52

# 기호를 특정칸에 붙혀 숫자 출력하기
>>> print("{:+5d}".format(52))
  +52
>>> print("{:=+5d}".format(52))
+  52
>>> print("{:+05d}".format(52))
+0052
>>> print("{:+05d}".format(-52))
-0052

부동 소수점 출력하기

# 특정 위치에 소수점 출력하기
>>> print("{:f}".format(3.14150))
3.141500
>>> print("{:15f}".format(3.14150))
       3.141500
>>> print("{:+15f}".format(3.14150))
      +3.141500
>>> print("{:+015f}".format(3.14150))
+0000003.141500

# 소수점 마지막 자리가 0은 출력하지 않기
>>> print("{:g}".format(3.14150))
3.1415

대소문자 변경하기

# upper(), lower()를 이용하여 대소문자 변경하기
>>> print("Hello World".upper())
HELLO WORLD
>>> print("Hello World".lower())
hello world

문자열 양옆의 공백 제거하기

# strip(), lstrip(), rstrip()으로 문자열 내 공백 제거하기 
>>> print("  Hello World  ".strip())
Hello World
>>> print("  Hello World  ".lstrip())
Hello World  
>>> print("  Hello World  ".rstrip())
  Hello World

문자열의 구성 파악하기

# isOO 계열의 함수를 이용하여 문자열의 구성을 파악할 수 있음
>>> print("HELLOWORLD".isupper())
True
>>> print("helloworld".islower())
True
>>> print("1234".isdigit())

문자열 찾기

# 왼쪽부터 시작하여 발견한 문자열의 인덱스를 반환하는 find()
# 오른쪽부터 시작하여 발견한 문자열의 인덱스를 반환하는 rfind()
>>> print("helloworld".find("ell"))
1
>>> print("helloworld".find("o"))
4
>>> print("helloworld".rfind("o"))
6

# in연산자 : 문자열 내부에 문자열이 있는지 확인
>>> print('hell' in 'helloworld')
True

문자열 자르기

# split() : 특정한 문자를 기준으로 문자열을 자를 때 사용, 자른 결과는 list로 나옴
>>> a = "1 2 3 4 5 6 7".split(" ")
>>> print(a)
['1', '2', '3', '4', '5', '6', '7']
>>> type(a)
<class 'list'>

 

728x90
반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함