Semiconductor, Embedded/3. C, C#, Python

Python - 기본 문법 복습 (Function, Class, Thread 등...)

잇(IT) 2024. 8. 19. 16:26

- Print(), Input()

- List

- Tuple, Set, Dictionary

- Loop

- Try / Except

- Function

- Class

- 상속

- QR Codes

- Thread Programming

- Macro


- Print(), Input()

# print

print("Hello")

# input

a = input("Input 1st Value = ")
b = input("Input 2st Value = ")
print(a+b)

- List

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

b_list = []
b_list.append(1)
print(b_list)

c_list = [1, 3.14, 'hello', [1,2,3]]
print(c_list)

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

- Tuple, Set, Dictionary

 

Tuple

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

 

a_tuple[0] = 5

tuple의 경우 불변값이기 때문에 위 처럼 값을 변경하게 될 경우 에러가 발생한다.

 

Set

a_set = {1,2,3,4,5}
b_set = {1,1,2,3,4,5}
print(a_set)
print(b_set)

set은 중복을 제거해준다.

 

Dictionary

a_dic = {'a' : 1, 'b' : 2, 'c' : 3}
print(a_dic)
print(a_dic['a'])
a_dic['d'] = 4
print(a_dic)

- Loop

 

For

word_list = ['baek','in','soo']
num_list = [100, 200, 300]

for i in range(len(word_list)) :
	print(word_list[i], end = ' ')
    print(num_list[i])
    
test_list = [i for i in range(5)]
print(test_list)

test2_list = []
for i in range(len(test_list)) :
	test2_list.append(i)
    print(test2_list)
    
test_list = [i*5 for i in range(5)]
	print(test_list)
    
test2_list = [0 for i in range(5)]
	print(test2_list)

 

 

Range

word_list = ['baek','in','soo']
num_list = [100, 200, 300]

for i in range(len(word_list)) :
	print(word_list[i], end = ' ')
    print(num_list[i])
    
test_list = [i for i in range(5)]
print(test_list)

test2_list = []
for i in range(len(test_list)) :
	test2_list.append(i)
    print(test2_list)
    
test_list = [i*5 for i in range(5)]
	print(test_list)
    
test2_list = [0 for i in range(5)]
	print(test2_list)

 

 

While

a = 0
while a < 5 :
	print(a)
    a = a + 1
a = 0
while True :
	print(a)
    a = a + 1
    if a >= 5 :
    	break

- Try / Except

 

try :
	qwerasdfzxcv
except :
	print("Error!!")
try :
	qwerasdfzxcv
except :
	pass
   	print("Skip Error")
try :
	qwerasdfzxcv
except Exception as e :
	print("Error : ', e)

- Function

 

- 기본 구조

def func() :
    print("This is func print.")
    
func()

기본적인 함수 구조

 

- 반환 값 2개

def func_add_mul(a,b) :
    add = a + b
    mul = a * b
    return add, mul

c, d = func_add_mul(2,4)
print(c,d)

Python에서는 return 값으로 2개를 반환할 수 있다.

 

def func_add_mul(a,b) :
    add = a + b
    mul = a * b
    return add, mul

_, d = func_add_mul(2,4)
print(d)

return 값이 2개지만 하나만 반환하고 싶을 때는 위와 같이 _ 기호를 사용하여 비워둔다.


- Class

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

    def stu_info(self) :
        print(f'{self.name}/{self.age}/{self.like}')

A = student("kim", 22, 'Game')
A.stu_info()

 

__init__는 생성자를 의미한다. 클래스의 인스턴스가 생성될 때 자동으로 호출되어 인스턴스를 초기화하는 역할을 한다.

A = student("kim", 22, 'Game')을 호출하게 되면 __init__(self, name, age, like) 함수가 호출된다.

self가 붙게되면 클래스 인스턴스의 속성이 된다. 즉, 해당 클래스의 변수에 해당한다. (self.name은 클래스 내부에서 사용되는 name이고 그냥 name은 외부에서 전달된 값이 저장되는 변수다.

A = student("kim", 22, 'Game')이 호출되면 name, age, like로 값이 전달되고, self.name, self.age, self.like에 저장되고, self가 붙은 변수들은 클래스 내부에서 자유롭게 사용이 가능하다.


- 상속

class mom() :
    def characteristic(self) :
        print("Tall")
        print("Smart")
class daughter(mom) :
    def characteristic(self):
        super().characteristic() 
        print("Strong")

M = mom()
D = daughter()
print("[Mother]")
M.characteristic()
print("[Daughter]")
D.characteristic()

 

super을 통해 부모 클래스의 메서드를 사용할 수 있다.

 

class mom() :
    def __init__(self) :
        print("Tall")
        print("Smart")
class daughter(mom) :
    def __init__(self) :
        super().__init__()
        print("Strong")
        
print("[Mother]")
M = mom()
print("[Daughter]")
D = daughter()

 


- QR Codes

pip install qrcode

 

import qrcode
import re

# QR 코드로 변환할 데이터
qr_data = 'https://insoobaik.tistory.com/'

# QR 코드 이미지 생성
qr_img = qrcode.make(qr_data)

# 파일 이름에서 사용할 수 없는 문자를 대체할 함수
def sanitize_filename(filename):
    # 파일 이름으로 사용할 수 없는 문자들을 대체하거나 제거
    return re.sub(r'[\\/*?:"<>|]', '_', filename)

# 파일 이름 생성
safe_qr_data = sanitize_filename(qr_data)
save_path = 'QR_Code_' + safe_qr_data + '.png'

# QR 코드 이미지 저장
qr_img.save(save_path)

print(f"QR 코드가 '{save_path}'에 저장되었습니다.")

현재 블로그로 이동하는 qr 코드 생성


- Thread Programming

동시에 여러가지 작업이 가능하도록 하는 것 코어가 많을 수록 Thread를 생성해서 작업을 분업할 수 있다.

import threading
import time

def thread_1() :
    while True :
        print("Thread 1 is working")
        time.sleep(0.7)

t1 = threading.Thread(target=thread_1)
t1.daemon = True
t1.start()

while True :
    print("Main Loop")
    time.sleep(1)

별도로 동작하는 것을 확인할 수 있다.


- Macro

pip install pyautogui
pip install pyperclip

 

그림판 그림 그리기

import pyautogui

pos = [375,400]
len = 200

pyautogui.click(pos[0], pos[1])
for y in range(20):
    if y%2==0 : pos[1] = pos[1]+len
    else : pos[1] = pos[1]-len
    pyautogui.dragTo(pos[0], pos[1], 0.1)
    
    if y%2==0 : pos[0] = pos[0]+len
    else : pos[0] = pos[0]-len
    pyautogui.dragTo(pos[0], pos[1], 0.1)

    len = len-10
728x90