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")
>>> tax = 12.5 / 100
>>> price= 100.5
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_,2)
113.06
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
・ Compare until one of the sequences runs out
・ Do not compare the same elements
・ Comparison result of different elements
-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
Escape sequence counts with one character
Line breaks\n counts as one character
range function
>>>print(range(5))
range(0,5)
・ The range function is iterable.
・ The range function is an object
Built-in function
>>>dir(Module name) #dir is a built-in function. Show all names defined by the module.
python
・ The generality of data types is high, the problem domain is wider than Awk / Perl, and equal to or better than other languages.
Start the interpreter
>>> python -c command
>>> python -m module name
>>>
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'
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
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.
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
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]
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
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
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
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