파이썬의 기본 문법
변수 선언, 식별자, 자료형, 형변환, 연산자 학습
1 2 3 4 5 6 7 8 9 print(1 ) print(3 )
1
3
1 2 3 4 5 6 a = 1 b = 2 print(b) c = 3 b = 4 print(b)
2
4
1 2 3 4 5 print(1 ,2 , sep="-" , end="\t" ) print(3 )
1-2 3
1
2. 변수 선언
3. 식별자
변수, 함수, 클래스, 모듈등의 이름을 식별자 라고 합니다.
식별자 규칙
소문자, 대문자, 숫자, 언더스코어(_)를 사용합니다.
가장 압에 숫자 사용 불가
예약어의 사용 불가 : def, class, try, except …
컨벤션
snake case : fast_campus : 변수, 함수 _ camel case : FastCampus, fastCampus : 클래스
4. 데이터 다입
RAM 저장공간을 효율적으로 사용하기 위해 저장공간의 타입을 설정
동적타이핑
변수 선언시 저장되는 값에 따라서 자동으로 데이터 타입이 설정
기본 데이터 타입 : int, float, bool, str
컬렉션 데이터 타입 : list, tuple, dict
1 2 3 4 a = 1 b = "python" type (a), type (b)
(int, str)
1 2 3 4 5 6 a = 1 b = 1.2 c = True d = "data" type (a),type (b),type (c),type (d)
(int, float, bool, str)
2.2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-4fbab87c839c> in <module>
----> 1 a + d
TypeError: unsupported operand type(s) for +: 'int' and 'str'
('data', 'DATA')
'fast campus'
'Fast Campus'
1 2 f.replace("Fast" , "Slow" )
'Slow Campus'
'FastCampus'
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
1 g[2 ], g[-2 ], g[2 :5 ], g[:2 ], g[3 :], g[-2 :], g[::2 ], g[::-1 ]
('c', 'f', 'cde', 'ab', 'defg', 'fg', 'aceg', 'gfedcba')
1 2 result = numbers[::2 ] result[::-1 ]
'97531'
'97531'
'97531'
컬렉션 데이터 타입 : list, tuple, dict
list [] : 순서가 있는 수정이 가능한 데이터 타입
tuple () : 순서가 있는 수정이 불가능한 데이터 타입
dict {}: 순서가 없고 키:값 으로 구성된 데이터 타입
1 2 3 ls = [1 ,2 ,3 ,"four" , [5 ,6 ], True , 1.2 ] type (ls), ls
(list, [1, 2, 3, 'four', [5, 6], True, 1.2])
1 2 ls[3 ], ls[1 :3 ], ls[::-1 ]
('four', [2, 3], [1.2, True, [5, 6], 'four', 3, 2, 1])
[1, 5, 2, 4, 3]
[5, 4, 3, 2, 1]
1 2 3 4 num = ls.pop() num, ls
(3, [1, 2])
1 2 3 ls1 = [1 , 2 , 3 ] ls2 = ls1 ls1, ls2
([1, 2, 3], [1, 2, 3])
([1, 2, 5], [1, 2, 5])
1 2 ls3 = ls1.copy() ls1, ls3
([1, 2, 5], [1, 2, 5])
([1, 2, 10], [1, 2, 5])
Tuple
리스트와 같지만 수정이 불가능한 데이터 타입
튜플은 리스트보다 같은 데이터를 가졌을때 공간을 적게 사용
1 2 3 tp1 = 1 , 2 , 3 tp2 = (4 , 5 , 6 ) type (tp1), type (tp2), tp1, tp2
(tuple, tuple, (1, 2, 3), (4, 5, 6))
(1, 2)
(2, (3, 2, 1))
1 2 3 4 5 6 7 import sysls = [1 , 2 , 3 ] tp = (1 , 2 , 3 ) print(sys.getsizeof(ls), sys.getsizeof(tp))
80 64
dict {}
순서가 없고 {키:값}으로 구성된 데이터 타입
1 2 3 4 5 6 7 8 dic = { 1 : "one" , "two" : 2 , "three" : [1 , 2 , 3 ], } type (dic), dic
(dict, {1: 'one', 'two': 2, 'three': [1, 2, 3]})
('one', [1, 2, 3])
{1: 'one', 'two': 123, 'three': [1, 2, 3]}
1 2 3 city = ["seoul" , "busan" , "daegu" ] population = [9700000 , 3400000 , 2400000 ]
1 2 3 4 5 6 data = { "seoul" : 9700000 , "busan" : 3400000 , "daegu" : 2400000 , }
15500000
15500000
5. 형변환
데이터 타입을 변환하는 방법
int, float, bool, str, list, tuple, dict
1 2 3 a = 1 b = "2" a + int (b)
3
'12'
[9700000, 3400000, 2400000]
(['seoul', 'busan', 'daegu'], [9700000, 3400000, 2400000])
1 2 list (zip (city, population))
[('seoul', 9700000), ('busan', 3400000), ('daegu', 2400000)]
1 result = dict (zip (city, population))
1 2 3 data1 = list (result.keys()) data2 = list (result.values()) data1, data2
(['seoul', 'busan', 'daegu'], [9700000, 3400000, 2400000])
1 2 string = "python" int (string)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-113-3eb1982ee741> in <module>
1 string = "python"
----> 2 int(string)
ValueError: invalid literal for int() with base 10: 'python'
6. 연산자
산술연산자 : +, -, *, /, //, %, **
할당연산자 : 변수에 누적시켜서 연산 : +=, //=, **=
비교연산자 : <, >, ==, !=, <=, >= : 결과로 True, False
멤버연산자 : 특정 데이터가 있는지 확인할때 사용 : not in, in
논리연산자 : True, False를 연산 : or, and, not
2.0
30
1 2 3 4 b=2 print(a, b) a < b, a == b, a !=b
30 2
(False, False, True)
1 2 True and False , True or False , not True or False
(False, True, False)
1 2 ls = ['jin' , 'andy' , 'john' ]
1 'andy' in ls, 'anchel' in ls
(True, False)
1 2 3 4 import randomrandom.randint(1 , 10 )
10
1 2 3 data = input ("insert string: " ) data
insert string: 안녕하세요
'안녕하세요'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 solutions = [ "무엇을 하든 잘 안될것이다." , "생각지도 않게 좋은 일이 생길것이다." , "무엇을 상상하든 그 이상이다." ] input ("질문을 입력하세요.: " )idx = random.randint(0 , len (solutions) - 1 ) solutions[idx]
질문을 입력하세요.: d
'무엇을 하든 잘 안될것이다.'