3 months note for starting Python

A note of good techniques to know as a beginner's stumbling block

Ternary operator

Formula: (variable) = (value when condition is True) if (condition) else (value when condition is False)

score = 100
result = "good" if score > 80 else "bad"
print(result) # good

else

It seems that the timing when the loop processing is finished can be taken

while


i = 0
while i < 3:
    print(i)
    i += 1
else:
    print("while, end")

for


for i in range(3):
    print(i)
else:
    print("for, end")

pass

do nothing. Use when you want to roughly decide only the outer frame

def say_hello():
    pass
print(say_hello()) # None

Reference How to use Python pass statement

format

Smarter if you can use it when multiple casts such as str (1) continue

text = 'name -> {0:>10s}\nscore -> {1:<10.2f}'.format('sato',30.2)
# name ->Display width:10, s:string, >:Right justified
# score ->Display width:10,2 digits after the decimal point, f:float, >:Left justified
print(text)
# name ->       sato
# score -> 30.20     

↓ This is also convenient

Zero padding by specifying the number of digits


print('{:05}'.format(255)) # 00255
print('{:08}'.format(255)) # 00000255

scope

Handling of global variables in functions

If you do not declare global when assigning, an error will occur


x = 5 
def add():
    global x #Cannot be rewritten without declaration
    x += 1
add() 
print(x)

You don't need a global declaration if you just want to refer to it ...


#It is easier to understand if you declare global just by referring to it
x = 5 
def print_x():
    print(x)
print_x() 

However, to prevent side effects, it is better not to access global variables from within the function as much as possible.

It is better to pass it as an argument


x = 5 
def add(x):
    x += 1
    return x
x = add(x) 
print(x)

list

List pitfalls


x = ["a", "b", "c"]
y = x.append("d")
print(x) # ['a', 'b', 'c', 'd']Variables are replaced
print(y) #None Return is None

For strings


x = "abcdef"
y = x.upper()
print(x) #leave the abcdef variable as is
print(y) #ABCDEF returns a string
Object type Variables after executing the method What the method returns
String Variable as it is String
list Variables are replaced None

List comprehension

Narrow down to those that match the conditions | if

Image that can process map and filter at the same time If the if statement is True, the list will be created.

Extract names containing e and make them lowercase


users = ["Yo", "Ken", "Nao", "Shin", "Lee"]
users = [u.lower() for u in users if u.find("e") != -1]
print(users) # ['ken', 'lee']

Loop multiple lists at the same time | zip

Disassemble "Aiueo ..." and restore it


str_ = list('Aiue Okaki Sashisuseso')
a = str_[::2] #The second one that came out from the beginning to the end=Index number is even (including 0)
b = str_[1::2] #The second one from 1 to the end=Odd index number
print(a) # ['Ah', 'U', 'O', 'Ki', 'Ke', 'Sa', 'Su', 'So']
print(b) # ['I', 'e', 'Or', 'Ku', 'This', 'Shi', 'Se']
#Delimiter string.join(sequence)
moto = "".join([ _a + _b for _a,_b in zip(a,b) ])
print(moto) #Aiue Okakikuke Kosashi

https://docs.python.jp/3/library/functions.html#zip

Set / dictionary

set => No duplication, no order, hash investigation

dictionary => Value added to the usage of hashes in set

s = {1,2,3,4,5}
print(type(s)) # <class 'set'>

d = {} #Note that it will be a dictionary if it is empty.
print(type(d)) # <class 'dict'>

Mathematical arithmetic of set

colors1 = {"white","black","red","green"}
colors2 = {"white","black","yellow"}
#Set difference
print(colors1 - colors2) # {'green', 'red'}
#Whether it is included in the set
print("blue" in colors2) # False
#Union union
colors3 = colors1 | colors2
print(colors3) # {'white', 'green', 'red', 'black', 'yellow'}
#common part
colors4 = colors1 & colors2
print(colors4) # {'black', 'white'}

Variadic and keyword arguments

Tuple and dictionary type

Description Receiving type
* Tuple
** Dictionary type
#Keep the order of variable length arguments and keyword arguments
def print_args_kwargs(*args, **kwargs):
    print(args) # (1, 2, 3)
    print(kwargs) # {'age': 25, 'name': 'sato'}
print_args_kwargs(1,2,3, age=25, name='sato')

Dictionary of keyword arguments

Pass arguments as dictionary


def say_hello(name, age):
    print(name, age) # sato 25
user = {'name':'sato', 'age':25}
say_hello(**user) # **Dictionary type

Reference Introduction to Python (Extra 1): * arg and ** kwarg

class

self

Refers to an instance created from a class. The first argument of a class instance method or constructor. It's easy to forget. Variables associated with self are called "instance variables", and methods are called "instance methods".

Class variables (constants) and methods

Variables associated with class are called "class variables", and methods are called "class methods".

class Player:
    #Class variables
    count = 0
    #Class constant (uppercase)
    GUILD = "KoB"
    def __init__(self):
        Player.count += 1
    #Class method
    @classmethod 
    def show_count(cls):
        #Because I haven't received self
        #Instance variables / methods cannot be used
        print("{} instances".format(cls.count))
        
    #Static method
    #Something like a class method with no first argument
    #Can be called without instantiation
    @staticmethod
    def show_guild():
        print(Player.GUILD)

player01 = Player()
player02 = Player()
player03 = Player()

#Can be called without instantiation
print(Player.count) # 3
Player.show_count() # 3 instances

#If there is no instance variable with the same name, you can call the class variable from the instance as well.
print(player01.count) # 3

Player.show_guild() # KoB

Data management with class constants

↓ It is convenient to manage data like this

Manage colors with constants


class Color:
    MAIN = '#f00'
    SUB = '#00f'
    FONT = '#fff'
print(Color.MAIN) # #f00

Private variables / methods

Two underscores "__" make it inaccessible from the outside One underscore "_" is only the shape

class Player:
    def __init__(self):
        self.name = 'sato'
    def __method(self):
        print(self.name)

player01 = Player()
player01.__method() # error

Getter setter

Used for instance variables that need to be manipulated externally

getter

official


class ClassName:
    @property
    def getterName(self):
        return value
class Clock:
    def __init__(self, hour):
        self._hour = hour

    @property
    def hour(self):
        return self._hour

clock = Clock(10)
print(clock.hour) #You can access the method like a variable
clock.hour = 12 #Value cannot be changed AttributeError: can't set attribute

setter

official


class ClassName:
    @getterName.setter
    def getterName(self, value):
class Clock:
    def __init__(self, hour):
        self._hour = hour

    @property
    def hour(self):
        return self._hour
    
    @hour.setter
    def hour(self, value):
        self._hour = value

clock = Clock(10)
clock.hour # 10
clock.hour = 6 #Now accessible
clock.hour # 6

Lambda expression

lambda argument: expression Returns the function as an object It is smart if you can use it when you can do it with an anonymous function instead of creating a function each time when passing a function

lambda_test = lambda x, y : print('lambda_test : {}, {}'.format(x, y)) # function <lambda>
lambda_test('hello', 'lambda') # lambda_test : hello, lambda

map

map(function, iterable) Adapt the function of the first argument to the list (tuple) of the second argument and return the result

map_obj = map(lambda x : x * 2, range(10))
print(list(map_obj)) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

filter

filter(function, iterable) Adapt the function of the first argument to the list (tuple) of the second argument and collect the True element

filter_obj = filter(lambda x : x % 2 == 0, range(10))
print(list(filter_obj)) # [0, 2, 4, 6, 8]

Decorator

Add arbitrary processing before and after the function

import time

def time_log(func):
    def wrapper(*args,**kwargs):
        
        import datetime
        start = datetime.datetime.today()
        print("--- start", func.__name__)
        
        #Function execution
        func(*args, **kwargs)
        
        end = datetime.datetime.today()
        delta = end - start
        print("--- end", func.__name__, delta, "sec")
    
    return wrapper #Returns a function object

#Add processing by describing the decorator name
@time_log 
def test1():
    print("sleep 1sec")
    time.sleep(1)
    
@time_log
def test2():
    print("sleep 2sec")
    time.sleep(2)
    
test1()
test2()

Reference http://dotinstall.com/lessons/basic_python_v3 http://www.yoheim.net/

Recommended Posts

3 months note for starting Python
Note: Python
Python note
boto3 (AWS SDK for Python) Note
2016-10-30 else for Python3> for:
python [for myself]
Python study note_002
Note: Python Decorator
Python programming note
[Python] Learning Note 1
"Python AI programming" starting from 0 for windows
Python study note_004
Note for Pyjulia calling Julia from Python
Python study note_003
[Note] openCV + python
Python beginner's note
Get note information using Evernote SDK for Python 3
Image processing? The story of starting Python for
Note for formatting numbers with python format function
About Python for loops
[Note] future sentence ~ Python ~
[Note] File reading ~ Python ~
Python basics ② for statement
About Python, for ~ (range)
python textbook for beginners
Python starting with Windows 7
Refactoring tools for Python
GRPC starting with Python
Note to daemonize python
Note: python Skeleton Nya
Python basic grammar note (4)
Python basic grammar note (3)
Python Tkinter Primer Note
OpenCV for Python beginners
Install Python (for Windows)
[Python] for statement error
Python environment for projects
Notes on writing config files for Python Note: configparser
Python memo (for myself): Array
About Fabric's support for Python 3
Python list, for statement, dictionary
Python for Data Analysis Chapter 4
Modern Python for intermediate users
Learning flow for Python beginners
Python 3.6 installation procedure [for Windows]
BigQuery integration for Python users
Python learning plan for AI learning
Set Up for Mac (Python)
Reinforcement learning starting with Python
Search for strings in Python
Python Tkinter notes (for myself)
OpenCV3 installation for Python3 @macOS
Python code memo for yourself
[Python] xmp tag for photos
[Note] Operate MongoDB with Python
Python environment construction For Mac
Techniques for sorting in Python
pp4 (python power for anything)
Python3 environment construction (for beginners)
Roadmap for publishing Python packages
Python 3 series installation for mac