공부중/python

파이썬 입문 3일차

또돌근 2021. 2. 8. 22:26
반응형

1) try / except

2) yield

3) map

4) comprehension

5) class

6) mod

 

-- 다중예외처리(1:n) as e

-- list->(map_lambda)-->list 

-- comprehension 식으로 list, tuple, set, dictionary 만들기 

-- comprehension식에 if가 여러개

-- 생성자 / 생성자 매개변수가 여러개

-- self

-- 인스턴스멤버, 클래스멤버 사용

-- 다중상속(부모클래스가 여러개)

-- pass   : 부모클래스의 멤버 그대로 받음(try/except의 pass와 다른.)

-- 연산자오버로딩

-- 소멸자

-- repr(toString)

-- 추상메서드, 오버라이딩 필수, 예외

-- 모듈 / import / if __name__=="__main__": 메인메서드

-- from mod import add, sub

 

 

 

1. try/except_2

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 09:47:59 2021

@author: 2016005

tryex2.py : 다중 예외처리

try는 똑같은데
catch는 없고 그냥 'except 무슨에러 : ' 로 표현.
"""

num1 = input("문자 1 입력:") # 문자 1 입력받기
num2 = input("문자 2 입력:") # 문자 1 입력받기

try:
    num1 = int(num1) #정수형으로 변환 - 오류발생
    num2 = int(num2)
    while True:
        res = num1/num2
        print(res)
except ValueError as e: # 발생된 예외를 e라는 변수(객체)로 저장함.
    print("문자를 숫자로 변환 불가")
    print(e) # 에러메시지 출력
except ZeroDivisionError as e:
    print("0으로 나눔 불가")
    print(e)
except KeyboardInterrupt as e:
    print("CTRL+C가 눌렸음")
    print(e)
finally:   # 정상이던, 오류발생이던 어쨋든 실행되는 finally
    print("프로그램 종료")

2. try/except_3

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 10:02:31 2021

@author: 2016005

tryex3.py : 다중처리를 하나의 변수로 묶기
"""

try:
    a=[1,2]
    print(a[1])
    #4/0
    b = int("a")
except (ZeroDivisionError, IndexError)as e :  
    # 두개의 예외가 하나의 변수로 넣는게 아니고
    # 여러 발생 가능한 예외를 , 를 이용해서 연결해서 한문장으로 처리한 것.
    print(e)
except ValueError:
    print("정수값만 가능")


"""
    File "C:\Users\2016005\.spyder-py3\python\workspace\20210204\0206\tryex3.py", line 14, in <module>
    b = int("a")

    ValueError: invalid literal for int() with base 10: 'a'
    는 예외처리가 안된 것임.
"""

3. try/except_4

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 10:09:17 2021

@author: 2016005

tryex4.py : #자바에 없는 내용. 

1. finally는 정상이던 비정상이던 실행되는데,
    1)try 구문에서 오류가 발생하면 except구문실행됨 : 예외처리
    2)오류가 없는 경우는 else 구문이 실행 될 수 있다. : 자바에 없는 내용.★

2. 오류발생시 그냥 pass하는 방법 : pass예약어 이용.


3. 오류 강제 발생하는 방법 : raise예약어 이용.
"""

try:
    age = int(input("나이 입력"))

except:
    print("나이가 아님. 정확히 입력 요망")

else: ##오류가 발생하지 않으면.
    if age <= 19 : print("미성년자")
    else :print("성인")
    
try:
    f = open("없는파일","r")    #open ???
except FileNotFoundError :
    #print("파일오류 무시")  ##예외발생시 아무일도 안하게 하려는데, : 찍고나면 항상 뭘 써야한다. 
    #이럴때 아무것도 없이 하려면? 예약어 사용.
    pass  ## 예외발생시 아무것도 안하게끔.

4. yield

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 10:33:41 2021

@author: 2016005

yieldex1.py : 함수 종료 없이 , yield로 값을 리턴하는 기능이 있다.
"""

def genFun(num):
    for i in range(10, num + 10):
        yield i  # 함수 종료 없이 나를 호출한 곳에다가 i값을 전달하는 것임.but, 함수를 끝내지 않음.(return 안함.)
        print(i, "값 반환") # 얘가 먼저 실행 된 후 위의 yield는 list로 하나씩 보낸다.
        
print(list(genFun(5)))#결과값을 list로 만들어서 화면에 출력하자. 하나씩 모은 값들을 또 출력

ArithmeticError


for data in genFun(5): #여기서 genFun하면 yield i는 이 for문으로 값을 주고, 나머지 실행하고, 하는 식임.
    print("main에서 출력 : ",data)

5. map_1

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 10:41:37 2021

@author: 2016005

mapex1.py : map: 리스트의 각각의 요소를 '변경'함.

dictionary 와 헷갈리지 말 것.

자바의 스트림_map함수와 비슷. 다른형태로 매핑한다는 점에서.
"""

before = ["2021","02","08"] #문자열 리스트
print(type(before[0]))
print(before)

after = list(map(int,before))  
# map(자료형, 무엇(list객체)을) =>형변환 => list객체로 ##'자료형'은 함수다. 인트형태로 만드는 함수

print(type(after[0]))
print(after)

print(int("123"))

6. map_2

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 10:47:57 2021

@author: 2016005

mapex2.py : 람다 이용 map처리.
"""

mylist = [1,2,3,4,5]

add = lambda num:num+10
mylist = list(map(add, mylist))  ## map(자료형, 무엇을)  => 자료형을 람다로 처리.
print(mylist)

# num == mylist에 있는 요소 한개를 num이 받는다. 그 num에서 10을 빼.
mylist = list(map(lambda num:num-10, mylist)) 
print (mylist)

mylist = list(map(lambda num:num*10, mylist))
print (mylist)


print()
list1 = [1,2,3,4]
list2 = [10,20,30,40]
hap = lambda n1, n2 : n1+n2
haplist = list(map(hap,list1,list2)) ## hap 람다메서드에 대한 매개변수 : list1, list2 이렇게 표현하네?
print(haplist)

#haplist = mylist + list1 + list2

haplist = list(lambda n1,n2,n3:n1+n2+n3, mylist,list1,list2) 
## map을 안썼음. 왜 안쓰지?왜? 왜 위에는 씀?
# 리스트의 개수가 안맞을 땐? 안되는게 아니고 최소요소개수의 리스트의 개수로 맞춰줌.
   #list화 해라(이런식으로, 무엇들을)

print(haplist)

 

7. comprehension_1

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 11:13:35 2021

@author: 2016005

comprehension ex1.py : 컴프리헨션 예제
                    패턴이 있는 list, dictionary, set을 간편하게 작성할 수 있는 기능.
"""

numbers = []
for n in range(1,11):
    numbers.append(n)
print(numbers)

## ↑위의 것을 comprehension으로 똑같이 만들어보자.↓  ★ 반복문 안쓰고 패턴 만들기.

print([x for x in range(1,11)])  # []는 리스트다. 만들어서 바로 출력하는 것이지.
clist = [x for x in range(1,11)]
print(clist)


#1 ~ 10 까지의 짝수 리스트 작성하기. for 구문으로 작성하기
evenlist = []
for i in range(1,10+1):
    if(i%2==0):
        evenlist.append(i)
print(evenlist)

###conprehension쓰기↓ ★
evenlist = [x for x in range(1,11) if x%2==0]  ## for구문에 대해 if를 붙일 수 있다.
print(evenlist)

#2의 배수이고, 3의 배수인 값만 리스트에 추가하기.(사실상 6의 배수인 것들만 넣으면 되는데...)
list23 = [x for x in range(1,11) if x%2==0 if x%3==0] ## if구문을 두 개도 쓸 수 있다.
print(list23)


#comprehension의 중첩사용  : 컴프렌션==지능형리스트 어쩌고저쩌고.
matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(matrix)
list1 = [x for row in matrix for x in row]
# matrix의 각각의 row = [1,2,3]
# x : 1 or 2 or 3
#얘네들을 맨 앞의 x로 가져와서
# 리스트로 만들어.
print(list1)

#컴프렌션 표현식 안쓰기.
list2 = []
for row in matrix: ## row 라는 애가 샅샅이 뒤질 수 있는 놈인가봄..
    for i in row:
        list2.append(i)
print(list2)        


##========튜플 만들기=======두 리스트의 요소를 1:n으로 매칭시키기.
colorlist = ['black','white','blue']
sizelist = ["S","M","L"]
##튜플 만들기 튜플:변경불가 리스트. 동그란 괄호로 표시. 
##튜플의 내용은 (c,s) 두개로 쌍으로 만들겠다.
##((c,s) for c in xxxlist  {1대} // for s in xxlist   {N}) 나눠서 생각하면 될듯.
dresslist = ((c,s) for c in colorlist for s in sizelist)
##                          1대                  N           으로 튜플 만들기.
for d in dresslist:
    print(d)
    
##파이썬에서 for문을 쓸때, 아예 그 리스트 자체를 돌고싶으면 for N in 리스트이름 :    하면 된다.
'''
('black', 'S')
('black', 'M')
('black', 'L')
('white', 'S')
('white', 'M')
('white', 'L')
('blue', 'S')
('blue', 'M')
('blue', 'L')
'''

8. comprehension_2

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 11:55:29 2021

@author: 2016005

comprehensionex2.py : 컴프리헨션을 이용한 set


list1 = [x**2 for x in [1,1,2,2,3,3]] 이런게 컴프렌션 표현식.

"""

set1 = {x**2 for x in [1,1,2,2,3,3]} #{}중괄호 셋.
## 두번째x가 1,1,2,2,3,3을 돌면서 받고, 첫번째의 x**2가 계산을 해서 set에 넣어줌.
## 중복안되므로 {1,4,9}
print(set1)


list1 = [x**2 for x in [1,1,2,2,3,3]] # []대괄호 리스트
print(list1)


#1부터 10까지의 수 중 짝수의 제곱을 출력하기

set2 = {x**2 for x in range(1,11) if x%2==0} # x의 제곱을 구해.
print(set2)
print(sorted(set2))  ## set도 정렬을 할 수 있네. 근데. 결과가 list로 나오네????set->sorted->list

9. comprehension_3

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 12:02:26 2021

@author: 2016005

comprehensionex3.py : 컴프렌션으로 dictionary 만들기
"""

products = {"냉장고":220, "건조기":140, "TV":130, "세탁기":150, "오디오":50, "컴퓨터":250}
print(products)
product1 = {}

#200만원 미만의 제품만 product1에 저장하기   dictionary 순회하면서 그 값을 비교하는 방법. 
##for문으로.  get(XXX)을 쓴다. 그러면 그 value를 비교한다.
for name in products:
    if products.get(name) < 200:
        product1[name] = products.get(name)
print(product1)
        

for p,v in products.items():  # items가 (k,v)쌍인 객체를 전달해주고. k는 p로 v 는 v로 
    if v <200:   # v 가 200보다 작아?
        product1.update({p:v})  #.update로써 딕셔너리에 추가할 수 있다. 형태는 {p,v}로. 이것은 {K,V}이다.
print(product1)

# 이것을 컴프렌션으로 만들어보자.

product2 = {p:v for p,v in products.items() if v<200} 
## ★ p:v의 형태로 여러개 넣을 건데, products.items()로 (k,v)형태로 받아내서 p,v로 받아서 그대로 전달할건데,
## v가 200보다 작을 때 p,v형태로 product2에 추가할것이다.
print(product2)

10. class _1

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 13:32:05 2021

@author: 2016005

##파이썬에도 클래스라는 개념이 있다.
객체를 만들 수 있는 도구.

classex1.py : 클래스 예제

"""

#기본 생성자 : __init__(self) :  => 생성자를 구현하지 않으면 자동으로 제공되는 생성자(자바의 디폴트생성자)
    #           pass

class Car :##기본생성자가 제공됨(별도의 생성자를 구현하지 않았음.)
    color = "" #멤버변수
    speed = 0  #멤버변수
    def upSpeed(self, value): #멤버메서드
        self.speed += value
    def downSpeed(self, value): #멤버메서드
        self.speed -= value
        
### self는 comprehension의 row같이 쓰이는가봄.
### self : 자바의 this(자기참조 변수 : 자신객체의 멤버를 표현시 사용되는 '예약어') 
### 자바에서 this는 인스턴스멤버에서만 사용가능하다.
### self도 마찬가지이다.
### but, this처럼 자동으로 만들어주는게 아닌, self라고 표현을 해줘야한다.
### 메서드는 (self, value)로 매개를 쳐줬는데
### 사용은 upSpeed(30) 으로 하나만 한다.

myCar1 = Car() # 객체화. 객체생성하려면 반드시 생성자를 호출. 기본생성자 호출.
myCar1.color = "빨강"
myCar1.speed = 0

myCar2 = Car()
myCar2.color = "노랑"
myCar2.speed = 0

myCar3 = Car()
myCar3.color = "파랑"
myCar3.speed = 0

myCar1.upSpeed(30)
print("자동차1의 색상은 %s이며, 현재 속도는 %dkm입니다." % (myCar1.color, myCar1.speed)) 

myCar2.upSpeed(60)
print("자동차2의 색상은 %s이며, 현재 속도는 %dkm입니다." % (myCar2.color, myCar2.speed)) 

myCar3.upSpeed(10)
print("자동차3의 색상은 %s이며, 현재 속도는 %dkm입니다." % (myCar3.color, myCar3.speed)) 

11. class _2

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 13:49:35 2021

@author: 2016005

classex2.py : 생성자

    __init__  생성자임
    기본생성자 : 생성자의 매개변수가 self인 생성자
"""

class Car :
    color = ""   #초기화
    speed = 0    ## 인스턴스멤버 (self로 접근하기때문)
    
    def __init__(self, v1, v2): ## 생성자. self가 들어간다.
        self.color = v1
        self.speed = v2
    
    def upSpeed(self, value):
        self.speed += value
        
    def downSpeed(self, value): 
        self.speed -= value
        
myCar1 = Car("빨강",10) # v1<=빨강, v2<=10 값으로 매핑함
myCar2 = Car("노랑",20) # v1<=노랑, v2<=20 값으로 매핑함

print("자동차1의 색상은 %s 이며, 현재속도는 %dkm 입니다." % (myCar1.color, myCar1.speed))
print("자동차2의 색상은 %s 이며, 현재속도는 %dkm 입니다." % (myCar2.color, myCar2.speed))

12. class _3

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 13:57:28 2021

@author: 2016005

classex3.py : 클래스멤버 와 인스턴스 멤버
"""

class Car : 
    color = ""
    speed = 0
    num = 0
    count = 0
    def __init__(self,v=""):  # 생성자     #생성자 오버로딩이 아닌, v=""를 추가해주면 됨.
        self.color = v
        self.speed = 0  ##인스턴스 변수
        Car.count += 1  ## 클래스 변수    :  '클래스명.변수명' 으로 써주기만 하면 클래스변수가 된다.
        self.num = Car.count #인스턴스 변수  : 'self.변수명' 으로 쓰면 인스턴스변수가 된다.
    
    '''이것은 틀린 것.
    def __init__(self,color):
        self.color = color
        Car.count +=1
        self.speed = 0
        self.num = Car.count
    '''  
        
    def printMessage(self):  # 그냥 메서드() 처럼. 매개변수 없음.
        print("색상: %s, 속도:%dkm, 번호:%d, 생산번호:%s" % (self.color, self.speed, self.num, Car.count), end="")
        
mycar1, mycar2 = None, None  #자바의 null, 참조 객체 없음. 객체화되지 않음. 선언만.

mycar1 = Car() #객체화. num=1
mycar1.speed = 30
mycar1.printMessage()
print()

mycar2 = Car()  # num=2. Car.count가 클래스멤버이기때문에. count를 0으로 했어도.
mycar2.speed = 50
mycar2.printMessage()  
print()

Car.count+=10
print("생산번호:%d" % (mycar1.count))      
print("생산번호:%d" % (mycar2.count))   

mycar1.count += 1
mycar3 = Car("빨강") # 객체화 오류발생. 생성자 없음
mycar3.printMessage()

13. class _4

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 14:36:37 2021

@author: 2016005

classex4.py : 상속예제 _ 오버라이딩예제, 다중상속 가능. (자바랑 다름)

단일상속 : 자손입장에서 부모가 하나  (자바)
다중상속 :      ""            여러개
"""

class Car:
    speed = 0
    door = 3
    def upSpeed(self, value):
        self.speed += value
        
        print("현재속도(부모클래스): %d" % self.speed)
        
class Sedan(Car): ## Car클래스를 상속받은 하위클래스가 된다. 상속을 이렇게 받음. 'class 이름(부모클래스)'
    pass          ## Car클래스의 멤버를 그대로 유지하겠다. == 부모 멤버 외에 따로 멤버를 가지지 않겠다.

class Truck(Car):
    def upSpeed(self,value):  ## 오버라이딩.(Car클래스의 upSpeed메서드)
        self.speed += value
        
        if self.speed > 150 : #speed를 150으로 제한.
            self.speed = 150
        print("현재속도(자손클래스) : %d" % self.speed)
        
class Container:
    room = 1
    
class MovingCar(Container, Car):  ##다중상속 (container와 car를 상속받음)
    pass
    ##speed , door , room


sedan1 = Sedan() #객체화
truck1 = Truck() #객체화

print("트럭:", end="")
truck1.upSpeed(200) #트럭:현재속도(자손클래스) : 150  ==> upSpeed를 오버라이딩 했기때문.

print("승용차:",end="")
sedan1.upSpeed(200)

mcar = MovingCar() #Container, Car클래스를 다중상속받음.
mcar.upSpeed(60)
print("이동차량의 방 개수:",mcar.room,", 문 개수:",mcar.door)

14. class _5

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 14:54:25 2021

@author: 2016005

classex5.py : 클래스에서 사용되는 특별한 메서드

    *생성자   : __init__(self, ...)  or (self, v="") or 가변매개변수
    *소멸자   : __del__(self)  :매개변수가 있으면 안됨.
    
    *문자열화 : __repr__(self)           자바의 toString
    * '+'연산자: __add__(self,other)     이항연산자기때문에 other필요.
    * '<'      : __lt__(self,other)     이항연산자기때문에 other필요.
    * '>'      : __gt__(self,other)     이항연산자기때문에 other필요.
    * '=='     : __eq__(self,other)     이항연산자기때문에 other필요.
    * '-'      : __sub__(self,other)     이항연산자기때문에 other필요.
      ....등등등

"""

class Line:
    length = 0
    
    def __init__(self,length):
        self.length = length
        
    def __repr__(self):
        return "선의 길이:"+str(self.length)
    
    ###연산자 오버로딩###
    def __add__(self,other): ## '+' 연산자 사용시 호출되는 메서드. __add__
        print("'+' 연산자 호출==>add메서드 호출")
        return self.length + other.length
    
    def __lt__(self,other):#lt : myline1 < myline2 실행시 호출되는 메서드
        print("'<' 연산자 호출")
        return self.length < other.length
    
    def __gt__(self,other):#gt : myline1 > myline2 실행시 호출되는 메서드
        print("'>' 연산자 호출")
        return self.length > other.length
    
    def __eq__(self,other): #eq : myline1 == myline2 실행시 호출되는 메서드
        print("'==' 연산자 호출")
        return self.length == other.length
    
    ##__del__(self) : 소멸자 : 객체가 제거될 때 호출되는 메서드(자바에서는 자동으로 제거해주기때문에 사실상 없다.)
    def __del__(self):
        print(self.length,"길이 선이 제거되었습니다.")
        ##해당 객체가 없어졌을 때, 자동으로 호출해주는 메서드임
    
        
myline1 = Line(200) #__init__ 호출. 생성자 : 객체생성시 호출되는 메서드
myline2 = Line(100)

print(myline1) #__repr__(self): 자바의 toString의 기능을 한다.
print(myline2)

#1)
print("두 선의 길이의 합:",myline1+myline2) #파이썬은 '객체+객체' 시 __add__호출하도록 약속돼있다.
print("두 선의 길이의 합:",myline1.__add__(myline2))

##연산자로 해도 되지만 직접 함수로 해도 상관없다.

#2)
if myline1 < myline2:  ##비교를 하려면 Line class안에 __lt__가 있어야 함.  "<", ">"
    print("myline2 선이 더 길다")
elif myline1 == myline2 :     ##                            __eq__가 있어야 함. "=="
    print("myline1과 2의 선 길이가 같다")
elif myline1 > myline2:
    print("myline1 선이 더 길다")

    
#3) 
if myline1.__lt__(myline2): 
    print("myline2 선이 더 길다")
elif myline1.__eq__(myline2) :
    print("myline1과 2의 선 길이가 같다")
elif myline1.__gt__(myline2):
    print("myline1 선이 더 길다")
print("프로그램 종료")
# 생성된 모든 객체들이 제거됨.--> 소멸자가 자동으로 호출됨.

15. class _6

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 15:48:34 2021

@author: 2016005

classex6.py : 파이썬의 추상메서드
                부모클래스의 멤버 메서드를 자손클래스에서 반드시 구현.pass
"""

class SuperClass:

    def method(self): #추상메서드
        raise NotImplementedError  ##반드시 오버라이딩 해라.
        #raise NotImplementedError: 오버라이딩 안하면 예외를 발생시키겠다
        
#SubClass 클래스 생성하기. SuperClass의 하위클래스. 부모와 같은 멤버를 가지도록.
class SubClass1(SuperClass):
    #pass
    
    def method(self):
        print("SubClass1에서 method 함수를 오버라이딩 함")

####
sub1 = SubClass1()
sub1.method()




'''
클래스 < 모듈 < 패키지
'''

16. mod_1

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:00:41 2021

@author: 2016005

mod.py : 모듈 구현하기

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

def sub(a, b):
    return a - b


17. mod_2

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:12:00 2021

@author: 2016005

mod2.py  :  모듈로 import도 되고. 
            실행도 됨.
            
            if __name__=="__main__": 가 있으면
            ==>모듈로 실행될때는 하위 메서드를 실행하지 말아라.
            
"""

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

'''
 __name__  :   이 mod2.py파일을 실행할 경우 자동으로 __name__에는 "__main__"라는 값이 저장된다.
'''

##'모듈로 쓰일때는 이부분 좀 건너뛰어.'라는 말.
if __name__=="__main__":  
 ## __name__라는 변수가 main이니?  // mod2.py 파일이 직접 실행될 때는 print...를 실행함./모듈로쓰일땐 실행ㄴㄴ
    print(add(3,4))
    print(sub(4,2))
    
    

18. mod_3

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:03:01 2021

@author: 2016005

modex1.py : mod 모듈 사용하기
"""
import mod
import mod2

print("mod 모듈",mod.add(3, 4))
print("mod 모듈",mod.sub(3, 4))

print("mod2 모듈", mod2.add(3,4))
print("mod2 모듈", mod2.sub(3,4))

19. mod_4

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:04:40 2021

@author: 2016005

modex2.py : from ... import 사용하기
"""

from mod import add

print(add(3,4))
#print(sub(4,2))   얘는 사용할 수 없다. 이유는? add만 가져왔고, sub는 안가져왔음.

20. mod_5

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:09:49 2021

@author: 2016005

modex3.py :
"""

#mod 모듈에서 add, sub 함수를 가져오기
from mod import add, sub

print(add(3,4))  ## 그냥  함수 이름 자체로 호출해버렸음.    OOO.add 가 아님.
print(sub(4,2))


#모듈을 분리시켜서 클래스로 가져올수도있고, 함수로도 가져올 수 있고 그렇다.

=========================test========================

1. test_1

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:38:04 2021

@author: 2016005

test0208_1

1.  다음 코드를 실행 했을 경우 결과를 예측하시오. 출력된 결과의 이유를 설명하시오

a = "Life is too short, you need python"

if "wife" in a:
    print("wife")

elif "python" in a and "you" not in a:
    print("python")

elif "shirt" not in a:
    print("shirt")

elif "need" in a: 
    print("need")

else: 
    print("none")


"""

a = "Life is too short, you need python"

if "wife" in a:
    print("wife")
elif "python" in a and "you" not in a:
    print("python")
elif "shirt" not in a:
    print("shirt")
elif "need" in a: 
    print("need")
else: 
    print("none")
'''
#결과 : shirt
#원인 : 
    if "wife" in a:
        print("wife")  ==> wife가 a안에 없음
    
    elif "python" in a and "you" not in a:
        print("python") ==> 두 개의 조건이 참인 경우에 실행됨
    
    elif "need" in a: 
        print("need")
    else: 
        print("none")    ==> 앞에서 shirt출력하고 끝남.
'''

2. test_2

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:44:07 2021

@author: 2016005
test0208_2
2. 입력된 자연수가 홀수인지 짝수인지 판별해 주는 함수를 람다식을 이용하여 작성해 보자.
"""

num = int(input("정수숫자입력"))

evenodd = lambda num : num%2==0

print("짝수인가?",(lambda num : num%2==0)(num) )

3. test_3

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:49:11 2021

@author: 2016005

test0208_3

3. Rect 클래스 구현하기
   Rect 클래스는 가로,세로를 멤버변수로.  넓이와 둘레를 구하는 멤버 함수가진다.
   클래스의 객체를 print 시 : (가로,세로),넓이:xxx,둘레:xxx가 출력되도록 한다.
"""

class Rect:
    width = 0
    height = 0
    
    def __init__(self, w,h):
        self.width = w
        self.height = h
    
    def __repr__(self):
        return "(가로=%d, 세로=%d), 넓이=%3d, 둘레=%3d" % (self.width, self.height, self.width*self.height, self.width*2 + self.height*2)
    
print(Rect(20,30))

4. test_4

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:54:25 2021

@author: 2016005

test0208_4

4. 화씨온도= (( 9 / 5) * 섭씨온도) + 32 인 경우, 섭씨 -20 ~ 50 도까지를 화씨 온도로 변경하여 작성하기
"""
import math

for t in range(-20,50+1):
    print("섭씨:", t, "도 = 화씨:", math.floor(((9/5)*t)+32), "도")

5. test_5

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  8 16:58:28 2021

@author: 2016005

test0208_5

5. 1 부터 1000 까지의 홀수의 합계 계산시 최초로 1000이 넘는 숫자는 구하는 프로그램을 작성해 보자.
"""
sum = 0
for i in range(1,1000+1, 2):
    sum+=i
    if(sum >1000):
        print("현재합계: ",sum,", 더했을 때 최초로 1000이 넘는 수: ",i)
        break
반응형

'공부중 > python' 카테고리의 다른 글

파이썬 입문 7일차  (0) 2021.02.18
파이썬 입문 6일차  (0) 2021.02.18
파이썬 입문 5일차  (0) 2021.02.15
파이썬 입문 2일차  (0) 2021.02.08
파이썬 입문 1일차  (0) 2021.02.08