#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 ( " \n numbers : " , 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() 함수로 기상청의 전국 날씨를 읽는다
# 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 ()
댓글