Python List, Tuple, Directory, functions, Modules

shin·2022년 3월 14일
0

Python Web

목록 보기
1/6
post-thumbnail

1. List

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

print(type(days)) # <class 'list'>

- Common Sequence Operations

print("Mon" in days) # True
print("Mon" not in days) # False

print("Today is " + days[0] + "day") # Today is Monday

print(days * 2) # double print

print(days[0:3]) # Print ['Mon', 'Tue', 'Wed']

print(len(days)) # 6

print(days.count("Mon")) # 1

- Mutable(가변) Sequence Types

days.append("Sun")
print(days) # ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

days.reverse()
print(days) # ['Sun', 'Sat', 'Fri', 'Thu', 'Wed', 'Tue', 'Mon']

days.clear()
print(len(days)) # 0

days.insert(0, "Tue")
days.insert(0, "Mon")
print(days) # ['Mon', 'Tue']

days.remove("Mon")
print(days) # ['Tue']

2. Tuple

  • Immutable Sequence

    nobody can change
    use only common operation

days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat")

print(type(days)) # <class 'tuple'>

3. Dictionary

info = {
  "first name" : "shin",
  "last name" : "yebin",
  "age" : 23,
  "korean" : True,
  "fav_song" : ["Dynamite", "Life goes on"]
}

print(info)

info["fav_coffee"] = "vanilla latte" # add
print(info["fav_coffee"]) # print value

del info["fav_song"] # delete
print(info)

4. Build in Functions (내장 함수)

참고 자료 : Python library functions

age = "23"
print(age)
print(type(age)) # str
n_age = int(age) # Type conversion
print(n_age)
print(type(n_age)) # int

5. Function

  • 파이썬에서는 함수를 만들 때 정의(define)한다고 표현함
  • 중괄호는 사용하지 않고 들여쓰기(tab)로 함수의 body를 구별할 수 있음
name = "yebin"

def say_hello(who):
 print("hello", who)

say_hello(name) # hello yebin
  • default value

함수로 전달한 인자 수와 필요한 인자 수가 다르면 오류가 발생할 수 있는데 이때 default 값을 정의하면 오류를 방지할 수 있음

def plus(a=0, b=0):
  print(a + b)

plus(5, 8) # 5 + 8 = 13
plus(5) # 5 + 0(default value) = 5

def say_hello(who="Anonymous"):
  print("hello", who)

say_hello() # hello Anonymous(default value)
  • Keyworded Arguments
def plus(a, b):
  return a + b

result = plus(b=30, a=20) # 순서를 신경쓰지 않아도 됨
print(result)
def say_hello(name, age):
  return f"Hello {name} you are {age} years old" # string formatting

hello = say_hello("yebin", "23")
print(hello)
def say_hello(name, age, are_from, fav_food):
  return f"Hello {name} you are {age} you are from {are_from} you like {fav_food}."

hello = say_hello(name = "yebin", age = "23", 
  fav_food = "kimchi", are_from = "colombia")

print(hello) 
# Hello yebin you are 23 you are from colombia you like kimchi.

6. Code Challenge - Calculator

print("< calculator >\nOperation : plus, minus, times, division, negation, power, reminder")

cal = True
a = 1.0
b = 1.0

def operation(symbol, a, b) :
  if symbol == "plus":
    return a + b
  elif symbol == "minus":
    return a - b
  elif symbol == "times":
    return a * b
  elif symbol == "division":
    return a / b
  elif symbol == "negation":
    return -a
  elif symbol == "power":
    return a ** b
  elif symbol == "reminder":
    return a % b

while cal :
  operation_symbol = input("Please enter the operation as a string : ")

  while operation_symbol not in ("plus", "minus", "times", "division", "negation", "power", "reminder") :
    operation_symbol = input("Please enter it again : ")

  if operation_symbol == "negation":
    while True:
      try:
        a = float(input("input number : "))
        break
      except ValueError:
        print("invalid number! try again")
  else:
    while True:
      try:
        a = float(input("input first number : "))
        b = float(input("input second number : "))  
        break
      except ValueError:
        print("invalid number! try again")

  print("result = ", operation(operation_symbol, a, b))

  exit = int(input("1 to continue, 0 to exit : "))
  if exit == 1 :
    cal = True
  else:
    cal = False
    print("exit")

7. Modules

- import math

import math # import module
    
print(math.ceil(1.2)) # 반올림 2
print(math.fabs(-1.2)) # 절대값 1.2

- 특정 함수만 import

from math import ceil, fsum # import only what you want

print(ceil(1.2)) # 2
print(fsum([1,2,3,4,5,6,7])) # 28.0
from math import fsum as sum # can change the name
    
print(sum([1,2,3,4,5,6,7])) # 28.0

- 다른 파일에 정의된 함수를 import

# calculator.py
    
def plus(a, b):
	return a + b
    
def minus(a, b):
	return a - b
# main.py
    
from calculator import plus, minus
    
print(plus(1, 2), minus(1, 2)) # 3 -1


출처 : Python으로 웹 스크래퍼 만들기 - nomadcoders

profile
Backend development

0개의 댓글