Python tutorial summary

print statement

print statement


%s #String
%r ...
%d #integer
%f #Fixed-point notation
%1.5f #Fixed-point notation(,5 is a decimal digit)
%e #Exponential notation
print("Number 1=%f,Number 2=%.3f" % (1/3, 1/3))
Number 1=0.333333,Number 2=0.333

Set what to add at the end by putting a value in the argument "end"

print("a", end=",")
print("b", end=",")
print("c")

Variable containing the last displayed expression in interactive mode

>>> tax = 12.5 / 100
>>> price= 100.5
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_,2)
113.06

Module search path

  1. Inside the built-in module
  2. List of directories obtained with the sys.path variable
  3. Directory with input scripts 4.PYTHONPATH
  4. Default per installation

Coding style

Python coding style is called ** PEP8 **

Coding style


・ 4 spaces for indentation
・ Tab prohibited
・ 4 spaces are a good compromise between narrow indentation and wide indentation.
-Independence of comment lines.
・ Dockstring
-Encoding is UTF-8(default)・ ASCII
-Put a space around the operator and after the comma
・ Do not put a space just inside the parentheses

Comparison of sequence objects

・ Compare until one of the sequences runs out
・ Do not compare the same elements
・ Comparison result of different elements

Class variables and instance variables

-What is a class variable? ... ** Memory shared by all ** instances ** -What are instance variables? ** Memory of ** unique ** for each ** instance

The following is an example of a mistake ... Do not use mutable for class variables

Class variables and instance variables


class Sample:
  c_list = []・ ・ ・ Example of using class variables incorrectly
  def add_c_list(self,data):
    self.c_list.append(data)

print("Output result:", end=" ")
sample1 = Sample()
sample1.add_c_list("Data 1")

sample2 = Sample()
sample2.add_c_list("Data 2")

for item_data in sample1.c_list:
  print(item_data, end=" ")
=============================
Output result:Data 1 Data 2

Disable escape sequences

len function

Escape sequence counts with one character
Line breaks\n counts as one character

range function

range function


>>>print(range(5))
range(0,5)

・ The range function is iterable.
・ The range function is an object

Built-in function

Built-in function


>>>dir(Module name) #dir is a built-in function. Show all names defined by the module.

Chapter 1 Let's Appetite

python


・ The generality of data types is high, the problem domain is wider than Awk / Perl, and equal to or better than other languages.

Chapter 2 How to use the interpreter

Start the interpreter


>>> python -c command
>>> python -m module name
>>> 

Chapter 3 Easy Introduction

operator


-The power operator is exceptionally evaluated from right to left because it has a higher priority than other operators.
-When the type to be calculated is confused(int,float), Integers are converted to floating point

Characteristic of character string


>>> word[10000] #Error if you specify an index that is too large
IndexError  Traceback (most recent call last)
<ipython-input-4-47f442646512> in <module>
----> 1 Zen[50]

IndexError: string index out of range

>>> word[10000:20000] #Slicing out of range is handled well
''

Cancel a newline character that spans multiple lines


print("""\
Usage:thingy[options]
    -h                Display this usage message
    -H hostname       Hostname to connect to
""")

Calculator in interactive mode. underscore


The last displayed expression is the variable "_"(Underscore).
>>> tax = 12.5/100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_,2)
113.006

Interactive mode


Enumerated character literals are automatically concatenated

>>> 'Py' 'thon'
'Python'

Chapter 4 Control structure tool

Unpacking the list


>>> list(range(3,6)) #Calls with common individual arguments
[3,4,5]

>>> args = [3,6] #From here on, a special method
>>> list(range(*arg)) # *Unpacked with arg. Just 3,It becomes 6.
[3,4,5] # range(3,6)Same as

>>> 

documentation(docstring)


・ Line 1: A brief summary. Beginning with a capital letter, ending the period.
・ Second line: Blank
・ Third line:

Function annotation


def function name(arg1: 'Description of arg1', arg2: 'Description of arg2', , ,)->'Description of the return value':
processing

Example of docstring and function annotation


def my_func(n: 'Start adding from this value', m:'Add up to this value') -> 'Total value from n to m':
    """A function that returns the sum from n to m"""
    ret = 0
    for i in range(n, m+1):
        ret += i 
    return ret

Chapter 5 Data structure

Use the list as a queue


>>> from collections import deque
>>> queue = deque(["A","B","C"]) #Made a cue
>>> queue.append("D") #Add D
>>> queue.popleft() #Take out the first
>>> queue.pop() #Take out the last
>>> queue.pop(idx) #Extract idxth

dictionary


・ Key: Immutable type
-Value: changeable type
・ Confirm and obtain (search) the existence of the key key:in operator
-Check and get (search) the existence of the value value:in operator, values()
-Confirm the existence of a combination of key key and value value:in operator, items()

Multidimensional list sorting



operator


Comparison operator< <= == != is  is not  in  not in

Supplementary information about conditions


・ Comparison operators in and not in ・ ・ ・ Presence / absence of sequence values
・ Operators is and is not ・ ・ ・ Comparison of objects
・ Boolean operator and and or ・ ・ ・ Short circuit operator
・ Combination of comparisons (multiple conditions) if x<y and x>z

Operator precedence


Numerical operator> Comparison operator

Sequence comparison, other type comparison


・ When the two are basically the same sequence and the length of one is short, this shorter one is smaller.
-For the dictionary order of character strings, compare by Unicode code point number of each character.

Chapter 6 Modules and Packages

dir function


>>> import sys,fibo
>>> dir(fibo)

-Used to check the name defined by the module.

** For module search, in the case of XX module, XX.py is searched in the following order **

Module search path


1. 1. Search in the built-in module
2.sys.Spam using the list of directories obtained with the path variable.Search for py
2-1. Directory with input scripts
  2-2.PYTHONPATH
2-3. Default per installation

module


-A module is a file
-The module file is ".py」

package


-Packages are folders

>>>from package name import module name#With this you don't have to make it short and full name when referencing a module
>>>import package name.Module name#This requires a long, full name when referencing the module.[Dot delimited module name]Called.

package implementation example



>>> import sound.effects.echo
>>> sound.effects.echo.echofilter()#Loading submodules. The reference is the full name. It's not long! !!

>>> from sound.effects import echo
>>> echo.echofilter()#The reference can be short! !!

Compiled python file


・ Python.Compiled Python code other than py.You can also run a file called pyc
-Since it is an interpreter, it is converted to a binary file line by line.
-Compiler converts all at once to binary file

image.png

Chapter 8 Errors and Exceptions

Overview


・ "Error" is roughly divided into "syntax error" and "exception".
・"Syntax error"Is called "parse error" or "syntax interpretation error"
-"Exception" is "an error that occurs when executing even if the statement or expression is correct"

exception


ZeroDivisionError
NameError
TypeError
KeyboardInterrupt #Keyboard interrupt exception[Ctrl]+[c]

Chapter 9 class

Chapter 10 Standard Library Tour (Module)

Reference module name shortened


>>>from package name.Submodule name import module name#With this you don't have to make it short and full name when referencing a module
>>>import package name.Module name#This requires a long, full name when referencing the module.[Dot delimited module name]Called.

module


import os #Functions that interact with the operating system
import glob #Wildcard search for files
import sys #Handle command line arguments
import re #Regular expressions
import math #Floating point mathematics
from struct import * #binary
import random #random
import collections #list
import logging #Log

Command line arguments


>>> import sys
>>> print(sys.argv)

random module ・ ・ ・ Random sampling tool


>>> import random
>>> random.choice(['apple','banana','lemon']) #choice is selected from the list
'apple'
>>> random.sample(range(100),10) #sample extracts the second argument from the first argument without duplication
>>> random.random() #Random floating point

>>> radom.randrange(6) # range(6)Randomly selected integer from

Chapter 11 Visiting the standard library

Log


・ Is it log output?(Program executor)It is possible to distinguish whether it is output as information that you want to convey to
-Log types can be divided into levels such as Error and Debug.
・ If you specify the format, unified output is easily possible.

Log priority (lowest priority from left)


Low <-> High
DEBUG、INFO、WARNING、ERROR、CRITICAL

Chapter 12 Virtual environment and package

Package management with pip


>>>pip install package name#Install the latest version of the package
>>>pip install package name==2.6.0 #Install a specific version of the package
>>> pip install --upgrade package name#Upgrade to the latest version
>>>pip uninstall package name#Uninstall package
>>> pip list #Installed confirmation
>>> pip freeze #Installed confirmation(Output format is pip install)
>>>pip show package name#Detailed display of package version,author,summar,Description hp

Virtual environment


>>> deactivate #Virtual environment end

Chapter 14 Input line editing and history replacement in an interactive environment

Source code encoding


-Python source code encoding: UTF-8
・ When you dare to change the encoding, it will be as follows
#-*- coding:Encoding name-*-

End of interpreter


ctrl+d
>>>exit()
>>>quit()

Tab completion and history editing


Interactive interpreter


bpython
IPython

Exit the activated state



Interactive primary / secondary prompt


>>> 
...

Recommended Posts

Python tutorial summary
Python Django tutorial summary
Python Summary
Python tutorial
Python summary
Python Django Tutorial (5)
Python Django Tutorial (8)
Python Django Tutorial (6)
python related summary
Python Django Tutorial (7)
Python Django Tutorial (1)
Python Django tutorial tutorial
Python Django Tutorial (3)
Python basics summary
Python Django Tutorial (4)
Summary about Python scraping
[Docker] Tutorial (Python + php)
Summary about Python3 + OpenCV3
Python function argument summary
Python directory operation summary
Python AI framework summary
Python iteration related summary
Python OpenCV tutorial memo
Summary of Python arguments
[Python tutorial] Data structure
Cloud Run tutorial (python)
Python3 programming functions personal summary
Summary of python file operations
Summary of Python3 list operations
[Python tutorial] Control structure tool
Python
What's new in Python 3.10 (Summary)
Standard input / summary / python, ruby
Python class member scope summary
Python web programming article summary
[Python] Decision Tree Personal Tutorial
python pandas study recent summary
Python Competitive Programming Site Summary
Python data type summary memo
Face detection summary in Python
Python Django Tutorial Cheat Sheet
What's new in Python 3.9 (Summary)
Python Crawling & Scraping Chapter 4 Summary
[Python] Building a virtual python environment for the pyramid tutorial (summary)
EEG analysis in Python: Python MNE tutorial
Virtual Environment Version Control Summary Python
Summary if using AWS Lambda (Python)
R / Python coding rule link summary
A brief summary of Python collections
Machine learning summary by Python beginners
selenium case study summary python pyCharm
Python package management tool personal summary
Django Girls Tutorial Summary First Half
Python parallel / parallel processing sample code summary
[Introduction to Udemy Python 3 + Application] Summary
Summary of Python indexes and slices
[OpenCV; Python] Summary of findcontours function
[Python Tutorial] An Easy Introduction to Python
kafka python
[Python] Summary of how to use pandas
Python basics ⑤