Python - Week 2
Week 2
Python Functions
Python Functions and Lambda
# Declaring Function
# def function_name(parameter):
# code
def first_func(w):
print("hello, ", w)
word = "Goodboy"
# Call
first_func(word)
# Return
def return_func(w1):
value = "hello, " + str(w1)
return value
x = return_func('Goodboy2') # returns x as hello, Goodboy2
print(x) # hello, Goodboy2
# Multi Return
def func_mul1(x):
y1 = x * 10
y2 = x * 20
y3 = x * 30
return y1, y2, y3
x, y, z = func_mul1(3)
print(x, y, z)
# Tuple Return
def func_mul2(x):
y1 = x * 10
y2 = x * 20
y3 = x * 30
return (y1, y2, y3)
q = func_mul2(10)
print(q) # prints (100, 200, 300)
# List Return
def func_mul3(x):
y1 = x * 10
y2 = x * 20
y3 = x * 30
return [y1, y2, y3]
p = func_mul3(20)
print(p) # prints [200, 400, 600]
# Dictionary Return
def func_mul4(x):
y1 = x * 10
y2 = x * 20
y3 = x * 30
return {'v1': y1, 'v2': y2, 'v3': y3}
d = func_mul4(30)
print(d) # prints {'v1': y1, 'v2': y2, 'v3': y3}
# enumerate (returns a tuple of a number (starting from 0) and a value)
# *args, **kwargs (Unpacks the parameter of a function)
def args_func(*args): # Parameter name can be anything
for i, v in enumerate(args):
print('Result : {}'.format(i), v)
print('-----')
args_func('Lee')
args_func('Lee', 'Park')
args_func('Lee', 'Park', 'Kim')
# **kwargs allow dictionaries to be its parameters
def kwargs_func(**kwargs):
for v in kwargs.keys():
print("{}".format(v), kwargs[v])
print('-----')
kwargs_func(name1='Lee')
kwargs_func(name1='Lee', name2='Park')
kwargs_func(name1='Lee', name2='Park', name3='Cho')
# Lambda (Saves memory, improves readability, and concise code)
def func_final(x, y, func):
print(x * y * func(100, 100))
func_final(10, 20, lambda x,y:x * y) # immediately creates a function
# prints 2000000
Python Inputs
# Declaring an input
name = input("Enter Your Name : ")
grade = input("Enter Your Grade : ")
company = input("Enter Your Company Name : ")
# Opening a file with inputs
# go to the terminal (cmd)
# go to the folder where the code is placed
# open file
# Application
first_number = int(input("Enter number1 : "))
second_number = int(input("Enter number2 : "))
total = first_number + second_number
print("first_number + second_number : ", total)
# Application 2
print("FirstName - {0}, LastName - {1}".format(input("Enter first name : "), input("Enter second name : ")))
Classes, Modules, and Packages
Python Classes
class Dog: # inherit object
# class property
species = 'firstdog'
# produce reset / instance property
def __init__(self, name, age): # self is not a parameter
self.name = name
self.age = age
# instantiation
a = Dog("namil", 13)
b = Dog("Roy", 12)
# namespace
print('dog1', a.__dict__) # prints dog1 {'name': 'namil', 'age': 13}
print('dog2', b.__dict__)
# instance property confirmation
print('{} is {} and {} is {}'.format(a.name, a.age, b.name, b.age))
# prints namil is 13 and Roy is 12
if a.species == 'firstdog':
print('{0} is a {1}'.format(a.name, a.species)) # prints namil is a firstdog
# Understanding of Self
class SelfTest:
def func1():
print('Func1 called')
def func2(self):
print(self)
print('Func2 called')
SelfTest.func2(2) # prints 2, Func2 called
SelfTest.func2() # does not print anything
class Dog2:
species = 'firstdog'
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
return '{} is {} years old'.format(self.name, self.age)
def speak(self, sound):
return "{} says {}!".format(self.name, sound)
C = Dog2('namil', 4)
d = Dog2('Roy', 5)
# Call method
print(C.info()) # prints namil is 4 years old
# Call method
print(C.speak('Wal Wal')) # prints namil says Wal Wal
print(d.speak('Mung Mung')) # prints Roy says Mung Mung
Python Modules
# Assume the code below is written in a file called module_test.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
def power(x, y):
return x ** y
# use this piece of code in a different file using import
import module_test # allows you to use codes inside module_test.py
print(module_test.power(10, 3)) # prints 1000
Python Packages
# Assume that there are two files, sub1 and sub2, with a module in each of them, placed in a folder called sub.
# those modules placed in folders are packed, so therefore in order to import them you need to set a special call
import sub.sub1.module1 # opening folder sub, then sub1, then importing a module called module1.py
from sub.sub1 import module1 # does the same thing
from sub.sub1 import * # imports everything inside sub1
Exceptions
Error Types
# SyntaxError : Incorrect Grammar
print('error')
print('error'))
if True
pass
# NameError : No Reference
a = 10
b = 15
print(c)
# ZeroDivisionError
print(100 / 0)
# IndexError
x = [50, 70, 90]
print(x[1])
print(x[4])
print(x.pop())
print(x.pop())
print(x.pop())
print(x.pop())
# KeyError
dic = {'name': 'Shin', 'Age': '15', 'City': 'Pangyo'}
print(dic['hobby'])
print(dic.get('hobby'))
# EAFP Principle : Easier to ask for forgiveness than permission
# Writes code assuming that there is no error -> then fixes it when it occurs
# AttributeError : Incorrect usage of attributes in modules and classes
import time
print(time.time2())
# Valueerror
x = [10, 50, 90]
x.remove(50)
print(x)
x.remove(200)
# FileNotFoundError
f = open('test.txt')
# TypeError : Occur when calculation does not match data type
x = [1, 2]
y = (1, 2)
z = 'test'
print(x + y)
Dealing with Errors
# try : runs the code with possible errors
# except : excepts the error and runs the code below
# else : occurs when there is no error in try
# finally : always occur at the end
# raise : intentionally cause error
try:
z = 'Cho'
x = name.index(z)
print('{} Found it! {} in name'.format(z, x + 1))
except ValueError: # runs the code instead of causing error in the system
print('Not found it! - Occured ValueError!')
else:
print('OK! else.')
try:
z = 'Cho'
x = name.index(z)
print('{} Found it! {} in name'.format(z, x + 1))
except ValueError as e:
print(e)
print('Not found it! - Occured ValueError!')
else:
print('OK! else.')
finally:
print('Ok! Finally!')
try:
a = 'Park'
if a == 'Park':
print('Ok! Pass!')
else:
raise Valueerror
except ValueError:
print("Occured! Exception!")
else:
print('Ok! else!')
Python Functions
Since these are very important, functions will be posted on another post as well.
Built-in Functions
# absolute value
# abs()
print(abs(-3))
# all : iterable element availability (Outputs True, False)
# any : prints True if any of the variables is / are True
print(all([1, 2, 3])) # and
print(any([1, 2, 0])) # or
# chr : ASCII -> Character, ord : Character -> ASCII
print(chr(67))
print(ord('C'))
# enumerate : index + iterable object creation
for i, name in enumerate(['abc', 'bcd', 'efg']):
print(i, name) # i as number(index), name as object
# filter : creates iterable object as according to function code
def convert(x):
return abs(x) > 2
# extracts only True values
print(list(filter(convert, [1, -3, 2, 0, -5, 6])))
print(list(filter(lambda x: abs(x) > 2, [1, -3, 2, 0, -5, 6])))
# id : object id(reference)
print(id(int(5)))
print(id(4))
# len : length of an object
print(len('abcdefg'))
print(len([1, 2, 3, 4, 5, 6, 7]))
# max, min : maximum value, minimum value
print(max([1, 2, 3]))
print(max('python study'))
print(min([1, 2, 3]))
print(min('python study'))
# map : creates output iterable objects
def conv_abs(x):
return abs(x)
print(list(map(conv_abs,[1, -3, 2, 0, -5, 6])))
print(list(map(lambda x:abs(x), [1, 2, 3, -3, -2, -1])))
# power : powered value
print(pow(2, 10))
# range : extracts iterable object ranging from the values inputted
print(list(range(1, 10, 2)))
print(list(range(0, -15, -1)))
# round : rounding
print(round(6.5738, 2))
print(round(5.6))
# sorted : sorts the values in numeric and alphabetical order
print(sorted([6, 7, 4, 3, 1, 2]))
a = sorted([5, 6, 4, 6, 7, 2, 3, 1])
print(a)
print(sorted(['p', 'y', 'h', 'o', 't', 'n']))
# sum : adds all the values inputted
print(sum([6, 7, 8, 9, 10]))
print(sum(range(1, 101)))
# type : check data type
print(type(3))
print(type('eric'))
# zip : groups iterables into a tuple
print(list(zip([10, 20, 30], [2, 30, 40, 50])))
# prints [(10, 2), (20, 30), (30, 40)]
External Functions
Before using external functions, you have to import modules that include the function you want.
import sys # controls execution-related objects
print(sys.argv)
print(sys.path)
import pickle # writing object files
# writing
f = open("test.obj", 'wb')
obj = {1: 'python', 2: 'study', 3: 'basic'}
pickle.dump(obj, f)
f.close()
# reading
f = open("test.obj", 'rb')
data = pickle.load(f)
print(data)
f.close()
import os # environment variables, directories, operation properties
print(os.environ)
print(os.environ['USERNAME']) # prints the username of your window/mac
print(os.getcwd()) # current path
import time # time-related functions
print(time.time())
print(time.localtime(time.time()))
print(time.ctime()) # prints your current time of day, month, date, time, and year
# different formats
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
print(time.strftime('%H:%M:%S %Y-%m-%d ', time.localtime(time.time())))
# executes code every 1 second
for i in range(5):
print(i)
time.sleep(1)
import random # returns random numbers
print(random.random()) # prints random number between 0 and 1
# random int and random range
print(random.randint(1, 45)) # 1~45
print(random.randrange(1, 45)) # 1~44
# shuffle
d = [1, 2, 3, 4, 5]
random.shuffle(d)
print(d)
# random choice from a declared list
c = random.choice(d)
print(c)
import webbrowser # runs the web browser of your os
webbrowser.open("http://google.com")
webbrowser.open_new("http://google.com")
# runs two web pages with google
Thoughts
Using modules and functions, I could see the progress of my code is more and more productive. However, attending academies and listening to machine learning courses, I'm not 100% sure if I will be able to write another development blog next week. But my machine learning blog will be posted.