[제로베이스 데이터 취업 스쿨 15기] 2주차 (Python 중급/문제풀이)

김지환·2023년 5월 4일
0
post-thumbnail

2주차: 5/8/2023 - 5/14/2023


Function


  • Re-usability
  • def keyword + function name + : + code block
  • Call: function name + ()
    - e.g. addCal()

Built-in function

numbers = [1, 2, 3, 4, 5]
numbers.sort()
numbers.reverse()
numbers.clear()

User-defined function

def printUserName(name):
	print(f'Hello, {name}')

Function within function

def fun1():
    print('Call fun1!')
    fun2()
    print('Run after calling fun2!')

def fun2():
    print('Call fun2!')
    fun3()

def fun3():
    print('Call fun3!')

fun1()

Parameters and arguments

  • Numbers of arguments and parameters need to match
def greet(customer): # parameter
    print('Hello {}.'.format(customer))

greet('Jason') # argument
  • Use * for undetermined number of parameters
def printNumber(*numbers):
    for number in numbers:
        print(number, end='')
    print()

Return

  • Returns the result of the function through function call
  • Function ends at return
def calculator(n1, n2):
    result = n1 + n2

    return result

returnValue = calculator(20, 10)
print(f'returnValue: {returnValue}')

Global and local variables

  • Global variable
    - Declared outside a function and can be used anywhere
    - Cannot be changed within a function
  • Local variable
    - Declared and only used within a function
  • global keyword
    - Can change the value of a global variable within a function
totalVisit = 0

def countTotalVisit():
    global totalVisit

    totalVisit = totalVisit + 1
    print(f'Cumulative number of tourists: {totalVisit}')

countTotalVisit()
countTotalVisit()
countTotalVisit()
countTotalVisit()
countTotalVisit()

Nested function

  • Inner function cannot be called outside outer function
def out_function():
    print('out_function called!!')

    def in_function():
        print('in_function called!!')

    in_function()


out_function()

lambda keyword

def calculator(n1, n2):
    return n1 + n2


returnValue = calculator(10, 20)
print(f'returnValue: {returnValue}')

calculator = lambda n1, n2: n1 + n2
returnValue = calculator(10, 20)
print(f'returnValue: {returnValue}')

Exercises

def calFun():
    n1 = int(input('Input n1: '))
    n2 = int(input('Input n2: '))

    print(f'n1 * n2 = {n1 * n2}')
    print(f'n1 / n2 = {round(n1 / n2, 2)}')

calFun()
import random

def getOddRandomNumber():

    while True:
        rNum = random.randint(1, 100)
        if rNum % 2 != 0:
            break

    return rNum


print(f'returnValue: {getOddRandomNumber()}')
# recursion

def formattedNumber(n):
    return format(n, ',')


def recursionFunction(n):

    if n == 1:
        return n

    return n * recursionFunction(n - 1)


inputNumber = int(input('input number: '))
print(formattedNumber(recursionFunction(inputNumber)))
# Arithmetic sequence: a_n = a_1 + (n-1) * d
# Arithmetic sum: s_n = n * (a_1 + a_n) / 2


def sequenceCal2(n1, d, n):

    valueN = 0; sumN = 0

    i = 1
    while i <= n:

        valueN = n1 + (n - 1) * d
        sumN = int(n * (n1 + valueN) / 2)
        print(f'Value of {i}th term: {valueN}')
        print(f'Value of the sum of {i} terms: {sumN}')

        i += 1
        continue


inputN1 = int(input('Input first term: ')) # first term
inputD = int(input('Input common difference: ')) # common difference
inputN = int(input('Input number of terms: ')) # number of terms

sequenceCal2(inputN1, inputD, inputN)
# Geometric series: a_n = a_1 * r^(n - 1)
# Geometric sum: s_n = a_1 * (1 - r^n) / (1 - r)

def sequenceCal2(n1, r, n):

    valueN = 0; sumN = 0

    i = 1
    while i <= n:

        valueN = n1 * (r ** (n - 1))
        sumN = n1 * ((1 - r ** n) / (1 - r))
        print(f'Value of {i}th term: {valueN}')
        print(f'Value of the sum of {i} terms: {sumN}')

        i += 1
        continue


inputN1 = int(input('Input first term: '))
inputR = int(input('Input common ratio: '))
inputN = int(input('Input number of terms: '))

sequenceCal2(inputN1, inputR, inputN)

print(valueN)
print(sumN)

Module


  • A python file that contains python code (variables, functions, classes, etc.)
  • Intended to be imported into scripts and other modules
  • Internal, external, user-defined
import random

rNums = random.sample(range(1, 101), 10)
print(f'rNums: {rNums}')

Creating a module

import random

def getLottoNumbers():
    result = random.sample(range(1, 45), 6)

    return result

Importing a module

import lottoMachine

result = lottoMachine.getLottoNumbers()
print(f'lotto numbers: {result}')
  • Use as to shorten the module name
import calculator as cal
  • Use from to use only certain functions
from calculator import add

Global variable __name__

  • Imported module: __name__ stores the name of the module
def cmToMm(n):
    return round(n * 10, 3)

def cmToInch(n):
    return round(n * 0.393, 3)

def cmToM(n):
    return round(n * 0.01, 3)

def cmToFt(n):
    return round(n * 0.032, 3)

if __name__ == '__main__':
    print(f'10cm: {cmToMm(10)}mm')
    print(f'10cm: {cmToInch(10)}inch')
    print(f'10cm: {cmToM(10)}m')
    print(f'10cm: {cmToFt(10)}ft')
  • Main module: __name__ stores __main__
import unitConversion as uc

if __name__ == '__main__':
    inputNumber = int(input('Input length (cm): '))

    returnValue = uc.cmToMm(inputNumber)
    print(f'returnValue: {returnValue}mm')

    returnValue = uc.cmToInch(inputNumber)
    print(f'returnValue: {returnValue}inch')

    returnValue = uc.cmToM(inputNumber)
    print(f'returnValue: {returnValue}m')

    returnValue = uc.cmToFt(inputNumber)
    print(f'returnValue: {returnValue}feet')

Package

  • Group of modules
from CalculatorForInt import addCal
print(addCal.add(10, 20))

from CalculatorForFloat import addCal
print(addCal.add(10, 20))
  • site-packages
    - Its modules can be used outside the directory
def divisor(n):

    result = []
    for i in range(1, n + 1):
        if n % i == 0:
            result.append(i)

    return result


def prime_number(n):

    result = []

    for i in range(2, n): # 2, 3, 4, ... n
        prime = True
        for j in range(2, i):
            if i % j == 0:
                prime = False
        if prime:
            result.append(i)
    return result
from divisor_pac import divisor_mod as dm

print(f'Divisor of 10: {dm.divisor(10)}')
print(f'Prime numbers smaller than 50: {dm.prime_number(50)}')

Math module

import math

# absolute value
print(f'math.fabs(-10): {math.fabs(-10)}')
print(f'math.fabs(-0.12895): {math.fabs(-0.12895)}')

# ceiling
print(f'math.ceil(5.21): {math.ceil(5.21)}')
print(f'math.ceil(-5.21): {math.ceil(-5.21)}')

# floor
print(f'math.floor(5.21): {math.floor(5.21)}')
print(f'math.floor(-5.21): {math.floor(-5.21)}')

# truncate
print(f'math.trunc(5.21): {math.trunc(5.21)}')
print(f'math.trunc(-5.21): {math.trunc(-5.21)}')

# GCD
print(f'math.gcd(14, 21): {math.gcd(14, 21)}')

# factorial
print(f'math.factorial(10): {math.factorial(10)}')

# SQRT
print(f'math.sqrt(4): {math.sqrt(4)}')
print(f'math.sqrt(12): {math.sqrt(12)}')

Random module

random.randint, random.sample

Time module

import time

lt = time.localtime()
print(f'time.localtime(): {lt}')

print(f'lt.tm_year: {lt.tm_year}')
print(f'lt.tm_mon: {lt.tm_mon}')
print(f'lt.tm_mday: {lt.tm_mday}')
print(f'lt.tm_hour: {lt.tm_hour}')
print(f'lt.tm_min: {lt.tm_min}')
print(f'lt.tm_sec: {lt.tm_sec}')
print(f'lt.tm_wday: {lt.tm_wday}')

Exercises

# Module: discount

def calculatorTotalPrice(gs):

    if len(gs) <= 0:
        print('Item is not available')
        return

    rate = 25
    totalPrice = 0

    # Dictionary
    rates = {1:5, 2:10, 3:15, 4:20}

    if len(gs) in rates:
        rate = rates[len(gs)]

    for g in gs:
        totalPrice += g * (1 - rate * 0.01)

    return [rate, int(totalPrice)]

def formattedNumber(n):
    return format(n, ',')
import discount as dc

if __name__ == '__main__':

    flag = True
    gs = []

    while flag:

        selectNumber = int(input('1. Buy, 2. Close '))

        if selectNumber == 1:
            itemPrice = int(input('Enter the price of the item: '))
            gs.append(itemPrice)

        elif selectNumber == 2:
            result = dc.calculatorTotalPrice(gs)
            flag = False

    print(f'Discount rate: {result[0]}')
    print(f'Total price: {dc.formattedNumber(result[1])} KRW')
# Module: lotto

import random

userNums = []; randNums = []; collNums = []
randBonus = 0

# Setter
def setUserNums(ns):
    global userNums
    userNums = ns

def getUserNums():
    return userNums

def setRandNums():
    global randNums
    randNums = random.sample(range(1, 46), 6)

def getRandNums():
    return randNums

def setBonusNum():
    global randBonusNum

    while True:
        randBonusNum = random.randint(1, 45)
        if randBonusNum not in randNums:
            break

def getBonusNum():
    return randBonusNum

def lottoResult():
    global userNums
    global randNums
    global collNums

    collNums = []
    for un in userNums:
        if un in randNums:
            collNums.append(un)

    if len(collNums) == 6:
        print('First place')
        print(f'Number: {collNums}')

    elif len(collNums) == 5 and randBonusNum in userNums:
        print('Second place)')
        print(f'Number: {collNums}, Bonus number: {randBonusNum}')

    elif len(collNums) == 5:
        print('Third place')
        print(f'Number: {collNums}')

    elif len(collNums) == 4:
        print('Fourth place')
        print(f'Number: {collNums}')

    elif len(collNums) == 3:
        print('Fifth place')
        print(f'Number: {collNums}')

    else:
        print('Too bad')
        print(f'Machine number: {randNums}')
        print(f'Bonus number: {randBonusNum}')
        print(f'User number: {userNums}')
        print(f'Correct number: {collNums}')

def startLotto():
    n1 = int(input('Input number (1 - 45): '))
    n2 = int(input('Input number (1 - 45): '))
    n3 = int(input('Input number (1 - 45): '))
    n4 = int(input('Input number (1 - 45): '))
    n5 = int(input('Input number (1 - 45): '))
    n6 = int(input('Input number (1 - 45): '))
    selectNums = [n1, n2, n3, n4, n5, n6]

    setUserNums(selectNums)
    setRandNums()
    setBonusNum()

    lottoResult()
import lotto as lt

lt.startLotto()
# Module: permutation

def getPermutation(n, r, logPrint = True):

    result = 1
    for n in range(n, n-r, -1):
        if logPrint: print('n: {}'.format(n))
        result = result * n

    return result

from itertools import permutations

def getPermutations(ns, r):

    pList = list(permutations(ns, r))
    print(f'{len(ns)}P{r}: {len(pList)}')

    for n in permutations(ns, r):
        print(n, end=', ')
import permutation as pt

numN = int(input('Input numN: '))
numR = int(input('Input numR: '))

print(f'{numN}P{numR}: {pt.getPermutation(numN, numR, logPrint = False)}')
# Packages: arithmetic, shape

from arithmetic import basic_operation as bo
from arithmetic import developer_operation as do

from shape import triangle_square_area as tsa
from shape import circle_area as ca

inputNumber1 = float(input('Input first number: '))
inputNumber2 = float(input('Input second number: '))

print(f'{inputNumber1} + {inputNumber2} = {bo.add(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} - {inputNumber2} = {bo.sub(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} * {inputNumber2} = {bo.mul(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} / {inputNumber2} = {bo.div(inputNumber1, inputNumber2)}')

print(f'{inputNumber1} % {inputNumber2} = {do.mod(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} // {inputNumber2} = {do.flo(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} ** {inputNumber2} = {do.exp(inputNumber1, inputNumber2)}')

inputWidth = float(input('Input width: '))
inputHeight = float(input('Input height: '))

print(f'Area of the triangle: {tsa.calTriangleArea(inputWidth, inputHeight)}')
print(f'Area of the square: {tsa.calSquareArea(inputWidth, inputHeight)}')

inputRadius = float(input('Input radius: '))

print(f'Area of the circle: {ca.calCircleArea(inputRadius)}')

Object-oriented programming


  • object = attribute + function
  • Class: attributes and functions are defined -> creates objects
  • Codes can be reused
  • Good for modularization
  • Low coupling preferred

Class

  • class keyword + attributes (variables) + functions
  • First letter of class keyword capitalized
  • Method __init__ initializes objects
  • Constructors of class are called to construct objects
  • Numbers of parameters and arguments need to be matched
  • Values of parameters initialize attributes of objects
  • Objects are constructed -> memory addresses of objects are stored in reference variables
  • Object reference:
    - Functions of objects can be called and attributes of objects can be changed via reference variables
class Airplane:

    # attributes: color, length, weight
    def __init__(self, color, length, weight):
        self.color = color
        self.length = length
        self.weight = weight

    # functions: landing, takeoff, printAirplaneInfo
    def doLand(self):
        print('Land!')

    def doTakeoff(self):
        print('Take off!')

    def printAirplaneInfo(self):
        print(f'self.color: {self.color}')
        print(f'self.length: {self.length}')
        print(f'self.weight: {self.weight}')

# construct 5 airplane objects and store in reference variables
airplane1 = Airplane("red", 100, 50)
airplane2 = Airplane("blue", 200, 50)
airplane3 = Airplane("yellow", 300, 50)
airplane4 = Airplane("green", 400, 50)
airplane5 = Airplane("gray", 500, 50)

airplane1.printAirplaneInfo()
airplane2.printAirplaneInfo()
airplane3.printAirplaneInfo()
airplane4.printAirplaneInfo()
airplane5.printAirplaneInfo()

airplane1.doLand()
airplane1.doTakeoff()

Changing attributes of the object

class Calculator:

    # attributes
    def __init__(self):
        self.number1 = 0
        self.number2 = 0
        self.result = 0

    # functions
    def add(self):
        self.result = self.number1 + self.number2
        return self.result

    def sub(self):
        self.result = self.number1 - self.number2
        return self.result

    def mul(self):
        self.result = self.number1 * self.number2
        return self.result

    def div(self):
        self.result = self.number1 / self.number2
        return self.result

calculator = Calculator()
calculator.number1 = 1
calculator.number2 = 2
print(f'calculator.add(): {calculator.add()}')
print(f'calculator.sub(): {calculator.sub()}')
print(f'calculator.mul(): {calculator.mul()}')
print(f'calculator.div(): {calculator.div()}')

Object and memory

  • Constructor has the same name as the class
  • Memory address of the constructed object is stored in the reference variable
scores = [int(input('Input Korean scores: ')),
          int(input('Input English scores: ')),
          int(input('Input Math scores: '))]

print(scores)

copyScores = scores.copy()  # deep copy: objects are actually copied

for idx, score in enumerate(copyScores):
    result = score * 1.1
    copyScores[idx] = 100 if result > 100 else result

print(f'Previous average: {round(sum(scores) / len(scores), 2)}')
print(f'Current average: {round(sum(copyScores) / len(copyScores), 2)}')
  • shallow copy: object address is copied, not the object
  • deep copy: object itself is copied, constructing another object
import copy

scores = [9, 8, 5, 7, 6, 10]
scoresCopy = []

# shallow copy
scoresCopy = scores
print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

# deep copy 1
for s in scores:
    scoresCopy.append(s)

print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

# deep copy 2
scoresCopy.extend(scores)
print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

# deep copy 3
scoresCopy = scores.copy()
print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

# deep copy 4
scoresCopy = scores[:]
print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

Class inheritance

  • Child class can use all functions of parent class
class CalculatorSuper:

    def add(self, n1, n2):
        return n1 + n2

    def sub(self, n1, n2):
        return n1 - n2

# CalculatorChild inherits from CalculatorSuper
class CalculatorChild(CalculatorSuper):

    def mul(self, n1, n2):
        return n1 * n2

    def div(self, n1, n2):
        return n1 / n2

myCalculator = CalculatorChild()

print(myCalculator.add(10, 20))
print(myCalculator.sub(10, 20))
print(myCalculator.mul(10, 20))
print(myCalculator.div(10, 20))
  • Multiple inheritance
    - More than two classes can be inherited
class BasicCalculator:

    def add(self, n1, n2):
        return n1 + n2

    def sub(self, n1, n2):
        return n1 - n2

    def mul(self, n1, n2):
        return n1 * n2

    def div(self, n1, n2):
        return n1 / n2


class DeveloperCalculator:

    def mod(self, n1, n2):
        return n1 % n2

    def flo(self, n1, n2):
        return n1 // n2

    def exp(self, n1, n2):
        return n1 ** n2


class NewCalculator(BasicCalculator, DeveloperCalculator):

    def __init__(self):
        pass


cal = NewCalculator()

print(f'cal.add(10, 20): {cal.add(10, 20)}')
print(f'cal.sub(10, 20): {cal.sub(10, 20)}')
print(f'cal.mul(10, 20): {cal.mul(10, 20)}')
print(f'cal.div(10, 20): {cal.div(10, 20)}')

print(f'cal.mod(10, 20): {cal.mod(10, 20)}')
print(f'cal.flo(10, 20): {cal.flo(10, 20)}')
print(f'cal.exp(2, 5): {cal.exp(2, 5)}')

Constructor

  • Calling constructor: Calculator() => __init__ called automatically
  • __init__ intializes attributes
  • super() initializes the attributes of parent class
class P_Class:

    def __init__(self, pNum1, pNum2):

        print('[P_Class] __init__() called!')

        self.pNum1 = pNum1
        self.pNum2 = pNum2

class C_Class(P_Class):

    def __init__(self, cNum1, cNum2):
        print('[C_Class] __init__() called!')

        # # Method 1
        # P_Class.__init__(self, cNum1, cNum2)

        # Method 2
        super().__init__(cNum1, cNum2)

        self.cNum1 = cNum1
        self.cNum2 = cNum2

cls = C_Class(10, 20)

Overriding

  • Child class overrides the method of parent class
class TriangleArea:

    def __init__(self, w, h):
        self.width = w
        self.height = h

    def printTriangleAreaInfo(self):
        print(f'self.width: {self.width}')
        print(f'self.height: {self.height}')

    def getArea(self):
        return self.width * self.height / 2

class NewTriangleArea(TriangleArea):

    def __init__(self, w, h):
        super().__init__(w, h)

    def getArea(self):
        return str(super().getArea()) + 'cm²'

ta = NewTriangleArea(7, 5)
ta.printTriangleAreaInfo()
triangleArea = ta.getArea()
print(f'triangleArea = {triangleArea}')

Abstract class

  • Parent class forces child class to implement a certain method
    - s.t. the method can be used differently for different purposes
from abc import ABCMeta
from abc import abstractmethod

class Calculator(metaclass=ABCMeta):

    @abstractmethod
    def add(self, n1, n2):
        pass

    @abstractmethod
    def sub(self, n1, n2):
        pass

    @abstractmethod
    def mul(self, n1, n2):
        pass

    @abstractmethod
    def div(self, n1, n2):
        pass


class DeveloperCalculator(Calculator):

    def add(self, n1, n2):
        print(n1 + n2)

    def sub(self, n1, n2):
        print(n1 - n2)

    def mul(self, n1, n2):
        print(n1 * n2)

    def div(self, n1, n2):
        print(n1 / n2)

    def mod(self, n1, n2):
        print(n1 % n2)

    def flo(self, n1, n2):
        print(n1 // n2)

cal = DeveloperCalculator()
cal.add(2, 5)
cal.sub(2, 5)
cal.mul(2, 5)
cal.div(2, 5)
cal.mod(2, 5)
cal.flo(2, 5)

Exercises

class MidExam:

    # attributes
    def __init__(self, s1, s2, s3):
        print('[MidExam] __init__()')

        self.mid_kor_score = s1
        self.mid_eng_score = s2
        self.mid_mat_score = s3

    # functions
    def printScores(self):
        print(f'mid_kor_score: {self.mid_kor_score}')
        print(f'mid_eng_score: {self.mid_eng_score}')
        print(f'mid_mat_score: {self.mid_mat_score}')

class EndExam(MidExam):

    # attributes
    def __init__(self, s1, s2, s3, s4, s5, s6):
        print('[EndExam] __init__()')

        super().__init__(s1, s2, s3)

        self.end_kor_score = s4
        self.end_eng_score = s5
        self.end_mat_score = s6

    # functions
    def printScores(self):
        super().printScores()
        print(f'end_kor_score: {self.end_kor_score}')
        print(f'end_eng_score: {self.end_eng_score}')
        print(f'end_mat_score: {self.end_mat_score}')

    def getTotalScore(self):
        total = self.mid_kor_score + self.mid_eng_score + self.mid_mat_score
        total += self.end_kor_score + self.end_eng_score + self.end_mat_score

        return total

    def getAverageScore(self):
        return self.getTotalScore() / 6

exam = EndExam(85, 90, 88, 75, 85, 95)
exam.printScores()

print(f'Total: {exam.getTotalScore()}')
print(f'Average: {round(exam.getAverageScore(), 2)}')
# classes: Member, MemberRepository

class Member:
    def __init__(self, i, p):
        self.id = i
        self.pw = p


class MemberRepository:

    def __init__(self):
        self.members = {}


    def addMember(self, m):
        self.members[m.id] = m.pw


    def loginMember(self, i, p):
        isMember = i in self.members

        if isMember and self.members[i] == p:
            print(f'{i}: log-in successful')

        else:
            print(f'{i}: log-in failed')


    def removeMember(self, i, p):
        del self.members[i]


    def printMembers(self):
        for mk in self.members.keys():
            print(f'ID: {mk}')
            print(f'PW: {self.members[mk]}')
import member as mb

mems = mb.MemberRepository()

for i in range(3):
    mId = input('Input ID: ')
    mPw = input('Input Password: ')
    mem = mb.Member(mId, mPw)
    mems.addMember(mem)

mems.printMembers()

mems.loginMember('abc@gmail.com', '1234')
mems.loginMember('def@gmail.com', '5678')
mems.loginMember('ghi@gmail.com', '9012')

mems.removeMember('abc@gmail.com', '1234')

mems.printMembers()

Exceptions


  • Detected during execution
  • Syntactically correct but unexpected problem
  • Exception-related classes inherit from Exception class
  • e.g. ArithmeticError, EnvironmentError, LookupError, SyntaxError
  • e.g. ZeroDivisionError, IOError, IndexError, IndentationError
  • Exception handling: try, except
n = 1
while n < 6:

    try:
        num = int(input('input number: '))
    except:
        print('Exception raised!')
        continue

    nums.append(num)
    n += 1

print(f'nums = {nums}')
  • Exception handling: try, except, else
    - else: executed if \nexists exception
evenList = []; oddList = []; floatList = []

n = 1
while n < 6:

    try:
        num = float(input('input number: '))

    except:
        print('exception raised!')
        print('input number again!')
        continue

    else:
        if num - int(num) != 0:
            print('float number!')
            floatList.append(num)
        else:
            if num % 2 == 0:
                print('even number')
                evenList.append(num)
            else:
                print('odd number!')
                oddList.append(num)

    n += 1

print(f'evenList: {evenList}')
print(f'oddList: {oddList}')
print(f'floatList: {floatList}')
  • Exception handling: try, except, else, finally
    - finally: executed regardless of exception
evenList = []; oddList = []; floatList = []; dataList = []

n = 1
while n < 6:

    try:
        data = input('input number: ')
        floatNum = float(data)

    except:
        print('exception raised!')
        print('not a number!')
        continue

    else:
        if floatNum - int(floatNum) != 0:
            print('float number!')
            floatList.append(floatNum)
        else:
            if floatNum % 2 == 0:
                print('even number!')
                evenList.append(int(floatNum))
            else:
                print('odd number!')
                oddList.append(int(floatNum))

        n += 1

    finally:
        dataList.append(data)

print(f'evenList: {evenList}')
print(f'oddList: {oddList}')
print(f'floatList: {floatList}')
print(f'dataList: {dataList}')
  • except Exception as e
    - Shows which exception was raised
  • raise Exception()
    - Forces an exception to be raised with a customizable message
def sendSMS(msg):

    if len(msg) > 10:
        raise Exception('Too many words! Change it to MMS!', 1)

    else:
        print('Send SMS')

def sendMMS(msg):

    if len(msg) <= 10:
        raise Exception('Too few words! Change it to SMS!', 2)

    else:
        print('Send MMS')

msg = input('input message: ')

try:
    sendSMS(msg)

except Exception as e:
    print(f'e: {e.args[0]}')
    print(f'e: {e.args[1]}')

    if e.args[1] == 1:
        sendMMS(msg)
    elif e.args[1] == 2:
        sendSMS(msg)
  • User-defined exception class
    - Inherits from the Exception class
class PasswordLengthShortException(Exception):

    def __init__(self, str):
        super().__init__(f'{str}: shorter than 5 letters')

class PasswordLengthLongException(Exception):

    def __init__(self, str):
        super().__init__(f'{str}: longer than 10 letters')

class PasswordWrongException(Exception):
    def __init__(self, str):
        super().__init__(f'{str}: wrong password')

adminPw = input('input admin password: ')

try:

    if len(adminPw) < 5:
        raise PasswordLengthShortException(adminPw)

    elif len(adminPw) > 10:
        raise PasswordLengthLongException(adminPw)

    elif adminPw != 'admin1234':
        raise PasswordWrongException(adminPw)

    elif adminPw == 'admin1234':
        print('correct password')

except PasswordLengthShortException as e1:
    print(e1)

except PasswordLengthLongException as e2:
    print(e2)

except PasswordWrongException as e3:
    print(e3)

Text file


  • open()
    - w: write-only (replace)
    - a: write-only (append) (used for logs)
    - x: write-only (error if \exists file)
    - r: read-only (error if \nexists file)
  • read()
  • write()
    - Replaces all existing text if any
  • close()
import time

lt = time.localtime()

dateStr = '[' + time.strftime('%m-%d-%Y %I:%M:%S %p') + '] '

todaySchedule = input('Today\'s schedule: ')

file = open('C:/pythonTxt/test.txt', 'w')
file.write(dateStr + todaySchedule)
file.close()
def writePrimeNumber(n):

    file = open(uri + 'prime_numbers.txt', 'a')
    # write() only takes in strings
    file.write(str(n))
    file.write('\n')
    file.close()

inputNumber = int(input('Input an integer > 0: '))

for number in range(2, (inputNumber + 1)):
    flag = True
    for n in range(2, number):
        if number % n == 0:
            flag = False
            break

    if flag:
        writePrimeNumber(number)
  • with ... as: omit close()
import random

uri = 'C:/pythonTxt/'

def writeNumbers(nums):
    for idx, num in enumerate(nums):
        with open(uri + 'lotto.txt', 'a') as f:
            if idx < len(nums) - 2:
                f.write(str(num) + ', ')
            elif idx == len(nums) - 2:
                f.write(str(num))
            elif idx == len(nums) - 1:
                f.write('\n')
                f.write('Bonus: ' + str(num))
                f.write('\n')


rNums = random.sample(range(1, 46), 7)
print(f'rNums: {rNums}')

writeNumbers(rNums)
  • writelines()
    - Writes each item in the list or tuple onto the file
languages = ['c/c++', 'java', 'c#', 'python', 'javascript']
uri = 'C:/pythonTxt/'

with open(uri + 'languages.txt', 'a') as f:
    f.writelines(item + '\n' for item in languages)

with open(uri + 'languages.txt', 'r') as f:
    print(f.read())
  • readlines()
    - Reads all data and returns a list
    - Also reads \n
  • readline()
    - Reads each line and returns a string
uri = 'C:/pythonTxt/'

with open(uri + 'lans.txt', 'r') as f:
    lanList = f.readlines()

print(f'lanlist = {lanList}')
print(f'lanList type: {type(lanList)}')

with open(uri + 'lans.txt', 'r') as f:
    line = f.readline()

    while line != '':
        print(f'line: {line}', end='')
        # Read the next line
        line = f.readline()

Exercises

file = open('C:/pythonTxt/about_python.txt', 'r', encoding='UTF8')

str = file.read()
print(f'str: {str}')

file.close()

# Replace first two pythons
str = str.replace('Python', '파이썬', 2)
print(f'str: {str}')

file = open('C:/pythonTxt/about_python.txt', 'w')
file.write(str)
file.close()
uri = 'C:/pythonTxt/'

scoreDic = {'kor': 85, 'eng': 90, 'mat': 92, 'sci': 79, 'his': 82}
for key in scoreDic.keys():
    with open(uri + 'scoreDic.txt', 'a') as f:
        f.write(key + ':\t' + str(scoreDic[key]) + '\n')

# Dictionary
scoreDic = {'kor': 85, 'eng': 90, 'mat': 92, 'sci': 79, 'his': 82}
with open(uri + 'scores.txt', 'a') as f:
    print(scoreDic, file=f)
scoreDic = {}

uri = 'C:/pythonTxt/'
with open(uri + 'scores.txt', 'r') as f:
    line = f.readline()

    while line != '':
        tempList = line.split(':')
        scoreDic[tempList[0]] = int(tempList[1].strip('\n'))
        # Read the next line
        line = f.readline()

print(f'scoreDic: {scoreDic}')
profile
데이터 분석 공부하고 있습니다

0개의 댓글