Python3 cheat sheet (basic)

Contents of this article

  1. Python basics
  2. Control structure
  3. Data structure
  4. Function
  5. Class / instance
  6. Module / Package / Namespace / Scope
  7. Built-in functions / special methods
  8. File operations and input / output

1. Python basics

Basic grammar

Indent


import os
def function():
    #Indent is PEP8(*)According to, 4 half-width spaces
    print('Hello world')

(*)PEP8(Python Enhancement Proposal) https://www.python.org/dev/peps/pep-0008/ Indentation Use 4 spaces per indentation level.

Variable declaration


#Numerical value
num = 1
#String
name = 'Tanaka'
#list
list = [1, 2, 3, 4, 5]

#Explicit type declaration
num: int = 1
name: str = 'Tanaka'

#Type conversion
old_num = '1' #String type
new_num = int(num) #Convert to integer type and new_Assign to num

--The reason Python doesn't require variable declarations is because Python is a dynamically typed language. Dynamically typed languages perform processing while automatically determining the type during program execution. Even if the type is not specified, it is fixed at the time of execution, but since implicit type conversion is not performed, it is necessary to be aware of the type when writing the code.

comment


 #Line-by-line comment

"""
Multiple lines
collect
comment
"""

Docstring


def test_function(param1, param2):
    """Test that adds two arguments and returns_function
    
    Args:
        param1(int):Explanation of the first argument
        param2(int):Explanation of the second argument
    
    Returns:
Return the addition result of param1 and param2
    """
    return param1 + param2

--Unlike comments, Docstring is a document that can be referenced from various tools. Only available at the beginning of the module and in the definition of functions, classes and methods. (Cannot be used in the middle of a function, etc.)

Numerical manipulation

Numerical calculation


#Integer addition
>>> 1 + 1
2

#Integer subtraction
>>> 2 - 1
1

#Integer multiplication
>>> 5 * 6
30

#Integer division * Division always returns a floating point
>>> 6 / 5
1.2

#Evaluation order is the same as mathematics
>>> 50 - 5 * 6
20
>>> (50 - 5 * 6) / 4
5.0

#Standard division returns float
>>> 17 / 3
5.666666666666667

# 「//": Round-down division rounds down to the nearest whole number
>>> 17 // 3
5

# 「%": Returns the remainder (remainder of division)
>>> 17 % 3
2
>>> 

#5 squared
>>> 5 ** 2
25
#2 to the 7th power
>>> 2 ** 7
128

#Round after the decimal point(Round to two decimal places)
>>> pie = 3.1415926535
>>> pie
3.1415926535
>>> round(pie, 2)
3.14

Manipulating strings

String


#Surround with single quotes
>>> print('Hello world')
Hello world

#Surround with double quotes
>>> print("Hello world")
Hello world

#As a character string "'When using(Surround with double quotes)
>>> print("I'm from Japan.")
I'm from Japan.
'
#As a character string "'When using(Escape)
>>> print('I\'m from Japan.')
I'm from Japan.
'
#Begin on a new line(\n)
>>> print('Hello! \nHow are you doing?')
Hello! 
How are you doing?

#Prevent interpretation as a special character(「\Since the "n" part is interpreted as a line break, it is processed as raw data.)
>>> print(r'C:\name\name')
C:\name\name

#Multi-line output(「"""Surrounded by)
>>> print("""
... line1
... line2
... line3
... """)

line1
line2
line3

#Do not let line breaks(「\To describe)
>>> print("""\
... line1
... line2
... line3\
... """)
line1
line2
line3

#Repeating letters
>>> print('Yes.' * 3 + '!!!')
Yes.Yes.Yes.!!!

#String concatenation(Literals are "+Is OK without)
>>> print('Py''thon')
Python

#String concatenation(variable+The literal is "+"Is necessary)
>>> prefix = 'Py'
>>> print(prefix + 'thon')
Python

String index/Slicing



#Variable definition
>>> word = 'Python'

#Get the character at the 0th position of word
>>> print(word[0])
P

#Get the character in the 5th position of word
>>> print(word[5])
n

#Get the character in the first position from the end of word(From the beginning, 0,1,2 ... From the end-1,-2,-3 ...)
>>> print(word[-1])
n

#Get the character in the third position from the end of word(From the beginning, 0,1,2 ... From the end-1,-2,-3 ...) 
>>> print(word[-3])
h

#word 0(Including 0)From 2(2 is not included)Get characters up to the position of
>>> print(word[0:2])
Py

#word 2(2 including)From 5(5 not included)Get characters up to the position of
>>> print(word[2:5])
tho

#2 from the beginning of word(2 including)Get characters up to the position of
>>> print(word[:2])
Py

#word 2(2 including)Get the character from the position to the end
>>> print(word[2:])
thon

#Get the characters from the beginning to the end of word
>>> print(word[:])
Python

Method related to characters


#Define string s
>>> s = 'Hello Tom. How are you doing.'
>>> print(s)
Hello Tom. How are you doing.

#Check if the string contains a specific string
>>> print(s.startswith('Hello'))
True
>>> print(s.startswith('Tom'))
False

#Specific characters in the string(or string)Check the position where(From the beginning)
>>> print(s.find('o'))
4

#Specific characters in the string(or string)Check the position where(From the end)
>>> print(s.rfind('o'))
24

#Specific characters in the string(or string)Check the number of
>>> print(s.count('o'))
5

#Convert the first letter of the string to uppercase
>>> print(s.capitalize())
Hello tom. how are you doing.

#Convert the first letter of each word in the string to uppercase
>>> print(s.title())
Hello Tom. How Are You Doing.

#Convert string to uppercase
>>> print(s.upper())
HELLO TOM. HOW ARE YOU DOING.

#Convert strings to lowercase
>>> print(s.lower())
hello tom. how are you doing.

#Replace a specific string
>>> print(s.replace('Tom', 'Bob'))
Hello Bob. How are you doing.

2. Control structure

Conditional branch (if statement)

Conditional branch(if statement)


if conditional expression 1:
What to do if conditional expression 1 is true
elif conditional expression 2:
Processing to be executed when conditional expression 1 is false and conditional expression 2 is true
else:
Processing to be executed when all conditional expressions are false

--if is evaluated in order from the top, and the processing of the first true clause is executed. If conditional expression 1 is true, the processing of conditional expression 2 is not executed even if the result of conditional expression 2 is true.

A value that is false in the conditional expression


- None
- False
-Numeric type zero, 0, 0.0 、 0j(Complex number)
-Empty objects in container objects such as strings, lists, dictionaries, sets, etc.
-Method__bool__()Is an object that returns False
-Method__bool__()Is not defined and the method__len__()Object that returns 0

--In Python, anything other than a false object is evaluated as true. In other words, everything except the above is true.

Numerical comparison


#True if equivalent
>>> 1 == 1
True

#True if not equivalent
>>> 1 != 1
False

#True if the left side is large
>>> 1 > 0
True

#True if the right side is large
>>> 1 < 0
False

#True if the left side is large or equivalent
>>> 1 >= 0
True

#True if the right-hand side is large or equivalent
>>> 1 <= 0
False

# x < y and y <Equivalent to z
>>> x, y, z = 1, 2, 3
>>> x < y < z
True

Object comparison


>>> x = 'red'
>>> y = 'green'

#True if equivalent
>>> x == y
False

#True if not equivalent
>>> x != y
True

#True for the same object
>>> x is None
False

#True if not the same object
>>> x is not None
True

>>> items = ['pen', 'note', 'book']

#In items'book'True if is included
>>> 'book' in items
True

#In items'note'True if is not included
>>> 'note' not in items
False

Loop (for statement)

for statement


>>> items = [1, 2, 3]
>>> for i in items:
...     print(f'The value of the variable i is{i}')
... 
The value of the variable i is 1
The value of the variable i is 2
The value of the variable i is 3

# range()function
>>> for i in range(3):
...     print(f'{i}Second process')
... 
0th process
First process
Second process

# enumerate()function
>>> chars = 'word'
>>> for count, char in enumerate(chars):
...     print(f'{count}The second character is{char}')
... 
The 0th character is w
The first letter is o
The second letter is r
The third letter is d

#Dictionary loop(items()Method)
>>> sports = {'baseball': 9, 'soccer': 11, 'tennis': 2}
>>> for k, v in sports.items():
...     print(k, v)
... 
baseball 9
soccer 11
tennis 2

#Simultaneous loop of two sequences(zip()function)
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue' ]
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
... 
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

Behavior of else clause of for statement


>>> nums = [2, 4, 6, 8]
>>> for n in nums:
...     if n % 2 == 1:
...         break
... else:
...     print('There are no odd numbers')
... 
There are no odd numbers

--In the else clause, describe the process you want to execute only once after the for statement ends. --When the else clause is used, the block of the else clause is executed when the break statement is not used during the processing of the for statement or while statement.

Exception handling

try statement


try:
Processing that may cause an exception
except the exception class you want to catch:
Process executed when the exception you want to catch occurs
else:
Process executed only when no exception occurs
finally:
The process you want to execute regardless of whether an exception occurs

--try clause: Describe the processing that may cause an exception between the try-except clauses.

try-except clause


#Access the element that does not exist in the array, raise an exception, and catch it in the except clause
>>> l = [1, 2, 3]
>>> i = 5
>>> try:
...     l[i]
... except:
...     print('It is no problem')
... 
It is no problem

#Catch a specific exception in the except clause
>>> try:
...     l[i]
... except IndexError:
...     print('You got an IndexError')
... 
You got an IndexError

#Output the cause of the exception
>>> try:
...     l[i]
... except IndexError as ex:
...     print('You got an IndexError : {}'.format(ex))
... 
You got an IndexError : list index out of range

#Catch all exceptions
>>> try:
...     () + l
... except IndexError:
...     print('You got an IndexError')
... except BaseException as ex:
...     print('You got an Exception : {}'.format(ex))
... 
You got an Exception : can only concatenate tuple (not "list") to tuple

Exception class hierarchy https://docs.python.org/ja/3/library/exceptions.html#exception-hierarchy

--else clause: Describe the process to be executed when an exception does not occur in the else clause.

else clause


#Describe the process to be executed when an exception does not occur in the else clause.
>>> try:
...     1 + 1
... except BaseException:
...     print('You got an Exception.')
... else:
...     print('There are no Exceptions!')
... 
2
There are no Exceptions!

--Finally clause: Describe the process to be executed regardless of whether an exception occurs or not in the finally clause.

finally clause


#Describe the process to be executed in the finally clause regardless of whether an exception occurs or not.
>>> try:
...     raise NameError('It is a NameError!!!')
... except NameError as ne:
...     print(ne)
... finally:
...     print('NameError Program finished!!!')
... 
It is a NameError!!!
NameError Program finished!!!
Throwing an exception (intentionally raising an exception)

raise statement


#You can re-throw an exception by simply mentioning raise. (If you want to know how to send an exception, but don't let it be processed on the spot)
>>> try:
...     raise NameError('It is a NameError!!!')
... except NameError:
...     print('Name Error.')
...     raise
... 
Name Error.
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: It is a NameError!!!

3. Data structure

List type

List type


#Definition of list "l"
>>> l = [1, 2, 3, 4, 5]
>>> print(l)
[1, 2, 3, 4, 5]

#Get a specific element of the list
>>> print(l[0])
1 
>>> print(l[-1])
5

#Third from the beginning of the list(0th, 1st, 2nd)Up to the element of(Does not include the third)Get
>>> print(l[:3])
[1, 2, 3]

#Third from the end of the list(3 includes)Get from element to end
>>> print(l[-3:])
[3, 4, 5]

#Get all elements of the list
>>> print(l[:])
[1, 2, 3, 4, 5]

#Join list
>>> l2 = [6, 7, 8, 9, 10]
>>> print(l + l2)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#Modify list elements
>>> l[2] = 300
>>> print(l)
[1, 2, 300, 4, 5]

--Strings are immutable and specific elements cannot be changed, but lists are mutable and elements can be swapped.

Manipulating the list

Manipulating the list



#Add list elements(Add at the end)
>>> l.append(600)
>>> print(l)
[1, 2, 300, 4, 5, 600]

#Add list elements(Add to the beginning: Add "0" to the 0th index)
>>> l.insert(0, 0)
>>> print(l)
[0, 1, 2, 300, 4, 5, 600]

#Get list elements(Get last element, disappear from list)
>>> l.pop()
600
>>> print(l)
[0, 1, 2, 300, 4, 5]

#Get list element (delete 0th element, disappear from list)
>>> l.pop(0)
0
>>> print(l)
[1, 2, 300, 4, 5]

#Delete list elements(Delete the second element)
>>> del l[2]
>>> print(l)
[1, 2, 4, 5]

#Delete list (delete the entire list)
>>> del l
>>> print(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'l' is not defined

#Delete all elements of the list (do not delete the list)
>>> print(l)
[['A', 'B', 'C'], [1, 2, 3]]
>>> l.clear()
>>> print(l)
[]

#Deletes elements that match the specified value in the list
>>> l = [0, 1, 2, 3, 3, 3, 4, 5]
>>> l.remove(3)
>>> print(l)
[0, 1, 2, 3, 3, 4, 5]

#Delete the element that matches the specified value in the list (an error will occur if there is no matching element)
>>> l.remove(3)
>>> l.remove(3)
>>> l.remove(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> print(l)
[0, 1, 2, 4, 5]

#Get the number of elements in the list
>>> print(len(l))
5

#Nesting lists (creating lists with lists as elements)
>>> l1 = ['A', 'B', 'C']
>>> l2 = [1, 2, 3]
>>> l = [l1, l2]
>>> print(l)
[['A', 'B', 'C'], [1, 2, 3]]

#Get index that matches the specified value (error if item does not exist)
>>> l = [1, 2, 3, 4, 5]
>>> l.index(3)
2
>>> l.index(6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 6 is not in list

#Get the number of elements that match the specified value
>>> l.count(4)
1

#Change list elements in reverse order
>>> print(l)
[1, 2, 3, 4, 5]
>>> l.reverse()
>>> print(l)
[5, 4, 3, 2, 1]

#Sort the elements of the list in ascending order
>>> l = [4, 5, 2, 1, 3]
>>> print(l)
[4, 5, 2, 1, 3]
>>> l.sort(key=None, reverse=False)
>>> print(l)
[1, 2, 3, 4, 5]

#Sort the elements of the list in descending order
>>> l = [4, 5, 2, 1, 3]
>>> print(l)
[4, 5, 2, 1, 3]
>>> l.sort(key=None, reverse=True)
>>> print(l)
[5, 4, 3, 2, 1]

#Store in a list separated by specific characters
>>> s = 'Hi, Tom. How are you doing?'
>>> print(s.split(' '))
['Hi,', 'Tom.', 'How', 'are', 'you', 'doing?']
>>> print(s.split('.'))
['Hi, Tom', ' How are you doing?']

Tuple type

--The difference between a list and a tuple is that a list can change the value for each element (mutable), while a tuple cannot change the value (immutable). --Therefore, tuples are used for read-only purposes, such as when you do not want to be rewritten once you enter a value.

Tuple type



#Declaration of tuple(Defined as a tuple with or without parentheses)
>>> t = (1, 2, 3, 4, 5)
>>> print(t)
(1, 2, 3, 4, 5)

>>> t2 = 1, 2, 3
>>> print(t2)
(1, 2, 3)

#Declaration of tuple (at the end of the definition "",Note that if there is a "", it is defined as a tuple)
#Even if there is only one element, ",It is necessary to describe.
>>> t3 = 1,
>>> t3
(1,)
>>> type(t3)
<class 'tuple'>

#Tuples, unlike lists, cannot change their values
>>> t[0] = 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

#Store the list in a tuple and the value of the list can be changed
>>> t = ([1, 2, 3], [4, 5, 6])
>>> t
([1, 2, 3], [4, 5, 6])
>>> t[0][0]
1
>>> t[0][0] = 100
>>> t
([100, 2, 3], [4, 5, 6]) 

Tuple unpacking



#Assign tuple values to variables
>>> t = (1, 2, 3)
>>> t
(1, 2, 3)
>>> x, y, z = t
>>> print(x, y, z)
1 2 3

#Effective when exchanging the values of specific variables, etc.
>>> X = 100
>>> Y = 200
>>> print(X, Y)
100 200
>>> X, Y = Y, X
>>> print(X, Y)
200 100

Dictionary type (dictionary type)

Dictionary type (dictionary type)



#Dictionary type (dictionary type) declaration ①
>>> d = {'x': 10, 'y': 20, 'z': 30}
>>> d
{'x': 10, 'y': 20, 'z': 30}

#Dictionary type (dictionary type) declaration ②
>>> dict(a=100, b=200, c=300)
{'a': 100, 'b': 200, 'c': 300}

#Getting the value of a specific dictionary type (dictionary type) key
>>> d['y']
20

#Addition of keys and values to dictionary type (dictionary type)
>>> d['a'] = 40
>>> d
{'x': 10, 'y': 20, 'z': 30, 'a': 40}

#Deletion of specific dictionary-type (dictionary-type) keys
>>> del d['a']
>>> d
{'x': 10, 'y': 20, 'z': 30}

Dictionary type (dictionary type) operation

Dictionary type (dictionary type) operation



#Acquisition of dictionary type (dictionary type) key list
>>> d
{'x': 10, 'y': 20, 'z': 30}
>>> d.keys()
dict_keys(['x', 'y', 'z'])
>>> list(d.keys())
['x', 'y', 'z']

#Dictionary type (dictionary type) update (combination)
#Update the value for the item where the key exists, add the key and value for the item where the key does not exist
>>> d
{'x': 10, 'y': 20, 'z': 30}
>>> d2
{'x': 100, 'a': 1, 'b': 2}
>>> d.update(d2)
>>> d
{'x': 100, 'y': 20, 'z': 30, 'a': 1, 'b': 2}

#Get the value of a specific key
>>> d.get('x')
100

#Get the value of a specific key (the retrieved key and value are no longer in the dictionary definition)
>>> d
{'x': 100, 'y': 20, 'z': 30, 'a': 1, 'b': 2}
>>> d.pop('a')
1
>>> d.pop('b')
2
>>> d
{'x': 100, 'y': 20, 'z': 30}

#Check if a specific key is included in the dictionary
>>> d
{'x': 100, 'y': 20, 'z': 30}
>>> 'x' in d
True

set

--Unlike lists and tuples, sets do not allow duplicate elements and do not preserve the order of the elements. --There are two types of built-in set types, set type and frozen set type.

set type


>>> items = {'note', 'notebook', 'pen'}
>>> type(items)
<class 'set'>
>>> items
{'notebook', 'note', 'pen'}

#Duplicate elements will be one
>>> items = {'note', 'notebook', 'pen', 'pen', 'note'}
>>> items
{'notebook', 'note', 'pen'}

#Add element
>>> items.add('book')
>>> items
{'notebook', 'note', 'pen', 'book'}

#Delete element
>>> items.remove('pen')
>>> items
{'notebook', 'note', 'book'}

#Take an element and remove it from the set
#Since there is no order, the elements to be retrieved are indefinite
>>> items.pop()
'notebook'
>>> items
{'note', 'book'}

--Frozen set type is a type that makes set type invariant (type that handles invariant set)

frozen set type


>>> items = frozenset(['note', 'notebook', 'pen'])
>>> type(items)
<class 'frozenset'>

>>> items
frozenset({'notebook', 'note', 'pen'})

#Cannot be changed because it is an immutable type
>>> items.add('book')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'

Set arithmetic


>>> set_a = {'note', 'notebook', 'pen'}
>>> set_b = {'note', 'book', 'file'}

#Union
>>> set_a | set_b
{'notebook', 'note', 'file', 'book', 'pen'}
>>> set_a.union(set_b)
{'notebook', 'note', 'file', 'book', 'pen'}

#Difference set
>>> set_a - set_b
{'notebook', 'pen'}
>>> set_a.difference(set_b)
{'notebook', 'pen'}

#Intersection
>>> set_a & set_b
{'note'}
>>> set_a.intersection(set_b)
{'note'}

#Symmetric difference
>>> set_a ^ set_b
{'notebook', 'book', 'file', 'pen'}
>>> set_a.symmetric_difference(set_b)
{'notebook', 'book', 'file', 'pen'}

#Determine if it is a subset
>>> {'note', 'pen'} <= set_a
True
>>> {'note', 'pen'}.issubset(set_a)
True

Comprehension notation

--Comprehension is a syntax that can generate lists, sets, dictionaries, etc.

List comprehension(Creating a list)


#Creating a list using a for statement
>>> numbers = []
>>> for i in range(10):
...     numbers.append(str(i))
... 
>>> numbers
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

#Creating a list using list comprehension notation
>>> [str(v) for v in range(10)]
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

#Nested list comprehension
#Description using for statement
>>> tuples = []
>>> for x in [1, 2, 3]:
...     for y in [4, 5, 6]:
...         tuples.append((x, y))
... 
>>> tuples
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

#Creating nested lists using list comprehensions
>>> [(x, y) for x in [1, 2, 3] for y in [4, 5, 6]]
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

#Comprehension with if statement
#Description using for statement
>>> even = []
>>> for i in range(10):
...     if i % 2 == 0:
...         even.append(i)
... 
>>> even
[0, 2, 4, 6, 8]

#Description using comprehension notation
>>> [x for x in range(10) if x % 2 == 0]
[0, 2, 4, 6, 8]

4. Function

Function definition


#Function definition (no arguments)
>>> def say_hello():
...     print('Hello')
... 
>>> say_hello()
Hello

#Function definition (with arguments)
>>> def say_something(str):
...     print(str)
... 
>>> say_something('Good morning')
Good morning

#Function definition (with arguments, with default arguments)
>>> def say_something(str='Hi!'):
...     print(str)
... 
#If no argument is specified, the default argument is used
>>> say_something()
Hi!
#If an argument is specified, that argument will be used.
>>> say_something('Hello')
Hello

#Function definition (with return value)
>>> def increment(num):
...     return num + 1
... 
>>> increment(1)
2

--When the return statement is executed in the function, the processing ends there, so the subsequent processing is not executed. --The return value of a function without return is None.

Function arguments


#Positional argument->Stored in variables in the order passed when calling the function(Error if the number of arguments is different)
>>> def increment(num1, num2):
...     return num1 + num2
... 
>>> increment(2, 4)
6

#Keyword arguments->Specify keyword arguments when calling(The order doesn't matter)
>>> def greeting(name, str):
...     print(str + ', ' + name + '!')
... 
>>> greeting(str='Hello', name='Tom')
Hello, Tom!

#Default argument->A default value can be specified for the formal argument (however, the formal argument with the default value must be described after the formal argument without the default value).
>>> def greeting(name, str='Hi'):
...     print(str + ', ' + name + '!')
... 
>>> greeting('Tom')
Hi, Tom!

#Variable length positional argument->Can accept any number of arguments (specified position is at the end of the positional argument, before the argument with the default value)
>>> def say_something(name, *args):
...     for str in args:
...         print("I'm " + name + ". " + str + "!")
... 
>>> say_something('Tom', 'Hello', 'Hi', 'Good morning')
I'm Tom. Hello!
I'm Tom. Hi!
I'm Tom. Good morning!
'

#Variable length keyword argument->Receives keyword arguments that were not assigned to formal arguments in dictionary type (specified position is the last)
>>> def print_birthday(family_name, **kwargs):
...     print("Birthday of " + family_name + " family")
...     for key, value in kwargs.items():
...         print(f'{key}: {value}')
... 
>>> print_birthday('Smith', Nancy='1990/1/1', Tom='1993/1/1', Julia='2010/1/1')
Birthday of Smith family
Nancy: 1990/1/1
Tom: 1993/1/1
Julia: 2010/1/1

#Variable-length positional and keyword arguments->Can handle any argument calls
>>> def say_something(*args, **kwargs):
...     for s in args:
...         print(s)
...     for key, value in kwargs.items():
...         print(f'{key}: {value}')
... 
>>> say_something('Hello', 'Hi', 'Bye', Nancy='29 years old', Tom='26 years old')
Hello
Hi
Bye
Nancy: 29 years old
Tom: 26 years old

#Keyword only argument->Arguments that require a formal argument name when called
# 「*Only keywords are arguments after "
>>> def increment(num, lsat, *, ignore_error=False):
...     pass
... 
#An error will occur with positional arguments
>>> increment(1, 2, True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: increment() takes 2 positional arguments but 3 were given
#Can only be specified with keyword arguments
>>> increment(1, 2, ignore_error=True)
>>> 

#Position only argument->Arguments for which a formal argument name cannot be specified at the time of calling
# 「/Only the position is an argument before. If a dummy argument name is specified in the abs function, an error will occur.
>>> help(abs)
abs(x, /)
    Return the absolute value of the argument.
>>> abs(x=-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: abs() takes no keyword arguments

Unpacking the argument list


#Pass the value stored in the list as an argument
>>> def greeting(x, y, z):
...     print(x)
...     print(y)
...     print(z)
... 
>>> contents = ['Hello', 'Good morning', 'Bye']
#When calling a function, "*Expand arguments from the list with the operator
>>> greeting(*contents)
Hello
Good morning
Bye

#Pass the value stored in the dictionary as an argument
>>> def say_something(name, greeting):
...     print(name)
...     print(greeting)
... 
>>> dict = {'greeting': 'Hello'}
#When calling a function, "**Expand arguments from the dictionary with the operator
>>> say_something('Julia', **dict)
Julia
Hello

lambda expression

--You can use a lambda expression to create an anonymous function in one line. --Anonymous functions are often used when passing function objects as function arguments.

lambda expression syntax


lambda argument 1,Argument 2,Argument 3, ...:Expression that becomes the return value

Example of lambda expression


>>> increment = lambda num1, num2: num1 + num2
>>> increment(1, 2)
3

#Synonymous with
>>> def increment(num1, num2):
...     return num1 + num2
... 
>>> increment(1, 2)
3

#Only the function whose first argument is true remains.
>>> nums = ['one', 'two', 'three']
>>> filterd = filter(lambda x: len(x) == 3, nums)
>>> list(filterd)
['one', 'two']

Type hint

--Add type information to the function with annotation. --Used to improve the maintainability of the code. You can also use type checking with static analysis tools such as mypy. --Since the type check is not performed at the time of execution, an error does not occur even if you use an unexpected type specified.

Syntax for giving type information


def function name(arg1:Type of arg1, arg2:Type of arg2, ...) ->Return type:
    #The process you want to execute in the function
return Return value

>>> def say_something(name: str, age: int) -> str:
...     print(name)
...     print(age)
...     return name
... 
>>> say_something('Tom', 29)
Tom
29
'Tom'

5. Class / instance

Class definition

Class definition


class class name(Base class name):
def method name(Argument 1,Argument 2, ...):
The process you want to execute in the method
return Return value

>>> class Person(object):
...     def say_something(self):
...         print('Hello!!!')
... 
#Instantiate a class
>>> person = Person()
#Instance method call
>>> person.say_something()
Hello!!!

Instance initialization

Instance initialization


 >>> class Person:
...     def __init__(self):
...         print('Init completed!')
...     def say_something(self):
...         print('Hello!!!')
... 
#Initialization process when an instance is created(__init__Processing defined in)Is called
>>> person = Person()
Init completed!
>>> person.say_something()
Hello!!!

Property

--If you add "@property" to an instance method, you can call that instance method without "()". --Method with "@property"-> Called when getting value (read only)-> getter --"@Methodname.setter"-> Called when assigning a value-> setter --For the method name of setter, you must use the method name with "@property" as it is.

@property(setter)


>>> class Person:
...     @property
...     def name(self):
...         return self._name
...     @name.setter
...     def name(self, name):
...         self._name = name
... 
>>> person = Person()
>>> person.name = 'Tom'
>>> person.name
'Tom'

--Attribute starting with underscore (_name): Expresses that it is a private attribute. --Attribute starting with two underscores (\ _ \ _ name): Name mangling is done. (Example: Convert the variable "\ _ \ _name" of the Person class to "\ _Person__name".) Used to prevent name collisions in subclasses.

Class inheritance

Class inheritance


>>> class Person:
...     def greeting(self):
...         print('Hello')
...     def say_something(self):
...         print('I am human')
... 
>>> class Man(Person):
...     #Method override
...     def say_something(self):
...         print('I am a man')
... 
>>> man = Man()
>>> man.say_something()
I am a man
#Base class(Person class)Methods are also available
>>> man.greeting()
Hello 

6. Module / Package / Namespace / Scope

module

--A .py file with code --A file containing the definitions of classes and functions is called a module.

Creating a module (module name: sample.py)


import sys

def say_something_upper(s):
    #Convert to uppercase
    upper_s = s.upper()
    return upper_s

str = sys.argv[1]
print(say_something_upper(str))

module(sample.py)Call


$ python sample.py hello
HELLO
$ 

Writing code that works only when executed directly

Writing code that works only when executed directly


import sys

def say_something_upper(s):
    #Convert to uppercase
    upper_s = s.upper()
    return upper_s

def main():
    str = sys.argv[1]
    print(say_something_upper(str))

if __name__ == '__main__':
    main()

--If there is no description of "if \ _ \ _ name \ _ \ _ =='\ _ \ _ main \ _ \ _'", it will be executed even if it is imported from another module. --Therefore, describe the conditional statement as described above so that the process is called only when it is directly executed as a script. --The values stored in the global variable "\ _ \ _ name \ _ \ _" are as follows. --Variable "\ _ \ _ name \ _ \ _"-> "\ _ \ _ main \ _ \ _" when executed in interactive mode --Variable when executed as a script "\ _ \ _ name \ _ \ _"-> "\ _ \ _ main \ _ \ _" --Variable "\ _ \ _ name \ _ \ _" when imported as a module-> "Module name" --Therefore, when executed as a script, the conditional statement becomes "true" and the module is executed, and when imported as a module, the conditional statement becomes "false" and the module is not executed.

Creating a package

--To create a package, create a directory and place the "\ _ \ _ init \ _ \ _. Py" file to treat that directory as a package. (Empty file is OK) --It is also possible to write the initialization code of the package in "\ _ \ _ init \ _ \ _. Py" and set the "all.py" variable.

__init__.py


#Empty file is OK

Importing modules in a package

python_programming/sample.py


from python_package import hello

def say_hello():
    print(hello.return_hello())

def main():
    say_hello()

if __name__ == '__main__':
    main()

python_programming/python_package/hello.py


def return_hello():
    return 'Hello!!!'

Execution result


$ python sample.py
Hello!!!
$ 

--How to write import

How to write import


#Import package
import package name
import sample_package

#Import a specific module from a package(from not specified)
import package name.Module name
import sample_package.greeting

#Import a specific module from a package(from specified)
from package name import module name
from sample_package import greeting

#Import only specific attributes from packages and modules
from package name/Module name import Function name
from sample_package.greeting import say_something

#Imported package/module/Give function an alias
from package name import module name as alias
from sample_package.greeting import say_something as s

Bulk import of multiple attributes using wildcards and "\ _ \ _ all \ _ \ _"

Bulk import


#Wildcard(*) To batch import
from package name import*
from sample_package import *

--As mentioned above, import using wildcards is basically not used because it may reduce readability and cause problems due to unintended overwriting of names. --If the code in the "\ _ \ _ init \ _ \ _. Py" of the package defines the list "\ _ \ _ all \ _ \ _", it will be imported during "from package import *" It becomes a list of modules to be. --As an example, if the following is defined, only the "morning", "evening", and "night" modules will be imported even if "from sample_package import *" is executed.

__init__.py


__all__ = ["morning", "evening", "night"]

Premise: There are many modules including" morning "," evening "," night "in sample_package

7. Built-in functions / special methods

Built-in functions

Built-in functions are functions built into Python that can be used without importing anything.

--isinstance (): Returns True if the instance object passed in the first argument belongs to the class passed in the second argument.

isinstance()


>>> d = {}

#The first argument is an instance object
>>> isinstance(d, dict)
True

#If the second argument is a tuple, it will be compared in multiple classes at the same time.
>>> isinstance(d, (list, int, dict))
True

--issubclass (): Almost the same as isinstance (), but takes a class object as the first argument.

issubclass()


#The first argument is a class object
>>> issubclass(dict, object)
True

#bool type is a subclass of int type
>>> issubclass(bool, (list, int, dict))
True

--callable (): Judge callable objects (functions, classes, methods, etc. that can be called with ())

callable()


>>> callable(isinstance) #function
True
>>> callable(Exception) #class
True
>>> callable(''.split) #Method
True

--getattr () / setattr () / delattr (): Manipulate object attributes

getattr()/setattr()/delattr()


#Sample class definition
>>> class Mutable:
...     def __init__(self, attr_map):
...         for k, v in attr_map.items():
...             setattr(self, str(k), v)
... 
#Set attributes to m
>>> m = Mutable({'a': 1, 'b': 2})
>>> m.a
1
>>> attr = 'b'

#Get value
>>> getattr(m, attr)
2

#Delete value
>>> delattr(m, 'a')
>>> m.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Mutable' object has no attribute 'a'

# getattr()Can also get methods
>>> str = 'python'
>>> instance_method = getattr(str, 'upper')
>>> instance_method()
'PYTHON'

--zip (): Returns multiple iterable elements at the same time

zip()


#Summarize the i-th elements of each iterable
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> zip(a, b)
<zip object at 0x10827a7d0>
>>> list(zip(a, b))
[(1, 4), (2, 5), (3, 6)]

# zip()Returns results only up to the shortest iterable length
>>> d = [1, 2, 3]
>>> e = [4, 5, 6, 7, 8]
>>> f = [9, 10]
>>> zip(d, e, f)
<zip object at 0x10827a7d0>
>>> list(zip(d, e, f))
[(1, 4, 9), (2, 5, 10)]

#If you want to fit the longest iterable, the standard library itertools.zip_longest()Use function
>>> from itertools import zip_longest
>>> list(zip_longest(d, e, f, fillvalue=0))
[(1, 4, 9), (2, 5, 10), (3, 6, 0), (0, 7, 0), (0, 8, 0)]

--sort (): Sort the elements of the iterable

sorted()


>>> a = [3, 2, 5, 1, 4]
>>> b = [2, 1, 4, 5, 3]

# list.sort()Sorts themselves
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]

# sorted()Returns a new list
>>> sorted(b)
[1, 2, 3, 4, 5]
>>> b
[2, 1, 4, 5, 3]

# reverse=If True is specified, the order will be reversed.
>>> sorted(b, reverse=True)
[5, 4, 3, 2, 1]

Since sorted () compares elements directly, an error will occur if numbers and strings are mixed

See below for other built-in functions

List of Python built-in functions https://docs.python.org/ja/3/library/functions.html

Special method

A special method is a method with two underscores (__) before and after the method name, which is implicitly called by Python.

Special method


#In the class "Word", a special method, "__init__」「__str__」「__len__Define
>>> class Word(object):
...     def __init__(self, text):
...         self.text = text
...     def __str__(self):
...         return 'Word!!!'
...     def __len__(self):
...         return len(self.text)

#Instantiate a class
>>> w = Word('test')

#When trying to treat w as a string, implicitly "__str__Is called
>>> print(w)
Word!!!

#When I try to run "len" to get the length of w, it implicitly says "__len__Is called
>>> print(len(w))
4

#Original description method (access the text attribute of the instance w and get the value of len)
>>> print(len(w.text))
4

See below for other special methods

Python special method name https://docs.python.org/ja/3/reference/datamodel.html#special-method-names

8. File operations and input / output

Writing a file using open ()

open()Writing a file using


#The first argument is the file name and the second argument is the mode
#Mode (argument is optional, omitted for "r")
#"R": read-only
#"W": Export only
#"A": Addition (addition to the end of the file)
# 「r+": Both reading and writing
>>> f = open('test.txt', 'w')
>>> f.write('Test!')
>>> f.close()
#As follows "test."txt" is generated and "Test"!"Is written.
[localhost]$ cat test.txt
Test!
[localhost]$ 

#It is also possible to write to a file with print
>>> f = open('test.txt', 'w')
>>> print('Print!', file=f)
>>> f.close()
#As follows "test."txt" is generated and "Print"!"Is written.
[localhost]$ cat test.txt
Print!
[localhost]$

#Options when using print
>>> f = open('test.txt', 'w')
>>> print('My', 'name', 'is', 'Tom', sep='###', end='!!!', file=f)
>>> f.close()
#The delimiter is "" specified in sep.###(Default is half-width space), and finally "" specified by end!!!"Is written.
[localhost]$ cat test.txt
My###name###is###Tom!!!
[localhost]$ 

Read a file using read ()

read()Reading a file using


#As a preliminary preparation, "test.txt "prepared
>>> f = open('test.txt', 'w')
>>> print('My', 'name', 'is', 'Tom', end='!\n', file=f)
>>> print('My', 'name', 'is', 'Nancy', end='!\n', file=f)
>>> print('My', 'name', 'is', 'Julia', end='!\n', file=f)
>>> f.close()
[localhost]$ cat test.txt
My name is Tom!
My name is Nancy!
My name is Julia!
[localhost]$

# read()Read the contents of the file using
>>> f = open('test.txt', 'r')
>>> f.read()
'My name is Tom!\nMy name is Nancy!\nMy name is Julia!\n'
>>> f.close()

# readline()Read line by line using
>>> f = open('test.txt', 'r')
>>> f.readline()
'My name is Tom!\n'
>>> f.readline()
'My name is Nancy!\n'
>>> f.readline()
'My name is Julia!\n'
>>> f.close()

Manipulating files using the with statement

Manipulating files using the with statement


# with open()When you manipulate a file using()No processing is required.
>>> with open('test.txt', 'a') as f:
...     print('with open statement!', file=f)
... 
>>> 
[localhost]$ cat test.txt
My name is Tom!
My name is Nancy!
My name is Julia!
with open statement!
[localhost]$

--When performing a file operation with open (), the memory is used until close () is executed, so it is necessary to release the memory by closing () at the end. ――On the other hand, in the case of with open (), when the processing in the indent of the with open () clause is completed, it will close () without permission, so you will not forget to close ().

References / teaching materials

-[O'REILY] "Python Tutorial" [Author] Guido van Rossum -[Technical Review] "Introduction to Python Practice" [Author] Ryo Suyama -[Udemy] "Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style" [Author] Jun Sakai

Recommended Posts

Python3 cheat sheet (basic)
PySpark Cheat Sheet [Python]
Python sort cheat sheet
[Python3] Standard input [Cheat sheet]
Python Django Tutorial Cheat Sheet
Apache Beam Cheat Sheet [Python]
Python cheat sheet (for C ++ experienced)
Python Computation Library Cheat Sheet ~ itertools ~
RF Python Basic_01
Basic Python writing
Curry cheat sheet
Python3 basic grammar
RF Python Basic_02
SQLite3 cheat sheet
pyenv cheat sheet
AtCoder cheat sheet in python (for myself)
Blender Python Mesh Data Access Cheat Sheet
Mathematical Optimization Modeler (PuLP) Cheat Sheet (Python)
Python basic course (12 functions)
Python I'm also basic
Python basic grammar / algorithm
conda command cheat sheet
PIL / Pillow cheat sheet
Python Basic Course (7 Dictionary)
Python basic course (2 Python installation)
Linux command cheat sheet
Basic sorting in Python
Python basic course (9 iterations)
[python] class basic methods
Python Basic Course (11 exceptions)
Python basic course (6 sets)
Spark API cheat sheet
Python basic grammar (miscellaneous)
Python Basic Course (Introduction)
Python basic memorandum part 2
[Updating] Python Syntax cheat sheet for Java shop
python basic on windows ②
Python basic memo --Part 2
Python basic course (13 classes)
Basic Python command memo
Go language cheat sheet
Python basic grammar note (4)
Python basic grammar note (3)
Basic knowledge of Python
Python basic grammar memo
Python pdf cheat sheets
OpenCV basic code (python)
Python basic memo --Part 1
python memorandum super basic
Python basic course (8 branches)
Python basic if statement
Python Basic Course (3 Python Execution)
Python Basic --Pandas, Numpy-
tox configuration file cheat sheet
Basic Python 3 grammar (some Python iterations)
Python application: Pandas Part 1: Basic
Refactoring Learned in Python (Basic)
BASIC authentication with Python bottle
Python basic dict sort order
[Python] Using OpenCV with Python (Basic)
Python basic course (10 inclusion notation)