AI를 위한 파이썬 핵심문법

김경민·2022년 5월 24일
1

AI

목록 보기
4/11

Python

-> 1991년 Guido van Rossum 이 개발
-> Script Language
-> 컴파일 과정 없이 인터프리터에 의해 실행 결과를 바로 확인

https://www.python.org/downloads/

python keyword

  • 특별한 의미가 부여된 단어
  • 숫자로 시작 불가
  • False
  • break
  • else
  • if
  • not
  • while
  • None
  • class
  • except
  • import
  • or
  • with
  • True
  • continue
  • finally
  • in
  • pass
  • yield
  • and
  • def
  • for
  • is
  • raise
  • as
  • del
  • from
  • lambda
  • return
  • assert
  • elif
  • global
  • nonlocal
  • try

snake case: 언더바(_)를 기호 중간에 붙이기
camel case: 단어들의 첫 글자를 대문자로

python data type

  • string
  • number
  • boolean

#datatype1.py

print("안녕하세요")
print('안녕하세요')
print(100)
print(3.5)

print(type('안녕하세요'))
print(type(100))
print(type(3.5))

print(100>200)
print(100<200)
a=100<200
print(a)
print(type(a))

print("python" + ' program')
print(100+200)

print("홍길동 님, 안녕하세요")
print("'홍길동 님', 안녕하세요")
print('"홍길동 님", 안녕하세요')
print("\"홍길동 님\", 안녕하세요")
print()
print ("동해 물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세 무궁화 삼천리 화려 강산대한 사람 , 대한으로 길이 보전하세.")
print ("동해 물과 백두산이 마르고 닳도록 n 하느님이 보우하사 우리나라 만세 n 무궁화 삼천리 화려 강산대한 사람 ,\n 대한으로 길이 보전하세.")
print ("""동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세 무궁화 삼천리 화려 강산대한 사람 , 대한으로 길이 보전하세.""")

#data_index.py

print("문자열 인덱싱")
print("안녕하세요")
print("안녕하세요"[0])
print("안녕하세요"[1])
print("안녕하세요"[2])
print("안녕하세요"[3])
print()
print("안녕하세요"[-1])
print("안녕하세요"[-2])
print("안녕하세요"[-3])
print("안녕하세요"[-4])
print("안녕하세요"[-5])
print()

print("문자열 슬라이싱")
print("안녕하세요"[0:3]) #마지막 숫자는 포함되지 않음
print("안녕하세요"[1:4])
print("안녕하세요"[2:])
print("안녕하세요"[:4])
print("안녕하세요"[::-1])

print(len("안녕하세요."))

#datatype2.py

print("# 기본적인 연산")
print(15 , "+", 4 , "=", 15 + 4)
print(15 , "-", 4 , "=", 15 - 4)
print(15 , "*", 4 , "=", 15 * 4)
print(15 , "/", 4 , "=", 15 / 4)

print(10, '/', 3, '= ', 10/3)
print(10, '/', 3, '= ', 10//3)
print(10, '/', 3, '= ', 10%3)


print("# 제곱연산자 **")
print("2 ** 1 = ", 2**1)
print("2 ** 1 = ", 2**2)
print("2 ** 1 = ", 2**3)
print("2 ** 1 = ", 2**4)

#variable.py

#변수: 임의의 값을 저장하는 메모리의 임시 기억장소
#int a; (변수를 선언, 메모리 할당)
#a=100; (값을 변수가 할당된 메모리에 저장)

n1=100
f1=3.5
s1="kingdom"

print(type(n1), ", ", n1)
print(type(f1), ", ", f1)
print(type(s1), ", ", s1)      
print(n1+f1)
n1=200
print(n1+f1)

#input01.py

str1=input("성명 ? ")
print(type(str1), ", ", str1)

n1=input("정수 ? ")
print(type(n1), ", ", n1)

#n1=100;n2=30
#print(n1 , '+', n2, '=', n1+n2)

#input01.py

print("123")
print(type(int("123")), ", ", int("123"))
print(type(float(5.12)), ", ", float(5.12))

#str1=input("성명 ? ")
#print(type(str1), ", ", str1)

n1=input("정수1 ? ")
n1=int(n1)
print(type(n1), ", ", n1)

n2=int(input("정수2 ? "))
print(type(n2), ", ", n2)

#n1=100;n2=30
print(n1 , '+', n2, '=', n1+n2)

s1=100
s1_out=str(s1)
print(type(s1_out), ", ", s1_out)

#format01.py

name="홍길동"
salary=3800000

print("성명: ", name,", 월급: ", salary)
print("성명 :{}, 월급: {}, {}". format(name, salary, salary>=5000000))
print()

# 정수
output_a="{:d}".format(52)
# 특정 칸에 출력하기
output_b="{:10d}".format(52)
# 빈칸을 0으로 채우기
output_c="{:05d}".format(52)
output_d="{:05d}".format(-52)
print("# 기본")
print(output_a)
print("# 특정 칸에 출력하기")
print(output_b)
print("# 빈 칸을 0으로 채우기")
print(output_c)
print(output_d)
print()


#실수
output_a1="{:f}".format(52.273)
output_b1="{:15f}".format(52.273)
output_c1="{:+15f}".format(52.273)
output_d1="{:+015f}".format(52.273)
print(output_a1)
print(output_b1)
print(output_c1)
print(output_d1)
#의미없는 소수점 제거
output_a2 = "{:g}".format(53.00)
print(output_a2)
#소수점 출력자리수 지정
output_a3 = "{:.2f}".format(53.12345)
print(output_a3)
output_a4 = "{:.0f}".format(53.12345)
print(output_a4)

#fstring01.py

name="홍길동"
salary=3800000

print("성명: ", name,", 월급: ", salary)
print("성명 :{}, 월급: {}, {}". format(name, salary, salary>=5000000))

print(f"성명 : {name}, 월급 : {salary}")

print()

n1=100;n2=30
print(n1 , '+', n2, '=', n1+n2)
print(f"{n1} + {n2} = {n1+n2}")
print()

word="Pyton"
print(f"{word} , {word[0]}")
print(f"{word} , {word[-1]}")
print(f"{word} , {word[0:2]}")
print(f"{word} , {word[2:]}")
print(f"{word} , {word[:3]}")
print(f"{word} , {word[::-1]}")

print(f"{','.join([word] * 3)}")

#string_함수.py

str="hello world"
print(str.find("world")) #검색된 index 반환
print(str.find("campus"))

print("world" in str)   #포함하면 true
print("campus" in str)

#operator01.py

n1=50
n2=150

#관계연산자: 두 값을 비교하여 참(true), 거짓(False)을 반환
print(n1>n2)
print(n1<n2)
print(n1==n2)
print(n1!=n2)
print()

#논리연산자: 두 논리값을 비교하여 새로운 참(true), 거짓(False)을 반환
#           비교대상이 여러개 일 때 사용
print(n1>=100 and n2>=100)
print(n1>=100 or n2>=100)
print(not(n1>100))
print()

num=50
print(num>=0 and num<=100)  #0~100
print(0<= num <= 100)

#if01.py

#제어문: 조건제어(if), 반복제어(for, while), 기타제어(break, contine)

num=-10
if num >= 0 :        
    print(f"{num} 양수.")
else :        
    print(f"{num} 음수.")
print("End.")

score=45
if score >= 90:
    print("A 학점")
elif score >= 80:
    print("B 학점")
elif score >= 70:
    print("C 학점")
elif score >= 60:
    print("D 학점")
else:
    print("노력바람.")
print("End.")

import datetime

now1= datetime.datetime.now()
print(now1)

if now1.month <= 6:
    print("상반기")
else:
    print("하반기")

#for01.py

#반복횟수를 알고 있을 때 주로 사용

for index in range(10):
    print(index, ", ", end="")
print()

for index in range(1, 11):
    print(index, ", ", end="")
print()

for index in range(1, 11, 2):
    print(index, ", ", end="")
print()

for index in "CAMPUS":
    print(index, ", ", end="")
print()

#while01.py

i=1;sum=0

while i<=10:  #참이면 반복
    sum = sum+i
    i += 1; # i=i+1
print(f"합: {sum}")

# 1부터 100까지 홀수,짝수의 합
i=1
OddSum=0
EvenSum=0
while i<=100:
    OddSum += i
    EvenSum += (i+1)
    i += 2    
print("홀수의 합: ", OddSum)
print("짝수의 합: ", EvenSum)

#기타제어.py

#break/continue
i=0
sum=0
while True:
    i += 1
    if i>20:
        break;
    if(i%5 == 0):
        sum += i;
    else:
        continue
   
print("1 부터 20 까지 5의 배수의 합 :" , sum)
print()

'''
sum=0
for i in range(5):
    in_data=int(input(f"{i+1} 점수 ? "))
    sum += in_data
print(f"합: {sum}, 평균: {sum/5}")
'''

sum=0
cn=0
while True:
    in_data=input(f"{cn+1} 점수 ? ")
    if(in_data.isdigit()):
        sum += int(in_data)
        cn += 1
    else:
        print("값을 입력하세요!!")
    if(cn==5):
        break;

print(f"합: {sum}, 평균: {sum/cn}")

#list01.py

list_a=[100,200, "python", True, 3.5]
print(f"type(list_a) : {type(list_a)}")
print(f"list_a : {list_a}")

list_b=[40,50,60]
list_c= list_a + list_b
print(f"list_c : {list_c}")
print("list_b*3: ", list_b*3)
print()

print(f"list_c : {list_c}")
print(f"len(list_c) : {len(list_c)}")
print(f"list_c[0] : {list_c[0]}")
print(f"list_c[1] : {list_c[1]}")
print(f"list_c[-1] : {list_c[-1]}")
print(f"list_c[5:] : {list_c[5:]}")
print(f"list_c[:3] : {list_c[:3]}")
print(f"list_c[3:6] : {list_c[3:6]}")
print(f"list_c[::-1] : {list_c[::-1]}")
print(f"--->list_c : {list_c}")
print(f"list_c[2][0] : {list_c[2][0]}")

list_c[0]=150
print(f"list_c : {list_c}")

print("==============")
list_a=[10,20,30]
print(f"list_a : {list_a})")
list_a.append(40)
print(f"list_a : {list_a}")
list_a.insert(0, 5)
print(f"list_a : {list_a}")
list_a.extend([50,60,70])
print(f"list_a : {list_a}")

del list_a[0]   #index 위치 제거
print(f"list_a : {list_a}")
list_a.pop(1)   #index 위치 제거
print(f"list_a : {list_a}")

list_a.remove(70)   #값을 찾아 제거
print(f"list_a : {list_a}")

del list_a[0:2]
print(f"list_a : {list_a}")

#list02.py

list_a=[10,80,30,100,50]
print(f"list_a : {list_a}")

b1=20 in list_a
b2=50 in list_a
print(f"{b1}, {b2}")

print(f"max : {max(list_a)}")
print(f"min : {min(list_a)}")
print(f"sum : {sum(list_a)}")

list_a.sort()
print(f"list_a : {list_a}")
list_a.reverse()
print(f"list_a : {list_a}")

list_b=list((1,2,3,4,))
print(f"list_b : {list_b}")

list_c=list("python")
print(f"list_c : {list_c}")

#list_반복.py

list_a=[10,20,30,40,50]
print(f"list_a : {list_a}")

for item in list_a:
    print(f"item : {item}")
print()

for index in range(len(list_a)):
    print(index, ": ", list_a[index])
print()

print("리스트 내포")
list_a= [ i*i for i in range(0,20,2)]
print(f"list_a : {list_a}")

sal_list=[4000, 7500, 3400, 8900, 2500, 5000]
list_a = [ sal for sal in sal_list if sal >= 5000 ]
print(f"list_a : {list_a}")

list1 = [3, 12, 9, 10, 100, 49, 399, 20, 329, 450, 4]
list_a = [ i for i in list1 if i%2==0 and i<=100 ]
print(f"list_a : {list_a}")
print()

numbers = [1, 2, 3, 4, 5]
result = []
for n in numbers:
    if n % 2 == 1:
        result.append(n*2)
print(result) #2,6,10

#리스트 내포로 변경
numbers = [1, 2, 3, 4, 5]
result = []
result=[ n*2 for n in numbers if n%2 == 1]
print(f"result : {result}")

#list_반복02.py

list_of_list = [
[1, 2, 3],
[4, 5, 6, 7],
[8, 9],
]

print(f"type(list_of_list) : {type(list_of_list)}")
print(f"list_of_list : {list_of_list}")

print(f"list_of_list[0]: {list_of_list[0]}")
print(f"list_of_list[1]: {list_of_list[1]}")
print(f"list_of_list[2]: {list_of_list[2]}")
print(f"list_of_list[2][0]: {list_of_list[2][0]}")
print()

for line in list_of_list:
    #print(line)
    for item in line:
        print(item, ", ", end="")    
    print()
print("=========\n")

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
output = [[], [], []]

for i in range(len(numbers)):
    if(i%3 == 0):
        output[0].append(numbers[i])
    elif(i%3==1):
        output[1].append(numbers[i])
    elif(i%3==2):
        output[2].append(numbers[i])

print(f"output : {output}")

#tuple01.py

t1=(100, "python", True, 5.7)
print(f"type(t1) : { type(t1) }")
print(f"t1: {t1}")

print(f"t1[0] : { t1[0] }")
print(f"t1[0:1] : { t1[0:1] }")
print(f"len(t1): {len(t1)}")

for item in t1:
    print(item)
print()

#t1[0]=150
#t1.append(200)
#del t1[0]

a1=(100)
a2=(100,)
a3=(100,200,"python")
print(f"type(a1): {type(a1)}")
print(f"type(a2): {type(a2)}")
print(f"type(a3): {type(a3)}")
print(f"a3 : { a3 }")

x1, x2, x3 = a3
print(f"{x1}, {x2}, {x3}")
print(f"type(x1): { type(x1)}")
print(f"type(x3): { type(x3)}")

list_a=list(a3)
print(f"type(list_a) : { type(list_a) }")
print(f"list_a: {list_a}")

#dic01.py

dict1={"name": "kim", "age":30}
print(f"type(dict1): {type(dict1)}")
print(f"dict1: { dict1 }")
print(dict1["name"])

dict2=dict(name="lee", age=20)
print(f"type(dict2): {type(dict2)}")
print(f"dict1: { dict2 }")
print(dict2["name"])
print()

dictionary = {
"name": "7D 건조 망고",
"type": "당절임",
"ingredient": ["망고", "설탕", "메타중아황산나트륨", "치자황색소"],
"origin": "필리핀"
}

print(f"type(dictionary): {type(dictionary)}")
print(f"dictionary: { dictionary }")
print(dictionary["name"])
print(dictionary["type"])
print(dictionary["ingredient"])
print(dictionary["ingredient"][0])
print(dictionary["origin"])
print()

dictionary["price"] = 5000
dictionary["name"] = "apple"
del dictionary["type"]
print(f"dictionary: { dictionary }")
print()

print(dictionary.keys())
print(dictionary.values())
print()

print("name" in dictionary) #True
print("age" in dictionary)  #False

value = dictionary.get("origin")    #key 값에 해당하는 value
print(value)
value = dictionary.get("age")    #key 값에 해당하는 value
print(value)

#dict_반복.py

dictionary = {
"name": "7D 건조 망고",
"type": "당절임",
"ingredient": ["망고", "설탕", "메타중아황산나트륨", "치자황색소"],
"origin": "필리핀"
}

for key in dictionary :
    print(key, ":", dictionary[key])
print()
   
for key in dictionary :
    if type(dictionary[key]) is list:
        for item in dictionary[key] :
            print(item, ", ", end="")
        print()
    else:
        print(key, ":", dictionary[key])

print()

pets = [
{"name": "구름", "age": 5},
{"name": "초코", "age": 3},
{"name": "아지", "age": 1},
{"name": "호랑이", "age": 1}
]

for pet in pets :
    #print(pet['name'], ' ', pet['age'] , ' 살')
    #print(pet) #{"name": "구름", "age": 5}
    for key in pet:
        print(pet[key], " ", end="")
    print(" 살")

#set01.py

s1=set([1,2,3])
s2=set("hello")
print(f"type(s1): {type(s1)}")
print(f"s1: {s1}")
print(f"s2: {s2}")

list_a=[2,5,8,9,3,6,1,9,2,1,3,1]
s1=set(list_a)
print(f"type(s1): {type(s1)}")
print(f"s1: {s1}")

list_a=list(s1)
print(f"type(list_a): {type(list_a)}")
print(f"s1: {list_a}")
print()

s1=set([1,2,3,4,5,6])
s2=set([4,5,6,7,8,9])
print(f"s1: {s1}")
print(f"s2: {s2}")

s3=s1 & s2 # 교집합
print(f"s3: {s3}")

s3=s1 | s2 # 합집합
print(f"s3: {s3}")

s3=s1-s2 # 차집합
print(f"s3: {s3}")
s3=s2-s1 # 차집합
print(f"s3: {s3}")
print()          

numbers = [1,2,6,8,4,3,2,1,9,5,4,9,7,2,1,3,5,4,8,9,7,2,3]
counter = {}

for number in numbers:
    if number in counter:
        #counter[1]=counter[number] key의 value 값 + 1
        counter[number] = counter[number] + 1
    else:
        counter[number] = 1 #count[1] : 1

print(counter)
print()      

#func_Intor.py

#함수 정의부
def sum1():
    num=int(input("정수 ? "))
    sum=0
    for index in range(1,num+1):
        sum += index
    print(f"1부터 {num} 까지의 합: {sum}")

sum1() #함수 호출부
print()

        #가인수
def sum2(start, end=100):
    sum=0
    for index in range(start, end+1):
        sum += index
    print(f"{start}부터 {end} 까지의 합: {sum}")
   
sum2(1, 50) #함수(실인수)
sum2(1, 200)
sum2(1)

#func_가변매개변수.py

#가변인자를 받을 매개변수
def print_n_times(n, *values):
    for i in range(n):
        for value in values:
            print(value, ":", end="")
        print()
       
print_n_times(3, "안녕하세요", "즐거운", "파이썬 프로그래밍")
print_n_times(3, "안녕하세요", "즐거운", "파이썬 프로그래밍", "!!!")
print()

def print_n_times(*values, n=2):
    for i in range(n):
        for value in values:
            print(value, ":", end="")
        print()

print_n_times("안녕하세요", "즐거운", "파이썬 프로그래밍", n=3) #키워드 매개변수

print("파이썬의 리턴 값")
value = add_mul(100, 30)
print(f"type(value): {type(value)}")
print(f"value: {value}")
n1, n2=value
print(f"type(n1): {type(n1)}")
print(f"n1: {n1}, n2: {n2}")

n1, n2 = add_mul(10, 30) #반환값 tuple
print(f"type(n1): {type(n1)}")
print(f"n1: {n1}, n2: {n2}")
print()

def mul(*values):
    output = 1
    for value in values:
        output *= value
    return output

print(mul(5,7,9,10))

#func_변수구분.py

print("\n전역, 지역변수")
g1=100          #전역변수
count=5000      #전역변수
def funcA():
    global g1, g2
    l_value=10; #지역변수
    print("g1:", g1)
    print("g2:", g2)
    g1 = 50
    print("l_value:", l_value)
    count=1000  #지역변수
    global g3
    g3=200
    print(f"funcA() count: {count}")

g2="python"
funcA()

print("g1:", g1)
#print("l_value:", l_value) #Error
print("g2:", g2)
print("g3:", g3)
print(f"count: {count}")

#func_람다.py

def hap(x,y):
    return x+y

ret = hap(10,20)
print(f"ret : {ret}")

ret=(lambda x, y : x + y)(100,200)
print(ret)

sum=100
ret=(lambda y : sum + y)(300)
print(ret)
print()

print("map()")
ret= map(lambda x : x*2 , range(1,5))

print(f"type(ret) : {type(ret)}")
print(f"ret : {ret}")
list_a=list(ret)
print(f"type(list_a) : {type(list_a)}")
print(f"list_a : {list_a}")

list_b=[2,4,6,8,10,12]
list_a=list(map(lambda x: x+10, list_b))
print(f"list_a : {list_a}")

print("filter()")
ret= filter(lambda x : x<=5 , range(1,11))
print(f"type(ret) : {type(ret)}")
print(f"ret : {ret}")
list_a=list(ret)
print(f"type(list_a) : {type(list_a)}")
print(f"list_a : {list_a}")

list_b=[1,4,3,8,7,12]
list_a=list(filter(lambda x: x%2==0, list_b))
print(f"list_a : {list_a}")

list_b=[1,4,3,8,7,12]
list_a=list(map(lambda x: x%2==0, list_b))
print(f"list_a : {list_a}")

a1="kim", "lee", "han".split()
print(f"type(a1) : {type(a1)}")
print(f"a1 : {a1}")

#d1="100,200,300,400,500".split(',')
d1="100 200 300 400 500".split()
print(f"type(d1) : {type(d1)}")
print(f"d1 : {d1}")

d2=list(map(int, d1))
print(f"d2 : {d2}")

#input_여러데이터입력.py

a, b, c = input('"정수 3개 입력 ? : ').split()
print(type(a)) # input().split()의 결과는 문자열
print(int(a) + int(b) + int(c))
print()

x = input("정수 3개 입력 ? ").split() #결과는 문자열 리스트
print(type(x))

m = map(int, x) #리스트의 요소를 int로 변환, 결과는 맵 객체
a, b, c = m
print(type(a))
print(a + b + c)

a, b, c = map(int, input('"정수 3개 입력 ? : ').split())
print(a + b + c)

numbers = [1,2,3,4,5,6]
num_data="::".join(map(str, numbers))
print("num_data : ", type(num_data), ", ", num_data)

print("=======================\n")

numbers = list(range(1,10+1))
print("\nnumbers : ", numbers) #[1,2,3,4,5,6,7,8,9,10]

print("# 홀수만 추출하기")
print(list(filter(lambda x: x % 2 ==1, numbers)))
print()
print("# 3 이상, 7 미만 추출하기")
print(list(filter(lambda x:3 <= x < 7, numbers)))
print()
print("# 제곱해서 50 미만 추출하기")
print(list(filter(lambda x: x ** 2 < 50, numbers)))

#module_표준모듈.py

import math

print(math.sin(1))
print(math.floor(2.5))
print(math.ceil(3.5))
print(math.sqrt(10))
print()

from math import sin, floor, sqrt
print(sin(1))
print(floor(2.5))
#print(ceil(3.5))
print(sqrt(10))
print()

import math as m
print(m.sin(1))
print(m.floor(2.5))
print(m.ceil(3.5))
print(m.sqrt(10))
print()

#module_random.py

import random

print("random():", random.random())

# uniform(min, max): 지정한 범위 사이의 float를 리턴
print("uniform(10, 20):", random.uniform(10, 30))

# randrange(): 지정한 범위의 int를 리턴
print("randrange(10)", random.randrange(10))

print("randrange(10,30)", random.randrange(10,30))

# choice(list): 리스트 내부에 있는 요소를 랜덤하게 선택
print("choice([1, 2, 3, 4, 5]):", random.choice([1, 2, 3, 4, 5]))

#random_os.py

import os

print("현재 운영체제:", os.name)
print("현재 폴더:", os.getcwd())
print("------------------------------\n")
os.system("dir")

#module_datetime.py

import datetime

print("# 현재 시각 출력하기")
now = datetime.datetime.now()
print(now.year, "년")
print(now.month, "월")
print(now.day, "일")
print(now.hour, "시")
print(now.minute, "분")
print(now.second, "초")
print()

# 시간 출력 방법
print("# 시간을 포맷에 맞춰 출력하기")
output_a =now.strftime("%Y.%m.%d %H:%M:%S")
output_b = now.strftime("%Y-%m-%d %H:%M:%S")
output_c = now.strftime("%Y년 %m월 %d일 %H시 %M분 %S초")
print(output_a)
print(output_b)
print(output_c)
print()

print("# now.replace()로 1년 더하기")
output = now.replace(year=(now.year + 1))
print(output.strftime("%Y-%m-%d %H:%M:%S"))
print("# now.replace()로 1 달 더하기")
output = now.replace(month=(now.month + 1))
print(output.strftime("%Y-%m-%d %H:%M:%S"))
print("# now.replace()로 1 일 더하기")
output = now.replace(day=(now.day + 1))
print(output.strftime("%Y-%m-%d %H:%M:%S"))

PS D:\python\CH07> pip list
Package Version


pip 22.0.4
setuptools 58.1.0
WARNING: You are using pip version 22.0.4; however, version 22.1.1 is available.
You should consider upgrading via the 'C:\Users\formi\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip' command.
PS D:\python\CH07> pip install beautifulsoup4
Collecting beautifulsoup4
Downloading beautifulsoup4-4.11.1-py3-none-any.whl (128 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 128.2/128.2 KB 3.8 MB/s eta 0:00:00
Collecting soupsieve>1.2
Downloading soupsieve-2.3.2.post1-py3-none-any.whl (37 kB)
Installing collected packages: soupsieve, beautifulsoup4
Successfully installed beautifulsoup4-4.11.1 soupsieve-2.3.2.post1
WARNING: You are using pip version 22.0.4; however, version 22.1.1 is available.
You should consider upgrading via the 'C:\Users\formi\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip' command.
PS D:\python\CH07> pip list
Package Version


beautifulsoup4 4.11.1
pip 22.0.4
setuptools 58.1.0
soupsieve 2.3.2.post1
WARNING: You are using pip version 22.0.4; however, version 22.1.1 is available.
You should consider upgrading via the 'C:\Users\formi\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip' command.
PS D:\python\CH07>

#module_외부모듈.py

#1. 외부모듈 설치(pip)
#2. import 모듈명

from urllib import request
from bs4 import BeautifulSoup

# urlopen() 함수로 기상청의 전국 날씨를 읽는다
target = request.urlopen("http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108")
# BeautifulSoup을 사용해 웹 페이지를 분석
soup = BeautifulSoup(target, "html.parser")
# location 태그를 찾는다
for location in soup.select("location"):
    # 내부의 city, wf, tmn, tmx 태그를 찾아 출력
    print("날짜:", location.select_one("tmef").string)
    print("도시:", location.select_one("city").string)
    print("날씨:", location.select_one("wf").string)
    print("최저기온:", location.select_one("tmn").string)
    print("최고기온:", location.select_one("tmx").string)
    print()

main.py 파일

import test_module as test

radius = test.number_input()
print(test.get_circumference(radius))
print(test.get_circle_area(radius))

print("main.py : ", __name__)
# test_module.py 파일
PI = 3.141592

def number_input():
    output = input("숫자 입력> ")
    return float(output)

def get_circumference(radius):
    return 2 * PI * radius

def get_circle_area(radius):
    return PI * radius * radius

print("test_module.py: ", __name__)

# 패키지 내부의 모듈을 읽어 들입니다.
import test_package.module_a as a
import test_package.module_b as b

#### 모듈 내부의 변수를 출력합니다.
print(a.variable_a)
a.add(100, 30)

print(b.variable_b)
b.sub(100,30)
# ./test_package/module_a.py의 내용
variable_a = "a 모듈의 변수"

def add(x, y):
    print(f"{x} + {y}={x+y}")
# ./test_package/module_b.py의 내용
variable_b = "b 모듈의 변수"

def sub(x, y):
    print(f"{x} - {y}={x-y}")

init.py

#### "from test_package import *"로
#### 모듈을 읽어 들일 때 가져올 모듈
__all__ = ["module_a", "module_b"]

#### 패키지를 읽어 들일 때 처리를 작성할 수도 있습니다.
print("test_package를 읽어 들였습니다.")



#### 패키지 내부의 모듈을 모두 읽어 들입니다.
from test_package import *

#### 모듈 내부의 변수를 출력합니다.
print(module_a.variable_a)
module_a.add(100, 30)

print(module_b.variable_b)
module_b.sub(100,30)

#class_intro.py

class Student:
    def __init__(self): #객체생성시 자동으로 호출되는 함수
        print("객체 생성 함.")
       
    def study(self, name):
        print(name, "학생이 공부를 합니다.")

class Teacher:
    def teach(self, name):
        print(name, "선생님이 학생을 가르킵니다.")

#객체변수 = 클래스명
s1 = Student()
s2 = Student()
t1 = Teacher()

s1.study("kim ")
s2.study("lee ")
t1.teach("홍길동 ")

#class_Student.py

class Student:
    def __init__(self, name, kor, mat, eng) :
        #print("객체 생성 초기화")
        self.name=name #객체 멤버변수
        self.kor=kor
        self.mat=mat
        self.eng=eng
        self.tot=0
        self.avg=0

    def hap(self):
        self.tot=self.kor+self.eng+self.mat
        self.avg = self.tot/3

    def student_show(self):
        print("{:4s}, {:3d}, {:3d} ,{:3d}, {:3d}, {:.2f}".format(self.name,
              self.kor, self.mat, self.eng, self.tot, self.avg))
 
#s1=Student("kim", 90, 87, 80)
#s1.hap()
#s1.student_show()

student = [
    Student("kim", 78, 50, 90),
    Student("lee", 90, 70, 50),
    Student("han", 98, 59, 40),
    Student("park", 38, 80, 92),
    Student("sun", 56, 70, 80)
]

print(f"type(student) : {type(student)}")
print(f"student : {student}")

for stu in student:
    #print(stu)
    stu.hap()
    stu.student_show()

0개의 댓글