[For beginners] Basics of Python explained by Java Gold Part 2

Overview

I hope I can continue to share the basics of Python following Part 1! If you haven't seen it, start with Part 1 ^^

agenda

・ If statement ・ For statement ·function ・ Exception handling ・ Pass statement ·scope ·class ·closure ·argument ・ At the end

if statement

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')

for statement

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.

function

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)

Exception handling

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

pass statement

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

scope

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.

class

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

closure

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.

argument

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.

At the end

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:

References

· 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

[For beginners] Basics of Python explained by Java Gold Part 2
[For beginners] Basics of Python explained by Java Gold Part 1
Basics of Python × GIS (Part 1)
[Linux] Basics of authority setting by chmod for beginners
Basics of Python x GIS (Part 3)
■ Kaggle Practice for Beginners --Introduction of Python --by Google Colaboratory
[Must-see for beginners] Basics of Linux
Basics of Python x GIS (Part 2)
Learn the basics of Python ① Beginners
[Python] Minutes of study meeting for beginners (7/15)
[Learning memo] Basics of class by python
Pandas of the beginner, by the beginner, for the beginner [Python]
A textbook for beginners made by Python beginners
Basics of Python ①
Basics of python ①
Python learning memo for machine learning by Chainer Chapter 13 Basics of neural networks
For new students (Recommended efforts for Python beginners Part 1)
Easy understanding of Python for & arrays (for super beginners)
[Python for Hikari] Chapter 09-01 Classes (Basics of Objects)
Basics of pandas for beginners ② Understanding data overview
Basic story of inheritance in Python (for beginners)
Python basics ② for statement
Basics of Python scraping basics
python textbook for beginners
# 4 [python] Basics of functions
Basics of python: Output
OpenCV for Python beginners
Image processing by matrix Basics & Table of Contents-Reinventor of Python image processing-
Summary of pre-processing practices for Python beginners (Pandas dataframe)
Learning flow for Python beginners
Sample source of Observer pattern realized by Java, PHP, Python
[For beginners] Summary of standard input in Python (with explanation)
python: Basics of using scikit-learn ①
Python3 environment construction (for beginners)
Overview of Docker (for beginners)
Python #function 2 for super beginners
Seaborn basics for beginners ④ pairplot
Basic Python grammar for beginners
Pandas basics for beginners ④ Handling of date and time items
100 Pandas knocks for Python beginners
[Python] The biggest weakness / disadvantage of Google Colaboratory [For beginners]
Python for super beginners Python #functions 1
Python #list for super beginners
What beginners learned from the basics of variables in python
~ Tips for beginners to Python ③ ~
[Python machine learning] Recommendation of using Spyder for beginners (as of August 2020)
Wrap (part of) the AtCoder Library in Cython for use in Python
A brief summary of Graphviz in python (explained only for mac)
Seaborn basics for beginners ① Aggregate graph of the number of data (Countplot)
Python techniques for those who want to get rid of beginners
Implementation example of hostile generation network (GAN) by keras [For beginners]
Automatic creation of 2021 monthly calendar (refill for personal organizer) by Python
Paiza Python Primer 5: Basics of Dictionaries
Pandas basics for beginners ① Reading & processing
Pandas basics for beginners ⑧ Digit processing
Python Exercise for Beginners # 2 [for Statement / While Statement]
Expansion by argument of python dictionary
Python for super beginners Python # dictionary type 1 for super beginners
Machine learning summary by Python beginners
Seaborn basics for beginners ② Histogram (distplot)
Getting Started with Python Basics of Python