따릉이
[파이썬] Types, Operators, Strings, Function, List, Tuple, Set, Dict 본문
파이썬
[파이썬] Types, Operators, Strings, Function, List, Tuple, Set, Dict
ObserverPoa 2021. 1. 11. 03:481. Numeric Types
a = 300 # int (10진수)
b = 10.12 # float
c = 10 + 2j # complex
d = 0b1001 # int (2진수)
e = 0o1001 # int (8진수)
f = 0x1001 # int (16진수)
print(type(a)) # object a의 class 이름 출력
print(dir(a)) # object a의 attribute 목록 출력
<class 'int'>
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__',
'__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__',
'__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__',
'__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__',
'__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__',
'__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__',
'__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__',
'__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__',
'__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator',
'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
2. Arithmetic Operators
x = 20
y = 3
print(x + y) # 합
print(x - y) # 차
print(x * y) # 곱
print(x / y) # 몫 (실수)
print(x // y) # 몫 (정수) (소숫점 아래 버림)
print(x % y) # 나머지
print(x ** y) # x의 y제곱
23
17
60
6.666666666666667
6
2
8000
3. Boolean Type, Logical Operators
x = True # bool
y = False # bool
print(bool(1))
print(bool(' '))
print(bool(0))
print(bool(''))
print(bool(None), '\n')
print(x or y) # ||
print(x and y) # &&
print(not x) # !
True
True
False
False
False
True
False
False
4. Comparison Operators
x = 15
print(x < 15) # less than
print(x <= 15) # less than or equal
print(x > 15) # larger than
print(x >= 15) # larger than or equal
print(x == 15) # equal
print(x != 15) # not equal
False
True
False
True
True
False
5. Bitwise Operators
x = 0b1010
print(bin(x | 0b0101)) # bitwise or
print(bin(x ^ 0b0000)) # bitwise exclusive or
print(bin(x & 0b1111)) # bitwise and
print(bin(x << 2)) # bitwise shift left
print(bin(x >> 2)) # bitwise shift right
print(bin(~x)) # bitwise not
0b1111
0b1010
0b1010
0b101000
0b10
-0b1011 // 0b101
6. Strings
s = 'hello Ttareungi bike' # str
print(s[0]) # indexing
print(s[6:15]) # slicing ([start:stop]일 떄, start ~ stop - 1 의 substring이 반환된다.)
print(s[0:15:2]) # stride를 명시한 slicing ([start:stop:step]일 때, step만큼 건너뛰며 retrieve한다.)
print(s[::-1], '\n') # 전체 string 역순
''' start또는 stop을 비우면 문자열의 양 끝까지을 의미하게 된다.
step이 양수이면 일반적으로 (start < stop)으로 하고, step이 음수이면 일반적으로 (start > stop)으로 한다.
그리고, i >= 0 일때 (s[i] < stop)과 (s[i] = start + step*i)을
만족하는 s[i]들로 이루어진 str이 retrieve된다.
'''
print(s[-1]) # 마지막 문자의 index
print(s[-4], '\n') # (== s[16])
print(s.upper()) # 전체 대문자화한 문자열 반환
print(s.lower()) # 전체 소문자화한 문자열 반환
print(s.count('i')) # 'i'의 개수
print(' hi! '.strip()) # 앞 뒤의 공백문자 전부 제거한 문자열 반환
print('apple|pear|oragne'.split('|')) # '|'을 기준으로 문자열을 split 하여 list를 반환
print('/'.join(['red', 'green', 'blue'])) # string list를 '/'구분자를 사용하여 한개의 string으로 연결한 문자열 반환
print("My name is {0}. and i'm {5} years old.".format('aaa', 'bbb', 'ccc', '11', '22', '33'), '\n')
s2 = "Sammy likes to swim in the ocean, likes to spin up servers, and likes to smile."
print("first match index", s2.find("likes", 0, 40), end = ".", sep = ": ") # 일치하는 것 중 가장 첫번째의 index
h
Ttareungi
hloTaeni
ekib ignueratT olleh
e
b
HELLO TTAREUNGI BIKE
hello ttareungi bike
2
hi!
['apple', 'pear', 'oragne']
red/green/blue
My name is aaa. and i'm 33 years old.
first match index: 6.
[참고]
https://stackoverflow.com/questions/509211/understanding-slice-notation
www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3
7. Type Casting
a = 10
b = "10"
print(str(a) + b) # 형 변환
a += int(b)
print(a)
1010
20
8. Function, global/local variables
* 함수 정의 영역의 범위는 indent(공백4개)를 통해 구분한다.
* 함수 내에서 global를 사용하면, 해당 함수의 scope에 대해서만 global이 선언된다. (nested function의 경우 주의)
def f(x, y):
z = x + y
return z
print(f(3, 5), '\n')
def aplus():
global a # 전역변수를 수정하기 위해 'global' keyword 사용
a += 10
return None # 이 line은 생략가능하다.
a = 10 # 전역변수
aplus()
print(a, '\n')
def func():
a = 2 # 지역변수
def change():
nonlocal a # 가장 근접한 바깥 scope인, func()의 a를 가리키게 함.
a = 3
print(a)
change()
print(a)
a = 4
func()
print(a)
8
20
2
3
4
[참고]
www.geeksforgeeks.org/global-keyword-in-python/
9. List
l = [10, 20, 30, 40] #순서가 있고, 변경가능한 자료형, string 처럼 slicing 가능 ([start:stop:step])
print(l)
print(type(l))
l[1] = 50
print(l)
l.append(70)
l.append(70)
print(l)
print(l.count(70))
l.extend([-1, -2, -3])
print(l)
print(l.index(-1))
print(sorted(l))
print(l, '\n')
l.sort()
print(l)
[10, 20, 30, 40]
<class 'list'>
[10, 50, 30, 40]
[10, 50, 30, 40, 70, 70]
2
[10, 50, 30, 40, 70, 70, -1, -2, -3]
6
[-3, -2, -1, 10, 30, 40, 50, 70, 70]
[10, 50, 30, 40, 70, 70, -1, -2, -3]
[-3, -2, -1, 10, 30, 40, 50, 70, 70]
10. Tuple
l = [10, 20, 30, 40]
t = (100, 200, 300, l) # 순서가 있고, 변경이 불가능한 자료형
print(t)
print(type(t))
print(t)
l.clear()
print(t) # t는 참조 불변이다. (참조하고있는 대상의 값은 변경가능)
(100, 200, 300, [-3, -2, -1, 10, 30, 40, 50, 70, 70])
<class 'tuple'>
(100, 200, 300, [-3, -2, -1, 10, 30, 40, 50, 70, 70])
(100, 200, 300, [])
11. Set
s = {10, 2, 2, 300, 300, 4, 4, 4, 5} # 순서가 없고, 중복이 없는 자료형
print(s)
print(type(s))
print(set('aabbccddeefffffzzzthhh'))
{2, 4, 5, 10, 300}
<class 'set'>
{'h', 'd', 't', 'a', 'e', 'c', 'z', 'f', 'b'}
12. Dict
d = {'one':10, 'two':20, 'three':30, "thirty":30} #순서가 없고, 키의 중복을 허용하지 않음
print(type(d))
print(d['one'])
print(d.values()) #중복인 value들을 그대로 출력
print(d.keys())
lis = list(d.items())
print(type(lis))
print(lis[2][1])
d2 = d #포인터 copy
d2 = d.copy() #내용물 copy
<class 'dict'>
10
dict_values([10, 20, 30, 30])
dict_keys(['one', 'two', 'three', 'thirty'])
<class 'list'>
30
[해당강좌]
HTML, CSS, JS, Python 30분 요약강좌 - 인프런
이 강좌는 코딩을 처음 하시는 분들에게는 빠르게 훑을 수 있는 강의가 될 것입니다. 이미 코딩을 하시는 분들에게는 복습을 빠르게 할 수 있는 강의가 될 것입니다. 이 강의를 통해 자신감을 얻
www.inflearn.com
'파이썬' 카테고리의 다른 글
[날씨 API] 기온, 풍속, 강수량, 습도, 미세먼지, 초미세먼지, 오존 (0) | 2021.07.06 |
---|---|
[파이썬] Control statements, range(), enumerate(), List Comprehension, Generator Expression, Class (0) | 2021.01.12 |
[파이썬_기초] 7. 파일 입출력 (0) | 2021.01.10 |
[파이썬_기초] 6. 예외 처리 & 내장 함수, 외장 함수 (0) | 2021.01.10 |
[파이썬_기초] 5(2). 모듈 & 패키지 (0) | 2021.01.10 |
Comments