반응형

주석

'''
여러 줄
주석
'''
print("Hello World") # 한 줄 주석

표준 입출력

name = input("이름을 입력해주세요. >> ")

print('안녕하세요.', name)

print('Hello ', end='')  # 개행 제거
print('World')

연산자

a = 10
b = 5
c = 2.0
d = 0.5
e = '5'

print(type(b))  # <class 'int'>
print(type(c))  # <class 'float'>
print(type(e))  # <class 'str'>

print(a / b)  # 2.0
print(a // b)  # 2
print(a % b)  # 0
print(a ** b)  # 100000

print(a > 0 and b < 10)  # True
print(a < 0 or b > 10)  # False
print(not a > 20)  # True

print(e + e)  # 55
print(e * 5)  # 55555

타입 변환

print(str(10))  # 10
print(int('10'))  # 10
print(int(12.5))  # 12
print(list('hello'))  # ['h', 'e', 'l', 'l', 'o']

숫자

print(round(3.66))  # 4
print(round(3.66, 1))  # 3.7

print(abs(3))  # 3
print(abs(-3))  # 3

print(pow(3, 2))  # 9
print(3 ** 2)  # 9

x, y = divmod(7, 2)
print(x, y)  # 3 1

print(max([2, 3, 4]))  # 4
print(max(2, 3, 4))  # 4
print(min(2, 3, 4))  # 2

print(sum([2, 3, 4]))  # 9

String

text = input("input yyyy.MM.dd >> ")
y, m, d = text.split(".")

print(text, y, m, d)  # 2020.09.01 2020 09 01
print('{} + {} = {}'.format(1, 2, 3))  # 1 + 2 = 3
text = 'abcdefgh'

print(text[0])  # a
print(text[-1])  # h

print(text[0:2])  # ab
print(text[-5:-1])  # defg

print(text[5:])  # fgh
print(text[:5])  # abcde
print(text[:])  # abcdefgh

print(text[0:6:2])  # ace
print(text[8:0:-1])  # hgfedcb
print(text[::-1])  # hgfedcba
print('/'.join('abcde'))  # a/b/c/d/e

print('aaabbc'.count('b'))  # 2

print('a' in 'aaabbcc') # True

print('  abcde  '.strip())  # 'abcde'
print('  abcde  '.lstrip())  # 'abcde  '
print('  abcde  '.rstrip())  # '  abcde'

print('**abc*de**'.strip('*'))  # 'abc*de'
print('**abc*de**'.lstrip('*'))  # 'abc*de**'
print('**abc*de**'.rstrip('*'))  # '**abc*de'

print('ABC ABC'.find('A'))  # 0
print('ABC ABC'.rfind('A'))  # 4
print('ABC ABC'.index('A'))  # 0
print('ABC ABC'.rindex('A'))  # 4

print('ABC ABC'.find('a'))  # -1
print('ABC ABC'.rfind('a'))  # -1
print('ABC ABC'.index('a'))  # Error
print('ABC ABC'.rindex('a'))  # Error

print('AAbbCCdd'.isalpha())  # True
print('12345'.isdigit())  # True
print('AAbb1234'.isalnum())  # True
print('AABBCC'.isupper())  # True
print('aabbcc'.islower())  # True

print('AAbbCCdd'.upper())  # AABBCCDD
print('AAbbCCdd'.lower())  # aabbccdd

print('2020'.zfill(4)) # 2020
print('9'.zfill(2)) # 09
print('1'.zfill(2)) # 01

List

# li = list(['a', 'b', 'c'])
li = ['a', 'b', 'c']

print(li[0])  # a
a, b, c = [1, 2, 3]

print(a, b, c)  # 1 2 3
a, b, c = map(int, ['1', '2', '3'])

print(a + b + c)  # 6
li = ['a', 'b', 'c']

print(li.index('c'))  # 2

li.append('d')
print(li)  # ['a', 'b', 'c', 'd']

li.insert(0, 'aa')
print(li)  # ['aa', 'a', 'b', 'c', 'd']

li.remove('aa')
print(li)  # ['a', 'b', 'c', 'd']

del li[2]
print(li)  # ['a', 'b', 'd']

print('b' in li)  # True

print(len(li))  # 3

print(li.count('a'))  # 1
num = [1, 5, 2, 7, 3]

print(sum(num))  # 18
print(min(num))  # 1
print(max(num))  # 7

num.reverse()
print(num)  # [3, 7, 2, 5, 1]

num.sort()
print(num)  # [1, 2, 3, 5, 7]

num.sort(reverse=True)
print(num)  # [7, 5, 3, 2, 1]

List Comprehension

print([i for i in range(10)])  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print([i for i in range(10) if i % 2 == 0])  # [0, 2, 4, 6, 8]
print([i + j for i in ['A', 'B'] for j in ['B', 'C'] if not (i == j)])  # ['AB', 'AC', 'BC']

words = 'Hello World'.split()
print([[w.upper(), w.lower(), len(w)] for w in words])  # [['HELLO', 'hello', 5], ['WORLD', 'world', 5]]

print({i: v for i, v in enumerate('Hello World'.split())})  # {0: 'Hello', 1: 'World'}

Tuple

  • 변경 불가능한 리스트
# tu = tuple('a', 'b', 'c')
tu = ('a', 'b', 'c')

print(tu[0])  # a
a, b, c = (1, 2, 3)

print(a, b, c)  # 1 2 3
a = 'hello'
b = 'world'
(a, b) = (b, a)

print(a, b)  # world hello
print(tuple(['a', 'b', 'c']))  # ('a', 'b', 'c')
print(list(('a', 'b', 'c')))  # ['a', 'b', 'c']

Set

print(set({2, 4, 2, 1, 2, 3}))  # {1, 2, 3, 4}
print({2, 4, 2, 1, 2, 3})  # {1, 2, 3, 4}
a = {2, 4, 2, 1, 2, 3}

a.add(5)
print(a)  # {1, 2, 3, 4, 5}

a.remove(5)
print(a)  # {1, 2, 3, 4}

print(1 in a)  # True
print(len(a))  # 4
print(sum(a))  # 10
print(min(a))  # 1
print(max(a))  # 4

print(list(a))  # [1, 2, 3, 4]
print(tuple(a))  # (1, 2, 3, 4)
a = {1, 2, 3}
b = {2, 3, 4}

print(a & b)  # {2, 3}
print(a | b)  # {1, 2, 3, 4}
print(a - b)  # {1}
print(a ^ b)  # {1, 4}

Dictionary

print(dict({'name': 'john'}))  # {'name': 'john'}
print({'name': 'john'})  # {'name': 'john'}
dic = {'kor': 80, 'eng': 90, 'mat': 77}

print(dic['kor'])  # 80

dic['eng'] = 0
print(dic)  # {'kor': 80, 'eng': 0, 'mat': 77}

del dic['eng']
print(dic)  # {'kor': 80, 'mat': 77}

print('kor' in dic)  # True
print(len(dic))  # 2

print(list(dic.keys()))  # ['kor', 'mat']
print(list(dic.values()))  # [80, 77]
print(list(dic.items()))  # [('kor', 80), ('mat', 77)]

print(tuple(dic))  # ('kor', 'eng', 'mat')
print(list(dic))  # ['kor', 'eng', 'mat']
print(set(dic))  # {'mat', 'eng', 'kor'}
print(dict([['a', 1], ['b', 2]]))  # {'a': 1, 'b': 2}

dic.clear()
print(dic)  # {}

조건문

text = input('알파벳 입력 >> ')

if text.isupper() :
    print('대문자')
elif text.islower() :
    print('소문자')
else :
    print('대/소문자 구분 불가능')
def func(a):
    return "a > 10" if a > 10 else "a <= 10"

print(func(15))  # a > 10

while

n = 1

while n <= 10:
    print(n)
    n = n + 1

for

print(list(range(5)))  # [0, 1, 2, 3, 4]
print(list(range(1, 11)))  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(range(3, 10, 3)))  # [3, 6, 9]
print(list(range(5, 0, -1)))  # [5, 4, 3, 2, 1]

for i in range(10):  # 0123456789
    print(i, end='')

for i in range(5):  # 0124
    if i == 3:
        continue
    print(i, end='')

for i in range(5):  # 012
    if i == 3:
        break
    print(i, end='')

for i in range(5):  # 0124
    if i == 3:
        pass
    else:
        print(i, end='')

함수

def add(a, b):
    return a + b

print(add(1, 2))  # 3
def add(x, y):
    return x, y, x + y

a, b, result = add(1, 2)
print(a, b, result)  # 1 2 3
def f():
    s = "I love London!"
    print(s)  # I love London!

s = "I love Paris!"
f()
print(s)  # I love Paris!
def f():
    global s
    s = "I love London!"
    print(s)  # I love London!

s = "I love Paris!"
f()
print(s)  # I love London!

Enumerate & Zip

for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)
alist = ['a1', 'a1']
blist = ['b1', 'b2']

for a, b  in zip(alist, blist):
    print(a, b)

a, b, c = zip((1, 2, 3), (10, 20, 30))
print(a, b, c)  # (1, 10) (2, 20) (3, 30)

print([sum(x) for x in zip((1, 2, 3), (10, 20, 30))])  # [11, 22, 33]
alist = ['a1', 'a1']
blist = ['b1', 'b2']

print([{i: (a, b)} for i, (a, b) in enumerate(zip(alist, blist))])  # [{0: ('a1', 'b1')}, {1: ('a1', 'b2')}]

내장 모듈 사용하기

import math
import random

print(math.ceil(2.1))  # 3
print(math.floor(2.1))  # 2
print(math.factorial(5))  # 120
print(math.sqrt(4))  # 2
print(math.pi)  # 3.141592653589793

print(random.random())  # 0 ~ 1 사이 랜덤값
print(random.randint(1, 5))  # 1 ~ 5 사이 랜덤값

li = ['a', 'b', 'c']
print(random.choice(li))  # 랜덤으로 하나 뽑기
print(random.sample(li, 3))  # 랜덤으로 3개 뽑기

random.shuffle(li)
print(li)  # 랜덤으로 순서 섞기

개발한 모듈 사용하기

  • ~/calculator.py
def add(a, b):
    return a + b
  • ~/test.py
import calculator

print(calculator.add(1, 2))  # 3
import calculator as calc

print(calc.add(1, 2))  # 3
# from calculator import *
from calculator import add

print(add(1, 2))  # 3

Package

  • ~/calcualtor/add.py
def add(a, b):
    return a + b
  • ~/calculator/multiple.py
def multiple(a, b):
    return a * b
  • ~/main.py
from calculator.add import add
from calculator.multiple import multiple

print(add(2, 3))
print(multiple(2, 3))
  • 실행
# __main__.py가 있는 위치에서 아래 명령 실행
python .

클래스

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "name: %s, age: %d" % (self.name, self.age)

    def get_name(self):
        return self.name

john = Student("john", 25)
print(john)  # name: john, age: 25
print(john.get_name())  # john

클래스 상속

class Person:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def __str__(self):
        return "name: {}, age: {}".format(self.__name, self.__age)

    def get_name(self):
        return self.__name

class Student(Person):
    pass

class User(Person):
    def __init__(self, name, age, email):
        super().__init__(name, age)
        self.__email = email

    @property
    def email(self):
        return self.__email

john = Student("john", 25)
print(john)  # name: john, age: 25
print(john.get_name())  # john

tom = User("tom", 29, "tom@example.com")
print(tom)  # name: tom, age: 29
print(tom.email)  # tom@example.com

Exception

try:
    10 // 0
except ZeroDivisionError as e:
    print('error')
else:
    print('not error')
finally:
    print('finally')
a = 'ABCD'

if not a.isnumeric():
    raise ValueError('a is not number')

File Read

f = open('example.py', 'r')
print(f.read())
f.close()
with open('example.py', 'r') as f:
    print(f.read())
with open('example.py', 'r') as f:
    for i in range(3):
        line = f.readline().rstrip()

        print(line)

File Write

import os

if not os.path.isdir("log"):
    os.mkdir("log")

if not os.path.exists("log/test.log"):
    with open("log/test.log", "w", encoding="UTF8") as file:
        file.write("로그 파일 작성\n")

with open("log/test.log", "a", encoding="UTF8") as file:
    file.write("로그 추가\n")
    file.write("로그 추가\n")
    file.write("로그 추가\n")

CSV Read

  • ~/data.csv
name,age,message
john,27,"Hello World"
tom,25,"Bye World"
  • ~/example.py
import csv

with open("data.csv", "r", encoding="UTF8") as file:
    for i, row in enumerate(csv.reader(file)):
        if i == 0:
            print("header : {}".format(row))
        else:
            print("name: {}, age: {}, message: {}".format(row[0], row[1], row[2]))
  • 실행 결과
header : ['name', 'message', 'age']
name: john, age: Hello World, message: 27
name: tom, age: Bye World, message: 25

CSV Write

  • ~/example.py
import csv

with open("data.csv", "w", encoding="UTF8") as file:
    writer = csv.writer(file, delimiter="\t", quotechar="'", quoting=csv.QUOTE_ALL, lineterminator="\n")
    writer.writerow(['name', 'message'])
    writer.writerow(['john', 'Hello World'])
    writer.writerow(['tom', 'Bye World'])
  • ~/data.csv
'name'	'message'
'john'	'Hello World'
'tom'	'Bye World'

HTTP request

import urllib.request

url = "https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-7.9.1-linux-x86_64.tar.gz"

file_name, header = urllib.request.urlretrieve(url, "filebeat.tar.gz")

print(file_name)
import urllib.request

url = "https://www.starbucks.co.kr/menu/drink_list.do"

html = urllib.request.urlopen(url)
html_contents = str(html.read().decode("UTF8"))

print(html_contents)

Regex

import re

text = "2020-09-18 Hello World"
result = re.findall(r"([0-9]{4}-[0-9]{2}-[0-9]{2})", text)

print(result)  # ['2020-09-18']

HTML Parsing

from bs4 import BeautifulSoup

html = '''
<ul>
    <li>AAA</li>
    <li>BBB</li>
    <li>CCC</li>
</ul>
'''

soup = BeautifulSoup(html, 'html.parser')

for tag in soup.select("li"):
    print(tag.text)

JSON Parsing

import json

contents = '''
{
  "name": "john",
  "age": 25
}
'''

data = json.loads(contents)

print(data["name"])

Date

import datetime

print(datetime.datetime.now())
print(datetime.datetime(2019, 1, 1))  # 2019-01-01 00:00:00
print(datetime.datetime(2019, 1, 1, 23, 59, 59))  # 2019-01-01 23:59:59

print(datetime.datetime.strptime("2020-12-31", "%Y-%m-%d"))  # 2020-12-31 00:00:00
print(datetime.datetime(2019, 1, 1).strftime("%Y.%m.%d %H.%M.%S"))  # 2019.01.01 00.00.00

print(datetime.datetime(2010, 1, 1, 23, 59, 59).replace(day=31))  # 2010-01-31 23:59:59

print(datetime.datetime(2010, 1, 1, 23, 59, 59).timetuple().tm_year)  # 2010

date = datetime.date(2010, 1, 1)
time = datetime.time(23, 59, 59)
print(datetime.datetime.combine(date, time))  # 2010-01-01 23:59:59

start = datetime.datetime(2010, 1, 1, 23, 59, 59)
finish = datetime.datetime(2010, 1, 8, 23, 59, 59)
diff = finish - start
print(diff.days)  # 7

lambda

from functools import reduce

items = [1, 2, 3]

print(list(map(lambda x: x * 2, items)))  # [2, 4, 6]
print(list(filter(lambda x: x >= 2, items)))  # [2, 3]
print(reduce(lambda acc, cur: acc + cur, items, 0))

add = lambda a, b: a + b
print(add(1, 2))  # 3
반응형

'Development > Python' 카테고리의 다른 글

[Python] tensorflow 시작하기  (0) 2024.01.30
[Python] 설치  (0) 2021.05.16
[Python] MySQL  (0) 2020.12.30
[Python] locust  (0) 2020.12.30
[Python] 가상환경  (0) 2020.12.30

+ Recent posts