I started python

Introduction

Describes the basic writing method of Python. The version is 3.4.3.

comment

Comments start with "#".

#This is a comment

Numerical value

There are integers, floating point numbers, and complex numbers.

#Four arithmetic operations
2 + 3 # 5
2 - 3 # -1
2 * 3 # 6

#Integer division is a floating point number
2 / 3 # 0.6666666666666666

# //The integer part after division can be extracted by calculation
3 // 2 # 1

# **Exponentiation
2 ** 10 #1024 2 to the 10th power

#Complex number
(1+1j) + (2+2j) # (3+3j)Imaginary unit is j, 1 of 1j cannot be omitted
c = 1 + 2j
c.real #1.0 Real part
c.imag #2.0 imaginary part

sequence

A data structure in which elements are arranged in numerical order. Each element is accessible with an integer index starting at 0.

The next data structure is sequence.

The sequence is explained using List as an example.

l = [1,2,3]
l[0]        #1 element 0 index starts with 0
l[2]        #3 element 2
l[-1]       #3 element 3 index can be negative
len(l)      #Number of 3 elements
max(l)      #3 maximum value
min(l)      #1 minimum value
l.count(1)  #1 Number of appearances
1 in l      #Whether True element is included
3 in l      # False 
1 not in l  #False element is not included or in is inverted

#Returns a List with a range
l[:]        # [1,2,3]Returns all elements as a List
l[1:2]      # [2]     a:a to b in b format-Returns elements up to 1 as a List
l[0:]       # [1,2,3] a:Returns the elements from a to the end in the format as a List
l[:2]       # [1,2]   :b from the beginning in b format-Returns elements up to 1 as a List

String

A sequence whose element is a character. You cannot change the element.

s = "string" #The string is"Come out
s = 'string' # 'But OK

#You can access the character with an integer index
s[0] # 's'

#Element cannot be changed
s[0] = "S" #error

#Multi-line strings" or 'I will put together 3 pieces
'''
Multiple lines
String
'''

#Connect strings
"a" + "b" # 'ab'

#Repeat the string
"a" * 2 # 'aa'

#Split the string
"1,2".split(",") # ['1', '2']List returns

#Combine strings
",".join(["1","2"]) # '1,2'

#Convert a string to a number
int("0x10", 16) #16 The second argument is the radix
int("10")       #10 If the second argument is omitted, the radix is treated as 10.
int("10", 2)   # 2
float("1.2")    # 1.2

#Converts a number to a string
"dec:{0},hex:{0:X},bin:{0:b}".format(16) # 'dec:16,hex:10,bin:10000'
"{0:.2f}".format(3.1415) # '3.14'

list It is a sequence that can be an element of arbitrary data. You can change the element.

l = [1,2,3] # ,Separation,"[]"Come out
l[0]        #1 element 0 index starts with 0
l[2]        #3 element 2
l[-1]       #3 element 3 index can be negative

#Add an element at the end
ll = l + [4] # ll = [1,2,3,4]Add element(+)
l.append(4)  # l  = [1,2,3,4]Add element(append)

#Extract the element from the end
l = [1,2,3]
l.pop #3 Result l= [1,2]

#Returns the element iteration
l = [2]
l * 2  # [2,2]

#You can use comprehension notation to initialize the list
# []Write the for statement inside
l = [x for x in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#Multidimensional list
#2D:queue
m = [[row for row in range(2)] for col in range(3)] # [[0, 1], [0, 1], [0, 1]]
#3D
m = [[[row for row in range(2)] for col in range(3)] for mat in range(4)]

tuple It is a sequence that can be an element of arbitrary data. ** You cannot change the element. This is the difference from List. ** **

t = (1,2,3) # ,Separation,"()"Come out
t[0] = 10   #Error, element cannot be changed

range A sequence that can have a numerical value as an element. You cannot change the element. It is used in combination with the for statement.

# range(x)At 0~x-Represents 1
# 0~9 is displayed
for i in range(10):
	print(i)
	

# range(x, y)With x~y-Represents 1
# 1~9 is displayed
for i in range(1, 10):
	print(i)
	

# range(x, y, step)With x,x+step, x+2*step, ... (y-Up to 1)Represents.
# 1,3,5,7,Represents 9.
for i in range(1, 10, 2):
	print(i)
	

Control statement

if Comparison conditions can be specified in the format aaa <x <bbb. You can use ʻin and ʻis operations.

# if .. elif .. else
x = 1
if x == 1:
	print("x == 1")
elif x == 2:
	print("x == 2")
else:
	print("else")
# result : x == 1

# < x <Calculation
x = 5
if 1 < x < 6:
	print("True")
else:
	print("False")
# result : True

#in arithmetic
if 0 in [1, 2, 3]:
	print("True")
else:
	print("False")
# result : False

#not in operation
if 0 not in [1, 2, 3]:
	print("True")
else:
	print("False")
# result : True

#is operation, determines if they are the same object
if [1] is [1]:
	print("True")
else:
	print("False")
# result : False

l = [1,2,3]
ll = l
if l is ll:
	print("True")
else:
	print("False")
# result : True

for break / continue is the same as any other language. else is characteristic. else is executed when the for statement is executed to the end. When it stops at break, else is not executed.

# range
for i in range(10):
	print(i)
# result : 0~10

# list
for i in [1, 2, 3]:
	print(i)
# result : 1~3

# else/break
#You can attach else.
#Else is executed when for is executed to the end.
#It will not be executed when it breaks.
for i in [1, 2, 3]:
	print(i)
	if i == 2:
		break
else:
	print("else")
# result : 1~2,else is not displayed

while Like for, you can add else.

i = 0
while i < 10:
	print(i)
	if i == 1:
		break
	i = i + 1
else:
	print("else")
# result : 0~1

function

You can call a function by specifying an argument name such as f (x = 10, y = 20). It is easier to read and you can change the order of the arguments.

#Define a function that returns the total value
def sum(l):
	val = 0
	for i in l:
		val = val + i
	return val
	
print(sum([1, 2, 3]))
# result : 6

#You can specify the default argument
def add(x=10, y=20):
	return x + y
	
print(add())
# result : 30

#You can call it by specifying the argument name, and you can change the order of the arguments.
def sub(x, y):
	return x - y
	
print(sub(y=20, x=10))
# result : -10

module

A file containing classes and functions is called a module. The extension is .py. The module name is the file name excluding .py. It is convenient to organize frequently used functions in a module so that they can be reused.

#Import the module with import.
import numpy as np #Define alias with as
a = np.array([1,2,3]) #Refer to a module member with the alias np

#When referencing a module member when simply importing
#Module name(or alias)Qualified with(e.g. np.array)need to do it.
#You can omit the qualification by using from.
from numpy import array
a = array([1,2,3]) #OK without np

# *It is also possible to specify all with
from numpy import *

class

Defining a class creates a corresponding class object. The constructor name is __init__. Takes self as an argument. self is a keyword for referencing your own object.

Class objects include

--Class variables --Instance variables --Class method --Instance method --Static method

Variables and methods have public and private scope. Prefix the name with __ to make it private. Private items cannot be accessed from outside the class.

#Define a class
class Test:
    #Class variables
    i   = "pub class var" #public
    __i = "prv class var" #private
    
    #Instance method
    def method(self):
        print("pub inst method")
    
    def __method(self):
        print("prv inst method")
        
    #Class method
    @classmethod
    def cls_meth(cls):
        print("cls_meth")
    
    #Static method
    @staticmethod
    def stat_meth():
        print("stat_meth")
    
    #constructor
    def __init__(self):
        #Instance variables
        self.j   = "pub inst var" #public
        self.__j = "prv inst var" #private
        
        print("__init__")
        #public
        print(Test.i)   #Class variable class.name format
        print(self.i)   #Class variable obj.name format
        print(self.j)   #Instance variable obj.name format
        self.method()   #Method
        
        #private
        print(self.__i) #Class variable class.name format
        print(self.__j) #Instance variable obj.name format
        self.__method() #Method

#Create an instance
t1 = Test()
t2 = Test()

#Browse variables
print(Test.i) #1 Class variable class.name format
print(t1.i)   #1 Class variable obj.name format
print(t1.j)   #2 Instance variable obj.name format

#You can define class variables and instance variables with the same name.
#It's a source of confusion, so don't use it like this.
t1.i = 10
print(t1.i)   # 10 obj.Priority is given to get the name. Class variable i cannot be referenced from t1
print(Test.i) # 3
print(t2.i)   # 3

#Dynamic variable addition
t1.x = 10    #You can add instance variables dynamically.
print(t1.x)  # 10
del t1.x     #Delete
Test.x = 20   #You can add class variables dynamically.
print(Test.x) # 20
del Test.x    #Delete

#Call the method
t1.method()
#t1.__method() #error

#Class method call
Test.cls_meth()

#Static method call
Test.stat_meth()

Inheritance

By writing class Child (Parent) in the class definition You can define a Child class that inherits from Parent.

You cannot access the private members of the parent class from the child class. You can override the methods of the parent class from the child class. To define an instance variable for a parent class, in the constructor of the child class You need to call the constructor of the parent class.

#Define the parent class
class Parent:
    i   = "pub class var"
    __i = "prv class var"

    def __init__(self):
        self.j   = "pub inst var"
        self.__j = "prv inst var"

    def meth(self):
        print("pub inst meth")
        print(self.i)
        print(self.__i)
        self.__meth()

    def meth2(self):
        print("pub inst meth2")
        print(self.j)
        print(self.__j)

    def meth3(self):
        print("pub inst meth3")

    def __meth(self):
        print("prv inst meth")

#Define a child class
class Child(Parent):
    def __init__(self):
        #Call the constructor of the parent class
        #Without this, the instance variable of the parent class will not be defined
        #Meth2 from child class will result in error
        Parent.__init__(self) 

    #override
    def meth3(self):
        print("child pub inst meth3")

    def meth4(self):
        self.__meth()

#Create an instance
p = Parent()
p.meth()
p.meth2()
p.meth3()
c = Child()
c.meth() 
c.meth2() 
c.meth3() #Child class meth3 is called
#c.meth4()
#Will result in an error
#Child class cannot access parent class private methods

exception

try:
	int("xxx") #Exception occurs because it is not a numerical value
except OSError:
	print("OSError")
except ValueError:
	print("ValueError")
# resutl : ValueError

#If there are no exceptions, else will be executed
try:
	int("10")
except OSError:
	print("OSError")
except ValueError:
	print("ValueError")
else:
	print("NoError")
# resutl : NoError

#Finally is executed with or without exceptions
try:
	int("xxx")
except OSError:
	print("OSError")
except ValueError:
	print("ValueError")
finally:
	print("Finally")
# resutl : ValueError Finally

File

#You can use with to close correctly even if an exception occurs
with open("tmp.txt", "a") as f:
	f.write("test\n")

#You can use the for statement to handle all lines
with open("tmp.txt", "r") as f:
	for ln in f:
		print(ln)

Command line arguments

Command line arguments go into sys.argv. sys.argv [0] is the script name. sys.argv [1] is the first argument.

test.py


import sys
print(sys.argv)
>python test.py param1 param2
['test.py', 'param1', 'param2']

Regular expressions

import re

ln = "<tag>1234</tag>"
#Define a regular expression.()You can group with.
r = re.compile("<tag>(.+)</tag>")
#Search.
m = r.search(ln)
#If there is no match, m will be None
print(m.group(0)) #The entire matched string"<tag>1234</tag>"
print(m.group(1)) # ()The character string grouped by is returned."1234"

Recommended Posts

I started python
started python
I started Docker
Django 1.11 started with Python3.6
1.1 Getting Started with Python
I started to analyze
I tried Python> autopep8
Getting Started with Python
I implemented Python Logging
Relearn Python (Algorithm I)
Getting Started with Python
I tried Python> decorator
Why I chose Python
I compared Python more-itertools 2.5 → 2.6
I started machine learning with Python Data preprocessing
I tried fp-growth with python
I tried scraping with Python
Getting Started with Python Functions
I wrote python in Japanese
curl -I python one liner
Python
I tried to get started with blender python script_Part 01
I made blackjack with python!
I started PYNQ (2) -Overlay self-made-
I compared Java and Python!
Getting Started with Python Django (4)
I tried to get started with blender python script_Part 02
5 reasons I got into Python
Getting Started with Python Django (3)
I tried Python C extension
[Python] I tried using OpenPose
Python started by C programmers
I made a python text
Getting Started with Python Django (6)
Get started with Python! ~ ② Grammar ~
I ran python on windows
I tried gRPC with Python
I tried scraping with python
I understand Python in Japanese!
I made blackjack with Python.
What I learned in Python
I learned Python basic grammar
IfcOpenShell python bindings get started
Python3 | Getting Started with numpy
I made wordcloud with Python.
Getting Started with Python Django (5)
I downloaded the python source
[Python] I started Poetry & Impression that I moved from Pipenv to poetry
I started machine learning with Python Clustering & Dimension Compression & Visualization
[Python3] List of sites that I referred to when I started Python
Getting Started with Python responder v2
I started, but it doesn't start!
Get started with Python! ~ ① Environment construction ~
Link to get started with python
I made a Line-bot using Python!
I tried to touch Python (installation)
I can't install python3 with pyenv-vertualenv
Getting Started with Python Web Applications
I checked Mac Python environment construction
I tried web scraping with python.
I can't remember Python regular expressions