Python_기본

Updated:

  • \n 줄바꿈
  • \t 탭
  • \ 문자\
  • ' 작은따움표
  • " 큰따움표

시퀀스

원소간의 순서가 존재
  • 문자열, 리스트, 튜플

문자열

문자열 연산하기


str1 = 'First string'
space_bar = " "
str2 = 'Second string'
print(str1 + space_bar + str2)

str_3 = 'Python'
print(str_3*3)

# 문자열 인덱싱과 슬라이싱


str = 'Life is short, You need Python'
print(str[0])  # 'L'
print(str[3])  # 'e'
print(str[-1]) # 'n'

문자열의 일부분 가져오기

  • : 콜론을 활용하면 범위 선정 가능 빈칸은 시작과 끝을 의미

str = 'Life is short, You need Python'
print(str[0:4])  # 'Life'
print(str[:4])   # 'Life'
print(str[15:])  # 'You need Python'

문자열 관련 함수

  • 사용자가 원하는 기능을 지정하고 입력값에 따라 함수를 실행하여 결과값을 보여주는것
str = 'Life is short, You need Python'
len(str) # 30
str.count('e') # 3
str.upper() # LIFE IS SHORT, YOU NEED PYTHON
str.lower() # life is short, you need python

x = 'python'
x.find('o') # 4
x.find('w') # -1
x.index('o') # 4
x.index('w') # error
  • split
    • 문자열을 쪼개서 리스트 반환
    • 괄호를 비울시
# 문자열 나누기

x.split(a) 문자열을 a로 토막냄

x = 'Life is short, You need Python'
x.split(' ')
# ['Life','is','short,','You','need','Python']

numbers = "   1  2  3   "
print(numbers.split())
# ['1','2','3']

print(numbers.split(' ')
# ['','','1','','2','','3','','']

# 그냥 split() 을 할 경우 ' ', '\t', '\n'를 모두 제거한다 

# 문자열 나누고 다시 합치기
y = x.split(' ')
print(y)
a = ' '
a.join(y)

x.lstrip() 왼쪽 공백 지우기
x.rstrip() 오른쪽 공백 지우기
x.strip() 양쪽 공백 지우기
x.replace(str1, str2) 문자열 바꾸기(str1->str2)
# x.replace(str1, str2)는 새로운 값에 저장해주어야 한다

x.count(str) 문자(문자열) 개수 세기
x.find(str) 위치 알려주기. (-1)
x.index(str) 위치 알려주기. (오류)
a.join(str_list) a 삽입 문자열 연결.

x.upper() 대문자로 변환.
x.lower() 소문자로 변환.
# x.upper()과 x.lower은 새로운 값에 저장해주어야 한다

len(x) 문자열의 길이
  
x.startswith(a) a로 시작하면 True, a가 문장일때도 사용 가능
# # 또는 @와 같은 해시태그를 찾을때 좋다


리스트

a = []
b = [1,2,3]
c = ['Life', 'is', 'too', 'short']
d = [1,2,'life', 'is']
e = [1,2,['life', 'is']] ```python a = [1,2,3] b = [4,5,6] a + b  ```

리스트의 일부 변경

a = [1,2,3]

a[1:3]
a[1:3] = [3,5,7,9,11]
print(a) #[1,3,5,7,9,11]
a = [1, 2, 3]
a[1:2] = [-1, -2, -3]
print(a) # [1, -1, -2, -3, 3]

a = [1, 2, 3]
a[1] = [-1, -2, -3]
print(a) # [1, [-1, -2, -3], 3]
# 위와 아래의 차이점

리스트 추가

a = [1, 2, 3, 4]
a.append(5) # [1, 2, 3, 4, 5]
a.insert(3,1) # [1, 2, 3, 1, 4, 5] 
# 3번 인덱스에 1을 추가한다.

리스트 삭제

a = [1, 2, 3, 4, 5]
a[1:3] = []
print(a) # [1, 4, 5]

a = [1, 2, 3, 4, 5]
del a[2]
print(a) # [1, 2, 4, 5]
  • pop
    • 인덱스 i의 원소를 제거 후 그 원소를 반환
    • (괄호를 비울 시 마지막 원소)
my_list = [1,2,3,4,5]
print(my_list.pop(0) # 1
print(my_list.pop() # 5

## 리스트 관련 함수

리스트 정렬

a = [3,1,5,2,4]
a.sort()
print(a) # [1,2,3,4,5]

a.sort(reverse = Treu) # == a.reverse()

print(a) # [5,4,3,2,1]

# 항구적이지 않은 sort
a = [3,1,5,2,4]
print(sorted(a)) # [1,2,3,4,5]
print(a) # [3,1,5,2,4]
  • 절대값을 기준으로 정렬
numbers = [-1,3,-4,5,6,100]
sort_by_abs = sorted(numbers, key=abs)
print(sort_by_abs) [-1,3,-4,5,6,100]
  • 끝값을 기준으로 정렬
fruits = ['cherry', 'apple', 'banana']
sort_by_last = sorted(key = reverse)
print(sort_by_last) # ['banana', 'apple', 'cherry']
  • 직접 key값을 지정해서 정렬
pairs = [
    ('time', 8),
    ('the', 15),
    ('turbo', 1),
]
 
def get_freq(pair):
    return pair[1]

def sort_by_frequency(pairs):
    return sorted(pairs,key = get_freq)
    # get_freq를 key롤 지정해서 정렬한다
    
print(sort_by_frequency(pairs))
# [('turbo', 1), ('time', 8), ('the', 15)]

리스트 값의 개수

my_seq = [2,2,2,4,4]
print(my_seq.count(2)) # 3

리스트로 리스트 만들기

  • List complehension
words = ['life', 'love', 'faith']
first_letters = [word[0] for word in words]
print(first_letters) # ['l','l','f']
  • 조건을 포함
numbers = [1, 3, 4, 5, 6, 7]
even = [n for n in numbers if n % 2 == 0]
print(even) # 4, 6
  • join
    • str.join(list) 일때 str을 기준으로 리스트를 합쳐서 문자열을 반환
    • 괄호를 비울시 공백 ```python my_list = [‘a’, ‘p’, ‘p’, ‘l’, ‘e’] print(‘‘.join(my_list))

friend = [‘Pat’,’Mat’] print(‘&’.join(friend)) # Pat&Mat




# 튜플

* 값을 바꿀수 없다

```python
tuple_zero = ()
tuple_one = (1,) # 자료가 하나일때는 ,를 붙여준다
tuple_ = (1,2,3,4,5)
tuple_ = 1,2,3,4,5

a = () # 빈 튜플
b = (1,2,3)
c = ('life', 'is', 'too', 'shoet')
d = (1,2,'life','is')
e = (1,2,('life', 'is'))

print(e[1]) # 2
print(e[2][1]) # is

a = (1,2,3,4,5)
print(a[:2]) # (1, 2)

print(a[2:]) # (3, 4, 5)

a= (1,2,3,('a','b','c'),4,5)
print(a[2:5]) # (3, ('a', 'b', 'c'), 4)

a = (1,2,3)
b = (4,5,6)
print(a+b) # (1, 2, 3, 4, 5, 6)

a = (1,2,3)
print(a * 3) # (1, 2, 3, 1, 2, 3, 1, 2, 3)

# 튜플의  가장 강력한 기능 중 하나인 추가, 삭제, 변경 불가능
del a[1] # error 튜플은 삭제 불가능

딕셔너리

  • key는 변할 수 없는 자료형
    • 리스트는 안되고, 튜플은 된다!
  • key: 값을 찾기 위해 넣어 주는 데이터
  • value: 찾고자 하는 데이터
accounts = {"kdhong":"Kildong Hong",}
print("kdhong" in accounts) # True
print("elice" in accounts) # False
a = {}
b = {'이름':'이재화','성별':'남자','나이':' ? '}
c = {1:'life', 2:'is', 3:'short'}
d = {'x' : [1,2,3], 'y':[4,5,6]}
e = {1:b, 2:c}

print(b['성별']) # 남자

print(e[2]) # {1: 'life', 2: 'is', 3: 'short'}

print(e[2][3]) # 'short'
a = {}
a['이름'] = '홍길동' # 자료 추가하는 법
print(a) # {'이름': '홍길동'}
 
del a['이름'] #자료 삭제하는 법
print(a) # {}
a = {'이름':'김진우', '성별':'남', '나이':'?'}
print(a.keys()) # dict_keys(['이름', '성별', '나이'])
print(a.values()) # dict_values(['김진우', '남', '?'])
print(a.items()) # dict_items([('이름', '김진우'), ('성별', '남'), ('나이', '?')])
a.clear() 
print(a) # {}

* 딕셔너리 순회하기
```python 
accounts = {"kdhong":"Kildong Hong",}
for username, name in account.item():
  print(username + " - " + name)
a = {'name':'LEE', 'gender':'MALE', 'age':35}
print(a.get('name')) # 'LEE'
print(a.get('wage',-1)) # -1, wage가 있으면 wage를 출력하고 없으면 -1을 출력한다

z = {'name':'최우혁','gender':'???','age':'??'}
print('name' in z) # True
print('성적' in z) # False

집합

  • 중복이 없다
  • 순서가 없다
set1 = {1,2,3}
set2 = set([1,2,3]}
set3 = {3,2,3,1}
# 셋 모두 같은 값
lists = [1,1,2,3,3,4,5]
set1 = set(lists)
# [1,2,3,4,5]

tuples = (1,1,2,3,3,4,5)
set2 = set(tuples)
# [1,2,3,4,5]
a = set()
b = set([1,2,3,3,3,3,4,5])
print(b) # {1,2,3,4,5}
print(type(b)) # <class 'set'>


a = set([1,2,3,4,5])
a.add(7)
print(a) # {1, 2, 3, 4, 5, 7}

a.update([10,11,12])
print(a) # {1, 2, 3, 4, 5, 7, 10, 11, 12}

# remove는 집합안에 존재해야 제거한다(집합안에 없다면 오류)
a.remove(5)
print(a) # {1, 2, 3, 4, 7, 10, 11, 12}

# discard는 만약에 존재한다면 제거한다 
a.discard(13)
print(a) # {1, 2, 3, 4, 7, 10, 11, 12}

# 복사
copy_set = my_set.copy()
num_set = {1,3,5,7}
print(6 in num_set) # False
print(len(num_set)) # 4

```python
s1 = set([1,2,3,4,5])
s2 = set([4,5,6,7,8])

# 교집합
s1 & s2 
s1.intersection(s2) 
# {4,5}

# 합집합
s1 | s2 
s1.union(s2)
# {1,2,3,4,5,6,7,8}

# 차집합
s1 - s2 
s1.difference(s2)
# {1,2,3}

# XOR
# (A-B) U (B-A)
s1 ^ s2 
# {1,2,3,6,7,8}

변수


a = 'abcd'
b = 3
print(type(b)) # <class 'int'>

c = b
print(b is c) # True

a,b,c = (111,True,'aaa')
print(a) # 111 
print(b) # True
print(c) # aaa

a,b,c = [111, True, 'aaa']
print(a) # 111 
print(b) # True
print(c) # aaa

a = b = c = 777
print(a) # 777
print(b) # 777
print(c) # 777

x, y = 666, 777
print(x) # 666
print(y) # 777

x , y = y , x
print(x) # 777
print(y) # 666

boolean

  • 참과 거직 두가지 값을 나타내는 자료형
  • 조건문의 반환값으로 사용되기도 한다
print(1 == True)
print(0 == False)

얕은 복사

import copy as cp

a = [1,2,[3,4,5]]
b = cp.copy(a)

a[0] =  666
print(a) # [666,2,[3,4,5]]
print(b) # [1,2,[3,4,5]]

a = [1,2,[3,4,5]]
b = a[:]

a[0] = 0
print(a) # [0,2,[3,4,5]]
print(b) # [1,2,[3,4,5]]

a[2][0] = -999
print(a) # [1,2,[-999,4,5]]

깊은 복사

import copy as cp
a = [1,2,[3,4,5]]
print(a) # [1,2,[3,4,5]]
b = cp.deepcopy(a)

a[2][0] = 0
print(a) a = [0,2,[3,4,5]]

반복문

i = 0
while i < 4 : 
    print(i)
    i += 1

# 0, 1, 2, 3

X = ['you', 'need', 'python']
for x in X:
    print(x)

# you, need, python

sum = 0
for x in range(1,11):
    sum += x
print(sum)

# 55
  • enumerate는 index와 값을 함께 출력할 수 있다.
    for i, e in enumerate([5,3,7]):
    print(i, ":", e)
    #  0:5 ,1:3 ,2:7   
    

함수

  • 함수는 특정 기능을 하지만 메서드는 특정 자료와 연관 지어 기능을 한다.
import os
os.getcwd() # 'C:\\Users\\user\\Desktop\\인공지능사관\\빅데이터\\파이썬실습\\notebook'
os.chdir('..')
os.getcwd() # 'C:\\Users\\user\\Desktop\\인공지능사관\\빅데이터\\파이썬실습'
os.listdir() # ['data', 'notebook', '파이썬_sol']
# 함수
def prod(a, b):
    x = a*b
    return x
print(prod(3,4)) # 12

def output():
    return 'hello world'
print(output()) # hello world

def times3(a):
    print(3*a)
    return
print(times3(7)) # 21

클래스

class 클래스명:
  변수명 = 
  변수명 = 
  def 함수명(self, 전달값_변수명):
    코드1
    코드2

class Dog_1:
    def __init__(self, name, age):
        self.name = name
        self.age = age        
        print("A Dog object is created!")

    def __del__(self):
        print('A Dog object is deleted!')

dog = Dog_1('이재화', 2) # A Dog object is created!
print(dog.name) # 이재화
del dog # A Dog object is deleted!
class Dog_2:
    def __init__(self, name, age):
        self.name = name
        self.age = age

dog1 = Dog_2('이재화_1',2)
dog2 = Dog_2('이재화_2',3)

print(dog1.name) # 이재화_1
print(dog2.age) # 3


class Dog:
    counter = 0
    def __init__(self, name):
        self.name = name
        Dog.counter += 1

    def __del__(self):
        Dog.counter -= 1

dog1 = Dog('이재화_1')
dog2 = Dog('이재화_2')

print(Dog.counter) # 2

del dog1 

print(Dog.counter) # 1

class Email:
    sender = ""

    def send_mail(self, recv, subject, contents):
        print("from : \t" + self.sender)
        print("To : \t" + recv)
        print("subject:" + subject)
        print("contents" + contents)
        print("-" * 20)

e = Email()
e.sender = "01094537706@gmail.com"

recv_list = ['1@gmail.com','2@gmail.com','3@gmail.com']

for recv in recv_list:
    e.send_mail(recv,"비상연락망입니다.", "이 번호로 연락 부탁드립니다.")
'''
from :  01094537706@gmail.com
To :    1@gmail.com
subject:비상연락망입니다.    
--------------------
from :  01094537706@gmail.com
To :    2@gmail.com
subject:비상연락망입니다.    
--------------------
from :  01094537706@gmail.com
To :    3@gmail.com
subject:비상연락망입니다.    
--------------------
'''

상속

class Pet:
    def __init__(self, name):
        self.name = name

# Cat이 상위 class
class Cat(Pet):
    def meow(self):
        print(self.name + ' is meowing...')

class Dog(Pet):
    def bark(self):
        print(self.name + ' is barking')

cat1 = Cat('흰돼지')

cat1.meow() # 흰돼지 is meowing...

dog1 = Dog('쎄리')

dog1.bark() # 흰돼지 is barking...

예외처리

x = []
try:
    result = x.index(1234)
except ValueError as err:
    print(err)
else:
    print(result)
finally:
    print("끝")

try:
    int("abcd")
    print("try가 모두 실행되었습니다.")
except Exception as e :
    print("오류가 발생하였습니다.")
    print(e)
finally:
    print("finally가 실행되었습니다")
'''
오류가 발생하였습니다.
invalid literal for int() with base 10: 'abcd'
finally가 실행되었습니다
'''
try:
    int(1000)
    print("try가 모두 실행되었습니다.")
except Exception as e :
    print("오류가 발생하였습니다.")
    print(e)
finally:
    print("finally가 실행되었습니다")
'''
try가 모두 실행되었습니다.
finally가 실행되었습니다
'''

print

  • sep의 값을 사이에 채운다
    print(N, '*', i, '=', N * i, sep=' ')
    

모듈

import math

패키지(폴더)에서 불러올때

import use.my_module

모듈의 함수나 변수 불러올때

from use.my_module import plus
  • urlopen 사용해서 웹페이지 구성 가져오기
from urllib.request import urlopen
webpage = urlopen("https://en.wikipedia.org/wiki/Lorem_ipsum").read().decode("utf-8")
print(webpage)
  • import 와 from import의 차이점
from random import randrange
import math

var1 = randrange(1,11)
var2 = math.log(5184,72)

print(var1,var2)

Leave a comment