python memo

A personal note when writing python. Mainly when studying on the following pages. http://www.tohoho-web.com/python/index.html

python.py


#!/usr/bin/python3
# -*- coding: utf-8 -*-

#See below
#  http://docs.python.jp/3/library/functions.html
#  http://www.tohoho-web.com/python/index.html
#  http://docs.python.jp/3.5/


print("In python, it seems that an error will occur if you do not write the character code at the beginning")


"""
Multi-line comment
Originally a string literal, but it seems to be used as a comment
"""


print("\n\n----------")
print("○ import and print")
import random
num = random.randint(1,10)
print("num is"+str(num))


print("\n\n----------")
print("○ if statement")
if num == 1:
    print("num is 1")
elif num < 5:
    print("num is 5 or less")
else:
    print("Other")


print("\n\n----------")
print("○ while statement")
n = 0
while n < 3:
    print("while "+str(n))
    n += 1
else:
    print('while END')
print("If you write else in the while statement, else will be executed if the while condition is not met and the message is exited.")
print("It will be executed even if the conditions are not met from the beginning.")
print("If it breaks due to break etc., it will not be executed.")


print("\n\n----------")
print("○ for statement")
for n in [1, 2, 3]:
    print(n)                 # => 1, 2, 3
else:
    print("END")
for n in (1, 2, 3):
    print(n)                 # => 1, 2, 3
for k,v in {'one': 1, 'two': 2, 'three': 3}.items():
    print(str(k)+":"+str(v)) # => one:1, two:2, three:3
for c in "123":
    print(c)                 # => 1, 2, 3
for line in open("data.txt"):
    print(line)              # =>Display line by line
for n in range(3,6):
    print(n)                 # => 3, 4, 5
for c in 'AIUEO':
    print(c)                 # =>Ah,I,U,e,O

print("You can also write else in the for statement.")
print("The meaning is the same as while.")
for x in range(2, n):
    if n % x == 0:
        print(n, 'equals', x, '*', n//x)
        break
else:
    # loop fell through without finding a factor
    print(n, 'is a prime number')


print("\n\n----------")
print("○ printf-like method")
errmsg = "String"
errcode = 12
msg = "You can do something like printf at the stage of creating a string[%s](%d)" % (errmsg, errcode)
print(msg)
print("%(name)s is %(age)d years old." % {'age': 28, 'name': "Tanaka"})


print("\n\n----------")
print("○ List and for statement")
a = [1, 2, "AAA", 4, (1+3j)*(2+2j)]
print('The third counting from 0 is'+str(a[3])) # => 4
print("1st to 2nd(No. 3 is not included)With slices"+str(a[1:3])) # => [2, 'AAA']
print("You can omit the start and end. Up to the second"+str(a[:3])) # => [1, 2, 'AAA']
print("Negative values can also be used. From the back to the second(However, the second itself is not included)Is"+str(a[:-2])) # => [1, 2, 'AAA']
print("Step width(Step)Can also be changed"+str(a[0:1:2])) # => [1, 'AAA']
print("Negative values can be used for the step size"+str(a[::-1])) # => [(-4+8j), 4, 'AAA', 2, 1]

print("You can also change the value")
print("Change before:"+str(a)) # => [1, 2, 'AAA', 4, (-4+8j)]
a[1]=999
print("After change:"+str(a)) # => [1, 999, 'AAA', 4, (-4+8j)]
print("You can also add.")
a.append(777)
print("After change:"+str(a)) # => [1, 999, 'AAA', 4, (-4+8j), 777]

for n in a:
    print("[for statement]"+str(n)+"That's right")

print("list join" + str([1, 2, 3] + [4, 5, 6])) # => [1, 2, 3, 4, 5, 6]
print("len()Find the length with"+str(len([1, 2, 3]))) # => 3

a = [[1, 2], [3, 4], [5, 6]]
a.append([7,8])
print("Multiple lists are also OK"+str(a)) # => [[1, 2], [3, 4], [5, 6], [7, 8]]
for line in a:
    for n in line:
        print(str(n)+" ", end="")
    print("") # => 1 2
              #    3 4
              #    5 6
              #    7 8
print("a[2][1]Is"+str(a[2][1])) # => 6


print("\n\n----------")
print("○ Tuple")
a = (11,22,33,)
print("There is a fixed value tuple of the list"+str(a))
print("First counting from 0"+str(a[1])) # => 22
#a[1]=12 # =>error


print("\n\n----------")
print("○ Dictionary")
d = {'Yamada': 30, 'Suzuki': 40, 'Tanaka': 80}
print("dictionary(Associative array)There is also"+str(d))
print("Yamada"+str(d["Yamada"]))
for key,val in d.items():
    print("[for statement]"+key+"Is"+str(val))


print("\n\n----------")
print("○ Function")
def doublefunc(x):
    return x * 2
print("Multiply 7 by double func"+str(doublefunc(7))) # => 14
a = [1, 2, 3]
print(str(a)+"To double func"+str(doublefunc(a))) # => [1, 2, 3, 1, 2, 3]


print("\n\n----------")
print("○map")
print("map returns the result of processing each element individually")

print("・ Function method")
print(map(doublefunc, a))       # => map object
print(list(map(doublefunc, a))) # => [2, 4, 6]

print("・ Lambda method")
print(map(lambda x: x * 2, a))       # => map object
print(list(map(lambda x: x * 2, a))) # => [2, 4, 6]

print("・ Inclusive notation")
print([x * 2 for x in a]) # => [2, 4, 6]

print("○filter")
print("filter processes each element individually and returns only the true one")
a = [1, 2, 3]
def kisuucheck(x): return x % 2
print("・ Function method")
print(filter(kisuucheck, a)) # => filter object
print("Odd ones"+str(list(filter(kisuucheck, a)))) # => [1, 3]
print("・ Lambda method and inclusion notation are omitted")


print("○reduce")
print("reduce processes the first and second elements, processes the result and the third, and so on.")
print("But probably because it is not used much, it can be used only after importing in python3")
from functools import reduce
a = [1, 2, 3, 4, 5]
def add(x, y): return x + y
print(reduce(add, a))                # => 15 :Function method
print(reduce(lambda x, y: x + y, a)) # => 15 :lambda method

print("○ Comprehension notation")
a = [1, 2, 3]
print([x * 2 for x in a])           # => [2, 4, 6]
print([x * 2 for x in a if x%2==1]) # => [2,6]
print([[x, x * 2] for x in a])      # => [[1, 2], [2, 4], [3, 6]]
print([(x, x * 2) for x in a])      # => [(1, 2), (2, 4), (3, 6)]
a = [[1, 2], [3, 4], [5, 6]]
print([[x[0]*2,x[1]*3] for x in a]) # => [[2, 6], [6, 12], [10, 18]]

print("○ Set")
print("set(set)Is a unique list")
a = set(['red', 'blue', 'green'])
b = set(['green', 'yellow', 'white'])
print("set a is"+str(a))                    # => set(['red', 'blue', 'green'])
print("set b is"+str(b))                    # => set(['green', 'yellow', 'white'])
print("a-b is"+str(a-b))                    # => set(['red', 'blue'])
print("a|b is"+str(a|b))                    # => set(['red', 'blue', 'green', 'yellow', 'white'])
print("a&b is"+str(a&b))                    # => set(['green'])
print("a^b is"+str(a^b))                    # => set(['red', 'blue', 'yellow', 'white'])
print("'green'in a is"+str('green' in a))  # => True
a.add('black')
print("After adding black to a"+str(a))       # => set(['red', 'blue', 'green', 'black'])
a.add('black')
print("If you add black to a"+str(a)) # => set(['red', 'blue', 'green', 'black'])


print("\n\n----------")
print("○ Note that the built-in function name can be overwritten after reservation.")
print("list([1,2])Is"+str(list([1,2]))) # => [1,2]
list_temp = list
list = doublefunc
print("list([1,2])Is"+str(list([1,2]))) # => [1,2,1,2]
list = list_temp
print("list([1,2])Is"+str(list([1,2]))) # => [1,2]


print("\n\n----------")
print("○ Exception handling")

mystring = 'ABC'
try:
    c = mystring[5]                    #I get an IndexError exception because I don't have the 5th character
except IOError:
    print('IOError')              #In case of IOError exception, this block will be executed
except IndexError:
    print('IndexError')           #In case of IndexError exception, this block will be executed
except:
    print('Unknown')              #For exceptions other than the above, this block will be executed
else:
    print('Error not occur')      #If no exception is raised, this block will be executed
finally:
    print('Finally')              #This block is always executed

try:
    f = open('sample.txt', 'r')
except:
    print('cannot open sample.txt')
else:
    lines = f.readlines()

try:
    raise SystemError("Sorry, my fault!")
except SystemError as e:
    print("SystemError")
    print(e)


print("\n\n----------")
print("○with")
print("If you process in with, the object will be terminated automatically.")
#How to write without using with
f = open("data.txt")
print(f.read())
f.close()

#How to write with with 1
with open("data.txt") as f:
    print(f.read())

#Writing with with 2
f = open("data.txt")
with f:
    print(f.read())


print("\n\n----------")
print("○pass")
print("pass does nothing, used when creating an empty function, etc.")
def myfunc():
    pass
class MyClass:
    pass


print("\n\n----------")
print("○del")
print("del deletes the object")
x = 5
y = [1, 2, 3]
z = MyClass()
del x, y, z


print("\n\n----------")
print("○ Print to a file with print")
f = open("gomi.txt", "a")
print("Hello world!", file=f)
f.close()


print("\n\n----------")
print("○exec")
print("You can execute a string with exec")
exec("print('hello')")


print("\n\n----------")
print("○ Function")
print("Function arguments can also be passed by name")
print("It also determines the default value for the argument")
def repeat_msg(msg, repeat=2, a=1):
    for i in range(repeat):
        print(msg+" a="+str(a))
repeat_msg('Hello')      # => Hello a=1, Hello a=1
repeat_msg('Yahho', a=5) # => Yahho a=5, Yahho a=5

print("You can also do things like argv in c")
def func(a1, a2, *args, **params):
    print(a1)        # => A
    print(a2)        # => B
    print(args)      # => ('C', 'D')
    print(params)    # => {'k1': 'K1', 'k2': 'K2'}
func('A', 'B', 'C', 'D', k1='K1', k2='K2')

args = ('C', 'D')
params = {'k1': 'K1', 'k2': 'K2'}
func('A', 'B', args, params)     # => A, B, (('C', 'D'), {'k2': 'K2', 'k1': 'K1'}), {}
func('A', 'B', *args, **params)  # => A, B, ('C', 'D'), {'k1': 'K1', 'k2': 'K2'}

print("You can also return multiple values")
def func():
    return 3, "ABC"

n, s = func()
print(n, s) # => 3 ABC


print("\n\n----------")
print("○ Global variables")
print("Global variables cannot be normally referenced or modified within a function")
print("You can change it by declaring it global")
count = 0                   #Global variables
def func():
    global count            #You can't change without this
    print(count)            #Can be referenced
    count += 1
    print(count)
func()

print("All global and local variables are globals()And locals()You can get it at")
def func():
    for k in globals().keys():
        print("GLOBAL: %s = %s" % (k, globals()[k]))
    for k in locals().keys():
        print("LOCAL: %s = %s" % (k, locals()[k]))
func()

print("\n\n----------")
print("○ Lambda type")
print("Lambda expressions are small, unnamed functions.")
print("The argument is before the colon and the return value is after it.")
myfunc = lambda x, y: x + y
print(myfunc(3, 5)) # => 8


print("\n\n----------")
print("○ Iterator")
print("An iterator is an object with a repeat function that can be used in a for statement.")
print("__init__()Write the process to be done only once at the beginning")
print("__iter__()Returns the object")
print("__next__()Will return the next element with StopIteration exception when it reaches the end")
class Fib:
    def __init__(self, max):
        self.max = max
        self.a = 0
        self.b = 1
    def __iter__(self):
        return self
    def __next__(self):
        fib = self.a
        if fib > self.max:
            raise StopIteration
        self.a, self.b = self.b, self.a + self.b
        return fib
for n in Fib(3):
    print(n)                     # => 0, 1, 1, 2, 3

print("The above does the following automatically")
it = Fib(3).__iter__()
while 1:
    try:
        n = it.__next__()
        print(n)                 # => 0, 1, 1, 2, 3
    except StopIteration:
        break

print("\n\n----------")
print("○ Generator")
print("It calculates when the next element is used, so it seems that memory and processing efficiency will be improved compared to creating and passing an array.")
def funcB(list):
    for n in list:
        yield n * 2
for n in funcB([1, 2, 3, 4, 5]):
    print(n)                     #=> 2, 4, 6, 8, 10

def readfileB(f):
    for line in f:
        yield line.rstrip()
f = open("data.txt")
for line in readfileB(f):
    if (line == "__END__"):
        break
    print(line)
f.close()



print("\n\n----------")
print("○ Decorator")
print("You can add processing before and after executing the function")

def mydecolater(func):
    import functools
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("Funcname:", func.__name__)
        print("Arguments:", args)
        print("Keywords:", kwargs)
        ret = func(*args, **kwargs)
        print("Return:", ret)
        return ret
    return wrapper

@mydecolater
def func(msg1, msg2, flag=1, mode=2):
    """A sample function"""
    print("----", msg1, msg2, "----")
    return 1234

n = func("Hello", "Hello2", flag=1)
print(n)

print(repr(func))
print(func.__doc__)


print("\n\n----------")
print("○ Class")

class MyClass(object):
    """A simple example class"""         #Comment by Mie Quart

    PI=3.14                              #Class variables

    def __init__(self):                  #constructor
        self.name = ""                   #name is an instance variable

    def getName(self):                   # getName()Method
        return self.name

    def setName(self, name):             # setName()Method
        self.name = name

a = MyClass()                            #Instantiate a class
a.setName("Tanaka")                      # setName()Call method
print(a.getName())                       # getName()Call method

print("Python does not implement scope control mechanisms such as private and protected, and class variables and instance variables can all be referenced from anywhere.(public)It will be.")
print("Class variables and instance variables can be rewritten directly")
MyClass.PI=3.141592
a.name="Tanaka2"

print("Can be added dynamically")
MyClass.myPI=3
a.age=18

print("If the instance variable does not exist, "instance".Note that "variable name" refers to a class variable.")
print(a.PI) #Since there is no instance variable called PI, the class variable is referenced.

print(""instance.An instance variable is generated when a value is assigned to "variable name", and the instance variable is referenced thereafter.")
a.PI=333 #An instance variable PI can be created separately from the class variable PI.
print(a.PI) # =>333 instance variables
print(MyClass.PI) # => 3.141592 Class variables

print("dir()If you use, it will be displayed in various ways")
print("MyClass : "+str(dir(MyClass)))
print("MyClass : "+str(dir(a)))


print("\n\n----------")
print("○ Private-like variables")
class MyClass2(object):
    _hidden_param=12
    __hidden_param2=34
print("There is a customary rule that variables in a class that have an underscore in front of them should not be accessed from the outside. But you can access it.")
print("2 If you poke it, you can access it normally in the class, but it will be difficult to access it from the outside. The name changed slightly, "_name of the class__It becomes "variable name".")
print("MyClass2._hidden_param="+str(MyClass2._hidden_param))
#print("MyClass2._hidden_param="+str(MyClass2.__hidden_param2)) #← This is an error
print("MyClass2._hidden_param="+str(MyClass2._MyClass2__hidden_param2)) #← This is OK


print("\n\n----------")
print("○ Constructor, destructor, and stringification")
class MyClass3(object):
    def __init__(self, name):
        self.name = name
        print("welcome "+str(self.name))

    def __str__(self):
        return "name is "+self.name

    def __del__(self):
        print("byebye "+str(self.name))

a = MyClass3("Tanaka")
print(a) # __str__The method defined as is called automatically.
del(a)


print("\n\n----------")
print("○ Inheritance")
class MyClass:
    def hello(self):
        print("Hello")

class MyClass2(MyClass):
    def world(self):
        print("World")

a = MyClass2()
a.hello()                   #=> Hello
a.world()                   #=> World

print("Method override")
class MyClass:
    def hello(self):
        print("Hello")
class MyClass2(MyClass):
    def hello(self):        #Parent class hello()Override method
        print("HELLO")

a = MyClass2()
a.hello()                   #=> HELLO

print("super")
class MyClass1(object):
    def __init__(self):
        self.val1 = 123
    def pripri(self):
        print("print1")
class MyClass2(MyClass1):
    def __init__(self):
        super(MyClass2, self).__init__()
        self.val2 = 456
    def pripri(self):
        super(MyClass2, self).pripri()
        print("print2")

a = MyClass2()
print(a.val1)                #=> 123
print(a.val2)                #=> 456
a.pripri()

print("Multiple inheritance")
class MyClassA:
    def funcA(self):
        print("MyClassA:funcA")
class MyClassB:
    def funcB(self):
        print("MyClassB:funcB")

class MyClassC(MyClassA, MyClassB):
    def funcC(self):
        print("MyClassC:funcC")

a = MyClassC()
a.funcA()                    #MyClassA methods too
a.funcB()                    #You can also use MyClassB methods
a.funcC()


print("\n\n----------")
print("○ Module")
import mymodule
mymodule.myfunc()

print("Omitted for packages.")

print("file name"+str(__file__))
print("__name__You can display the module name with. If started with a script__main__Will be. str(__name__)="+str(__name__))


print("\n\n----------")
print("○pprint")
print("Use pprint to display information such as arrays in an easy-to-read manner")
from pprint import pprint
aaa = [0, 1, 2]
ppp = {'taro':{'age': '21', 'name': 'tanaka'}, 'jiro':{'age': '18', 'name': 'tanaka2'},}
pprint(aaa) #=> [0, 1, 2]
pprint(ppp) #=> {'jiro': {'age': '18', 'name': 'tanaka2'},
            #    'taro': {'age': '21', 'name': 'tanaka'}}

import os
print("The current path is"+os.getcwd())


print("\n\n----------")
print("○ Debug print")
print("If you want to display it only when debugging, do as follows(I don't know if it's a good way)。")

def null_function(x):
    return

myprint=null_function
#myprint=print

myprint("hoge")


print("\n\n----------")
print("○ Partial change of character string")
print("Text like C[2]='x'Etc. cannot be used.")
print("because str is immutable")
print("Convert it to a list and then change it or operate it with slices.")
print("reference: http://minus9d.hatenablog.com/entry/20130528/1369745960")

text="test string"
#text[2]='S'#This is NG

temp=list(text)
temp[2]='S'
text="".join(temp)
print(text) #=> "teSt string"


print("\n\n----------")
print("○ Passing arguments by value and by reference")
print("Function arguments can be passed by value or by reference.")
print("Similar to C, int,float etc. are passed by value, list,dict etc. are passed by reference.")
print("But str is passed by value.")
print("reference: http://amacbee.hatenablog.com/entry/2016/12/07/004510")
def func1(x):
    x[1]=999
y=[0,1,2]
print(y) #=> [0, 1, 2]
func1(y)
print(y) #=> [0, 999, 2]

print("\n\n----------")
print("○ Stop the script file in the middle and enable input")
import code; code.InteractiveConsole(locals=dict(globals(),**locals())).interact()

mymodule.py


#!/usr/bin/python3
# -*- coding: utf-8 -*-

#module

def myfunc():
    print("Hello!")

Recommended Posts

Python memo
python memo
Python memo
python memo
Python memo
Python memo
Python memo
[Python] Memo dictionary
python beginner memo (9.2-10)
python beginner memo (9.1)
★ Memo ★ Python Iroha
[Python] EDA memo
Python 3 operator memo
[My memo] python
Python3 metaclass memo
[Python] Basemap memo
Python beginner memo (2)
[Python] Numpy memo
Python class (Python learning memo ⑦)
My python environment memo
python openCV installation (memo)
Python module (Python learning memo ④)
Visualization memo by Python
Python
Python test package memo
[Python] Memo about functions
python regular expression memo
Binary search (python2.7) memo
[My memo] python -v / python -V
Python3 List / dictionary memo
[Memo] Python3 list sort
Python Tips (my memo)
[Python] Memo about errors
DynamoDB Script Memo (Python)
Python basic memo --Part 2
python recipe book Memo
Basic Python command memo
Python OpenCV tutorial memo
Python basic grammar memo
TensorFlow API memo (Python)
python useful memo links
Python decorator operation memo
Python basic memo --Part 1
Effective Python Memo Item 3
Divisor enumeration Python memo
Python memo (for myself): Array
Python exception handling (Python learning memo ⑥)
Python execution time measurement memo
Twitter graphing memo with Python
[Line / Python] Beacon implementation memo
Python and ruby slice memo
Python Basic Grammar Memo (Part 1)
Python code memo for yourself
Raspberry Pi + Python + OpenGL memo
Python basic grammar (miscellaneous) Memo (3)
Python immutable type int memo
Python memo using perl --join
Python data type summary memo
Python basic grammar (miscellaneous) Memo (2)
[MEMO] [Development environment construction] Python
[Python] virtualenv creation procedure memo