I hope I can continue to share the basics of Python following Part 1! If you haven't seen it, start with Part 1 ^^
・ If statement ・ For statement ·function ・ Exception handling ・ Pass statement ·scope ·class ·closure ·argument ・ At the end
There is no Java switch-case syntax, but a similar implementation is possible by using the keyword "in". "El if" is an abbreviation for "else if".
・ If statement
val1 = 1
val2 = 2
if val1 == val2:
print('test1')
elif val1 > val2:
print('test2')
else:
print('test3') # test3
-A switch statement-like writing method using the "in" keyword
val3 = 3
if val3 == 1:
print('test1')
elif val3 in(2,3):
print('test2') # test2
elif val3 in(3,4):
print('test3')
else:
print('test4')
The for statement is equivalent to the Java foreach statement. Often used in combination with the range function.
・ For statement and range function
for i in range(3):
print(i) #Displayed in order of 0, 1, 2
・ For statement and character string (list, dictionary, etc. can be used)
for c in 'test':
print(c) # t, e, s,Displayed in order of t
By the way. .. .. Python has a while statement, but no do-while statement.
Use "def" to define the function. * All arguments are passed by reference. ~~ Pass by value.
def fnc(a, b=1): #b is an argument with a default value
return a + b #Return value
#Function call
print(fnc(10)) # 11
-When calling a function, it is possible to ignore the definition order by specifying the argument name.
def fnc(a, b, c):
print(a, b, c)
#Function call
fnc(c=3, a=1, b=2)# 1 2 3
■ Differences between functions and methods You can think of it as almost the same!
** Function **: Those that are not tied to a particular class. What is defined by def in the module. What is defined in def before instantiation in the class is a function. How to write: Function (argument)
** Method **: Dedicated to a particular class (or an instance of that class). ~~ What is defined by def in the class. ~~ After the class is instantiated, the function becomes a method. How to write: Value. Method (argument)
For example, len ("string") is a function that gets the length of a "string", while "string" .split () is a method (object.function) that splits characters by whitespace characters. .. Basically, in the case of a method, there are many processes specific to that object. For example, "string" .split or "string" .startswith. This is string specific. But len can be used for both strings and lists. len ("string") len ([0, 1, 2]). In these cases, Python provides a function.
· What is the difference between a Python function (object) and an object.function ()? http://blog.pyq.jp/entry/2017/09/14/100000
■ Immutable type ・ Numeric types such as int, float, and complex -String type (string) ・ Tuple type ・ Bytes ・ Frozen Set type
■ Mutable type ・ List type (list) -Byte array ・ Set type ・ Dictionary type (dictionary)
Process with the syntax "try ~ except ~ else ~ finally". except is a catch statement in Java, "a statement to be executed when an exception occurs, else describes the process that was not caught by except.
try:
x = 10 / 0
except Exception as e:
print(e) # division by zero
#What to do if no exception occurs
else:
print('test1')
#Processing that always runs regardless of whether an exception occurs
finally:
print('test2')# test2
-Use "raise" to explicitly raise an exception. (Throw statement in Java)
try:
raise Exception('test3')
except Exception as e:
print(e) # test3
Syntax to specify "do nothing". Not in Java.
For example, it is used in the following cases. -Do nothing when conditional branching ・ Do nothing when an exception occurs -The implementation of functions and classes is not clear
#Output only even numbers
for i in range(10):
if(i % 2) == 0:
print(i)
else:
pass
There are four types of scopes as follows. The acronym is called LEGB.
① Local scope → Only in the function. Variables and functions in built-in scope and module scope can be referenced from the local scope, but values cannot be assigned (overwritten) to the variables.
② Enclosing (function's) scope → A scope that is conscious for the first time when a function is defined inside a function.
③ Global Scope → The entire module (entire file).
④ Built-in scope → Can be referenced from anywhere within the scope of built-in variables (None) and built-in functions (print function).
For more information on scope, I referred to this article. Please see if you have time, as the details are described.
The constructor (initialization method) should be "\ _ \ _ init \ _ \ _" or "__new \ ___", and ~~ must define "self" as the first argument. It is customary to use ~~ self, and you can name it this or whatever you like. self is an object that represents an instance of ~~ itself. ~~ Argument name to receive the instance
Name.class
class Name:
#Class variables
LANG = 'JP'
#constructor
def __init__(self):
self.name = ''
# getter
def getName(self):
return self.name
# setter
def setName(self, name):
self.name = name
taro = Name()
taro.setName('Ichiro')
print(taro.getName()) #Ichiro
print(Member.LANG) # JP
A function that references a local variable of the function. You can continue to refer to local variables even after the function call is finished. Almost equivalent to Javascript closures.
For more information on closures, see this article.
There are four types of arguments as follows.
① Normal argument
② Argument with default value → An argument that defines the default value to be adopted when omitted when calling a function.
#② Argument with default value
def fnc(a, b = 1):
return a + b #Return value
③ Variable length argument → An argument that receives one or more values. If you add an asterisk (*) before the argument name, it becomes this argument. On the function side, the received variable length argument is treated as a tuple.
#③ Variable length argument
def fnc(a, b, *args):
print(a, b, args)
fnc('a','b','c','d','e') # a b ('c','d','e')
④ Variable length argument with keyword → A variable-length argument that requires a keyword when specifying the argument. If you add two asterisks (*) before the argument name, it becomes this argument. On the function side, the received variable-length argument is treated as dictionary-type data with the name given at the time of definition.
#④ Variable length argument with keyword
def fnc(a, b, **args):
print(a, b, args)
fnc('a','b',arg1 = 'c',arg2 = 'd',arg3 = 'e')# a b {'arg1': 'c', 'arg3': 'e', 'arg2': 'd'}
#fnc('a','b','c','d','e')← An error will occur if no keyword is specified.
Part 1 & 2 covered the general basics of Python. Python has a wealth of web frameworks and machine learning libraries, so if you combine it with this foundation, can you do what you want? !! I would like to create a Web API using Python from now on: raised_hand:
· What is the difference between a Python function (object) and an object.function ()? http://blog.pyq.jp/entry/2017/09/14/100000
・ About the scope of Python http://note.crohaco.net/2017/python-scope/
・ [Python] What is closure (function closure)? https://qiita.com/naomi7325/items/57d141f2e56d644bdf5f
-Pass by value and pass by reference in Python https://crimnut.hateblo.jp/entry/2018/09/05/070000
・ AmadaShirou.Programing Keikensya No Tameno Python Saisoku Nyumon (Japanese Edition) Kindle Edition
Recommended Posts