작은 메모장

3. 인프라 활용을 위한 파이썬 본문

실더스 루키즈 교육

3. 인프라 활용을 위한 파이썬

으앙내눈 2023. 11. 23. 17:23

파이썬이 보안에서 쓰는 곳?
-
일단 많이 사용함
-
자동화 업무에서 압도적 -> 특히 모의해킹 오픈 도구 80% 이상
-
보안 솔루션, 보안 스크립트 자동화 -> 보고서 작성 자동화
-
모든 운영체제에서 호환성이 뛰어남
-
웹 서비스 – PHP, ASP, NET, JSP/JAVA… -> React, Vue, Flask, Django

API?
사용자들이 원하는 데이터를 인증을 통해 제공하는 일련의 통로
쉽게 말해 창구 업무 종사자와 이야기를 한다고 생각하면 편함
어떤 데이터를 원하는가?
어떤 인증이 필요한가? (인증키, 개인정보 등)
얼마나 필요한가?
등등을 정해진 함수를 통해 제공하면, 데이터를 전송해 줌

 

<사용 라이브러리>

환경은 vsc 기준으로 설명
extensions > black formatter ~> set default formatter
pip install googletrans==3.1.0a0

 

print("hello world!")
print("hello" + "world!")
print("hello", "world!")
print("hello\n" + "world!\n")
print(
    """ 굉장히 긴 문자열입니다.........
      파이썬 화이팅
      파이썬자동화
      """
)

코드 조작법 습득

 

a = "python"
b = 15

print(a)
print(b)

print(type(a))
print(type(b))

# general output
print("I like learning", a, ", already studied", b, "times")

# formating output
print("I like learning {}, already studied {} times".format(a, b))

# fstring output
print(f"I like learning {a}, already studied {b} times")

### Refresh ###
all = [var for var in globals() if var[0] != "_"]
for var in all:
    del globals()[var]

name = input("Put here your name :")
phone = input("Put here your phone number :")
age = int(input("Put here your age :"))

# general output
print(name + "'s phone number is " + phone + ", and age is " + str(age))

# formating output
print("{}'s phone number is {}, and age is {}".format(name, phone, age))

# fstring output
print(f"{name}'s phone number is {phone}, and age is {age}")

기초적인 Input Output 연습

 

from googletrans import Translator

translator = Translator()

print(">> This is a tiny translator to eng <<")

target_text = input("@ Write sentence if you want to translate : ")
translated = translator.translate(target_text, dest="en").text

""" Output """
print("\n")
print(f"# Your input: {target_text}")
print(f"# Result : {translated}")

API 호출법 연습

 

names = ["person1", "person2", "person3", "person4", "person5"]

for i in range(len(names)):
    print(f"Place {i + 1} is {names[i]}")


### Refresh ###
all = [var for var in globals() if var[0] != "_"]
for var in all:
    del globals()[var]


scores = [10.0, 9.0, 9.5, 7.1, 5, 8.0]

print(f"# Scores before delete : {scores}")
print(f"# Scores before after delete : {sum(scores)/len(scores)}")

# Remove Trial
scores.remove(max(scores))
scores.remove(min(scores))

print(f"# Scores after delete : {scores}")
print(f"# Scores average after delete : {sum(scores)/len(scores)}")


### Refresh ###
all = [var for var in globals() if var[0] != "_"]
for var in all:
    del globals()[var]
    
    
# Program for saving scores
# Condition : 5 students scores will be input
#             Count student if score over 80
#             print Average, Highiest, Lowiest, Sum

STUDENTS = 5
scores = []
count = 0

for i in range(STUDENTS):
    value = int(input(f"Input score {i+1} student : "))
    scores.append(value)

    # Condition check
    if value >= 80:
        count = count + 1

print(f"# Sum value : {sum(scores)}")
print(f"# Max value : {max(scores)}")
print(f"# Min value : {min(scores)}")
print(f"# Avg value : {sum(scores)/len(scores)}")
print(f"# Student num that scores over 80 : {count}")

리스트 접근 및 수정/제어 연습

 

# Program for ordering coffee
"""
Condition
- Price : fixed
- Order items : bring price
- Accept multiple choice
- Calculate change
"""
import os

menus = {"coffee": 5000, "lattee": 6000, "piece of cake": 4500, "cake": 9000}
order_list = {}

# Get Budget
os.system("cls")
money = int(input("Insert Money : "))
os.system("cls")

# Ordering
while True:
    # Show Menu
    print(f"Your Budget : {money}")
    print(f"======Menu List======")
    for name, price in menus.items():
        print(f"{name}: {price}")

    try:
        selected_menu = input(
            "!If you want to finish, enter N!\n# Select item you want : "
        )
        if selected_menu == "N":
            break

        price = menus.get(selected_menu)
        if price == None:
            os.system("cls")
            print("Find error. Select correct item")
            continue

        money = money - price
        if money >= 0:  # Budget enough
            # init
            if selected_menu not in order_list:
                order_list[selected_menu] = 0

            order_list[selected_menu] = order_list[selected_menu] + 1
            os.system("cls")
            print(f"Bring {selected_menu}, price is {price}")

        else:  # Budget out
            money = money + price
            os.system("cls")
            print("Not enough Money. Canceled Order")

    except:
        os.system("cls")
        print("Something Worng...")

# Output
os.system("cls")
print("# You bough this items")
for item in order_list:
    print(
        f"$ {item}, amount {order_list[item]}. Price: {menus[item] * order_list[item]}"
    )
print(f"# You returned '{money}'.")

딕셔너리 수정 및 편집 연습

 

import os

os.system("cls")
txt_files = []

# If you want, path here
dir_path = os.getcwd()

all_files = os.listdir(dir_path)

print(all_files)
for file in all_files:
    print(file)
    if file.endswith(".txt"):
        txt_files.append(file)

print(f"TXT Files : {txt_files}")

for filename in txt_files:
    file_path = os.path.join(dir_path, filename)
    with open(file_path, "r", encoding="utf-8") as f:
        print(f"Infomation of {filename} : {f.read()}")

파일 입출력 연습