Python basic grammar memo

block

--Blocks like {} such as Java are indented.

comment

--The comment is #. With triple quotes, it can be used as a multi-line comment.

variable

--Creating a variable variable name = value --Variable names are generally separated by _, such as sample_color. --There are basically no constants like const. Name with uppercase letters and underscores, such as CONST_VALUE = 100. --You can check the type with the type () function. --You can find out the id number of an object with ʻid (object) `.

Numeric type

--There are three types of Python numeric types: integer type (int), floating point type (float), and complex number type (complex). --Literal, 5 is an int, 5.0 is a float, 0xff = 255 is a hexadecimal number, 0o23 = 19 is an octal number, and 0b1111 = 15 is a binary number. --You can convert string type to float type with float ("160.5 "). --Exponential notation 9.5e3 == 9.5 * 10 ** 3 --Convert from character type to integer type with ʻint ("5") . Convert hexadecimal numbers to integer types with ʻint ("FFF", 16) . --Convert from numeric type to character type with str (numerical value). Use hex () ʻoct () `` bin () `to convert to hexadecimal, octal, and binary character types, respectively.

operator

--The four arithmetic operations are +-* / --Exponentiation is ** --Truncate division, // --Remainder, % --As the assignment operator, + =-= * = / = // =% = can be used. ++ -- cannot be used.

String type

--Enclose the string type in single or double quotes. Escape with \. --To write a string on multiple lines, enclose it in triple quotation marks. --Strings can be combined with +.

print function, input function

--Display on the screen with print (argument 1, argument 2, ...). Avoid line breaks print (argument 1, argument 2, ..., end =" ") --To input from the keyboard, the string type is returned as str = input ("Enter: ").

Sequence type (list, tuple, string, etc.)

--Create a list type like height = [180, 165, 159, 171, 155]. --Retrieve the contents of the list type like height [0]. --You can change the contents like height [1] = 182. --Get the rightmost value with height [-1]. --Return the length of the list with len (height). --Create a tuple type like height_tuple = (180, 165, 159, 171, 155). Tuples are lists whose values cannot be changed. () can be omitted. How to retrieve the value is the same as the list. --You can convert between list and tuple with list () tuple ().

import

--ʻImport Import the module with the module name. --Create an instance of the class by calling module name.constructor. --Call a method with instance variable.method name (argument, ...)`.

import calendar
cal = calendar.TextCalendar()
cal.prmonth(2016, 1)

-- from module name import If you specify class name 1, class name 2, ..., you can omit the module name when calling the class.

from calendar import TextCalendar
cal = TextCalendar()
cal.prmonth(2016, 1)

--Import function modules (same as class import) --When import module name, you can call the function with module name.function name. --from module name import When function name 1, function name 2, ..., the function name can be called directly. --Load all functions with from module name import *`.

Use of random numbers

if statement

if conditional expression A:
Process 1
elif conditional expression B:
Process 2
else:
Process 3

--Use ʻand ʻor as the logical operator. --The conditional expression can be written as 3 <= month <5. --Lists and tuples can be determined by ʻin`` 3 in [1, 2, 3, 4] --3 not in [1, 2, 3, 4]can be used to determine if it is not included withnot in --ʻIn not in can also be used for character strings"day" in "Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday" --There is no switch statement in Python. --You can use the ternary operator as follows.

Value 1 if conditional expression else value 2

msg = "Hello" if hour < 18 else "Good evening"

Loop processing

--Python has no do ~ while loop --range ([start,] end [, step])

#for statement
for l in list:
processing

#Repeat 10 times(i=1〜9)
for i in range(10):
processing

#Convert range object to list
l = list(range(0, 31, 10))
# i=[0, 10, 20, 30]

# while
while conditional expression:
processing

--You can use the enumerate () function to retrieve index / element pairs.

countries = ["France", "America", "China" , "Germany" , "Japan"]
for index, country in enumerate(countries):
  print(str(index + 1) + ":", country)

--The zip (List 1, List 2, ...) function allows you to retrieve multiple list values in sequence as tuples until there are no more elements in the shortest list.

weekday1 = ["Sun", "Mon", "Tue" , "Wed" , "Thu"]
weekday2 = ["Day", "Month", "fire" , "water" , "wood", "Money", "soil"]
for (eng, jap) in enumerate(weekday1, weekday1):
  print(eng + ":" + jap)

--You can write the process when the for loop ends with else. However, it will not be executed when it is broken by break.

for variable in iterable object:
Loop body
else:
Block to be executed when completed

Exception handling

――If you do not specify an exception with except, you can catch any exception. --With except, you can specify multiple exceptions using tuples. --You can describe the processing when an exception does not occur with else.

try:
Processing that may cause an exception
except exception:
What to do if an exception occurs
else:
What to do if no exception occurs

Utilization of character strings

--Output uppercase letters with " python ".upper (). --Output lowercase letters with " python ".lower (). --Count the number of occurrences of the character string specified by " python ".count ("y "). --True / False returns whether to end with the string specified by " / python / ".startswith ("/ "). --True / False returns whether to end with the string specified by " / python / ".endswith ("/ "). --True / False returns whether the string specified by " python ".find (" t ") is included. --Concatenates and returns the string and list specified by ", ".join (list).

Basic operation of lists and tuples

--Combine lists with +. [" Spring "," Summer "] + [" Autumn "," Winter "] # ['Spring',' Summer','Autumn','Winter'] (Create a new list) --Repeat the list with *. [" Spring "," Summer "] * 3 # ['Spring',' Summer',' Spring',' Summer',' Spring',' Summer'] (Create a new list) --Fetch elements with list [start position starting from 0: next number after end position starting from 0]. --You can retrieve elements for each step with [:: Number of Steps]. --In element in list you want to find, return True / False whether it exists. Returns that it does not exist with not in. --Returns the order in list.index (element to look for), but returns a ValueError exception if not found. --Change the value of the list with list [index] = value. If no index is found, a ʻIndexErrorexception is thrown. --You can add values to the list withlist.append (values you want to add). When you add a list, it is added as an element and the list is nested. --You can remove the first element that matches a value with list.remove. (Even if they match, the second and subsequent ones will not be deleted) --You can delete the element of the specified index in the del list [index]. --In the del list [1: 4], indexes 1-3 can be deleted. --max (list) min (list) sum (list) returns the maximum, minimum, and total values, respectively. --Use the == operator to see if the lists have the same value. Use the ʻisoperator to determine if an object is the same. --Uselist.reverse ()` to reverse the list itself.

Command line arguments

--The command line arguments can be listed from sys.argv, the 0th is the executable program file name, and the 1st ~.

import sys
#Enumerate to get the index number()Use a function
for i,a in enumerate(sys.argv):
    print(i,a)

dictionary

--Dictionary {Key 1: Value 1, Key 2: Value 2, Key 3: Value 3, ...} --The number of elements is len (dictionary) --Tuples can be used for dictionary keys {("Japan "," Tokyo "):" Chiyoda Ward ", ("Japan "," Chiba Prefecture "):" Funabashi City ", ("Japan "," Saitama Prefecture " "):" Kawaguchi City "} --Retrieving the value Dictionary [key] --Update value Dictionary [key] = New value --Adding a pair Dictionary [key to add] = Value to add --Delete the pair del dictionary [key] --If you specify a key that does not exist, a KeyError exception will be thrown. --Check if the key exists Key in dictionary`` --Used in for statements (iterate) --Get a list of keys Dictionary.keys () --Get a list of valuesDictionary.values () --Get a list of pairsDictionary.items ()` --A program that counts the number of fruits that appear in a character string

fruits = "apple orange strawberry banana orange apple grape strawberry apple"

count = {}

fruits_list = fruits.split(" ")

for f in fruits_list:
    if f in count:
        count[f] += 1
    else:
        count[f] = 1

for k, v in count.items():
    print(k, v)

# apple 3
# orange 2
# strawberry 2
# banana 1
# grape 1

Set

--A list that does not allow duplication is a set, and is made up of {element 1, element 2, element 3, ...}. --A set can be created from a list with set (list), eliminating duplication. --Add an element with set.add (element to add). --Remove an element with set.remove. --Delete all elements with set.clear (). --Investigate whether it is included in ʻin. --set1 | set2 returns a new set containing both. --set1 & set2 returns a new set with elements common to both. --set1 --set2 returns a new set that is included in set1 and not included in set2. --set1 ^ set2` returns a new set contained in either set1 or set2.

Comprehension notation

-- [Expression for variable in iterable object] Create a list

l = [num ** 2 for num in range(0, 21, 2)]
# [0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

dolls = [1,55,243,445,178]
rate = 106
yens = [d * rate for d in dolls]
# [106, 5830, 25758, 47170, 18868]

--Added ʻif`` [expression for variable in iterable object if conditional expression] `

address = ["Chiyoda ward, Tokyo", "Setagaya-ku, Tokyo", "Saitama, Saitama prefecture", "Yokohama-city kanagawa prefecture", "Adachi-ku, Tokyo"]
#Take out only Tokyo
tokyo = [a for a in address if a.startswith("Tokyo")]
# ['Chiyoda ward, Tokyo', 'Setagaya-ku, Tokyo', 'Adachi-ku, Tokyo']

people = [("Suzuki", "woman"), ("Yamada", "Man"), ("Takahashi", "woman"), ("Sato", "Man")]
#Take out the name of a man only
man = [p[0] for p in people if p[1] == "Man"]

--Dictionary comprehension {Key: Value for variable in Iterable object}

en = ["apple", "orange", "cherry", "banana"]
jp = ["Apple", "Orange", "Cherry", "banana"]
fruits = {k: v for k, v in zip(en, jp)}
# {'apple': 'Apple', 'orange': 'Orange', 'cherry': 'Cherry', 'banana': 'banana'}

--Set comprehension (expression for variable in iterable object} --There is no tuple inclusion notation.

function

def variable name(Argument 1,Argument 2, ...):
processing
return Return value

--Keyword argument Caller: f (p1 = 100, p2 = 200) --Default argument Function definition side: f (a = 1, b =" empty "): --The arguments passed to the function are not reflected to the caller even if they are changed in the function, but the changes are reflected when mutable arguments are passed to the function (only for destructive methods such as append).

def change(a):
    a.append(4)

a = [1, 2, 3]
change(a)
print(a)
# [1, 2, 3, 4]

Variable scope

--Variables created outside the global scope function Valid for the entire program --Variables created inside local scope functions --If there is the same name, the local scope takes precedence, so if you want to assign it to a global variable in the function, you need to define it with global global variable name.

Variadic argument

--When defining a variadic argument, prefix the variable name with *. def (* objects, sep =''): The argument after the variadic variable should be a keyword argument. (Because I don't know how far the variable length argument is) --Variadic arguments are received as tuples.

Receive keyword arguments as a dictionary

--If you add ** before the formal argument name, you can receive any number of arguments specified by the keyword as a dictionary.

def dic(**a):
    print(a)

dic(height=100, width=80, depth=50)
# {'height': 100, 'width': 80, 'depth': 50}

Functions are also objects

--hello (a) can be called asmy_func (a)by substituting my_func = hello.

Lambda expression

--lambda argument 1, argument 2, argument 3, ...: processing --Keyword arguments, default values, and variadic arguments can also be used.

smaller = lambda n1, n2: n2 if n1 > n2 else n1
print(smaller(9, 2)) # 2
print(smaller(1, 11))  # 1

ave = lambda *n : sum(n) / len(n)
print(ave(1, 5, 10, 50, 1000, 5000, 10000))  # 2295.1428571428573

The map () function that processes the elements of the list together

--map (function, list) Returns as a map object. (Iterable object) --list (map (function, list)) Returns as a list

def cm(inch): return inch*2.54

inches = map(cm, [1, 2, 5, 10, 100])

for i in inches:
    print(i)

print(list(map(cm, inches))) # [2.54, 5.08, 12.7, 25.4, 254.0]
#It is the same even if you write as follows
print(list(map(lambda inch: inch*2.54, [1, 2, 5, 10, 100]))) # [2.54, 5.08, 12.7, 25.4, 254.0]
#Comprehension notation
print([n*2.54 for n in [1, 2, 5, 10, 100]]) # [2.54, 5.08, 12.7, 25.4, 254.0]

The filter () function that filters the values in the list

--filter (function, list) Returns the element that is True in the function as an iterable object.

print(list(filter(lambda n: n % 2 == 0, range(0, 10)))) # [0, 2, 4, 6, 8]
#Comprehension notation
print([n for n in range(0, 10) if n % 2 == 0]) # [0, 2, 4, 6, 8]

Sort the list

--Sort the list itself with list.sort (). Sort the list itself in reverse order with list.sort (reverse = True). --Returns a list sorted by sorted list = sorted (list). -- Sorted list = sorted (list before sorting, key = str.upper) Sort as uppercase -- Sorted list = sorted (key = function) Sort by the result of the function

Sort the dictionary

names = {"taro": 2, "jiro": 4, "saburo": 1, "shiro": 3}
#Sort by value
print(sorted(names.items(), key=lambda n: n[1])) # [('saburo', 1), ('taro', 2), ('shiro', 3), ('jiro', 4)]
#Sort by value (reverse order)
print(sorted(names.items(), key=lambda n: n[1], reverse=True)) # [('jiro', 4), ('shiro', 3), ('taro', 2), ('saburo', 1)]

Generator function

--Return the value with yield instead of return --Fetch the following with the next () function. --If you retrieve it with for, no exception will occur.

def gen(str):
  for c in str.upper():
    yield c

yes = gen("yes")
print(next(yes)) # Y
print(next(yes)) # E
print(next(yes)) # S
print(next(yes)) #StopIteration exception

for h in gen("hello"):
  print(h, end="")

# HELLO

Generator type

--(Expression for variable in iterable object) ――At first glance, it looks like a tuple inclusion notation, but there is no tuple inclusion notation.

gen = (c for c in "hello".upper())

for g in gen:
    print(g, end="")

File reading

--Open and closed --f = open (filename, mode, encoding) --Default is mode = "r", encoding = "utf_8" - f.close()

with open("hello.txt") as f:
    print(f.read())

with open("hello.txt") as f:
    for i, line in enumerate(f):
        print(i, line, end="")

class

--Class names are customarily using upper camel case like MyClass --Constructor def __init __ (self, argument 1, argument 2, ...): --Put a value in an instance variable self. Instance variable name = value --Instance creation Variable = class name (argument, ...) Since the first argument self of the constructor automatically contains itself, specify the second and subsequent arguments. --The variable to which the value is assigned in the constructor is the instance variable, and the variable to which the value is assigned outside the method is the class variable. --The method definition is def method name (self, argument, ...): --Private methods prefix the method name with __. Add _ to methods that can be accessed from the outside but you do not want them to be accessed. --The getter and setter methods are customarily named as get_name`` set_name. --Set property with property name = propery ([setter method [, getter method]])`

class Customer:
    #Class variables
    bmi = 22

    #constructor
    def __init__(self, number, name, height=0):
        #Instance variables
        self.__number = number
        self.__name = name
        self.__height = height

    #Getter
    def get_name(self):
        return self.__name

    def get_number(self):
        return self.__number

    #Setter
    def set_number(self, number):
        self.__number = number

    def get_height(self):
        return self.__height

    #Calculate standard weight
    def std_weight(self):
        return Customer.bmi * (self.height / 100) ** 2

    #Property settings
    name = property(get_name)
    number = property(get_number, set_number)
    height = property(get_height)


if __name__ == "__main__":
    #Object creation
    taro = Customer(101, "Taro Saito", 180)
    #Change the value
    taro.number = 150
    print("No.{}of{}Is the standard weight{:.2f}It is kg.".format(
        taro.number, taro.name, taro.std_weight()))

# No.Taro Saito's standard weight of 150 is 71.It is 28 kg.

module

--The module name will be the file name without the extension .py. --When the file name is customer_m1.py, customer_m1 is the module name. --It is customary to recommend lowercase letters and underscores for module names and file names. --ʻIf name == The "main": `block is called when only the filename is specified.

Class inheritance

--Define with class subclass name (superclass name). --Call the superclass constructor with super () .__ init__ (argument)

Reference: [Basic Python Basic Series](https://www.amazon.co.jp/%E5%9F%BA%E7%A4%8EPython-%E5%9F%BA%E7%A4%8E%E3%82 % B7% E3% 83% AA% E3% 83% BC% E3% 82% BA-% E5% A4% A7% E6% B4% A5-% E7% 9C% 9F-ebook / dp / B01CZDTIKC)

Recommended Posts

Python basic grammar memo
Python Basic Grammar Memo (Part 1)
Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
Python basic grammar (miscellaneous) Memo (4)
Python3 basic grammar
Python basic grammar / algorithm
Python basic grammar (miscellaneous)
Python basic memo --Part 2
Basic Python command memo
Python basic grammar note (3)
Python basic memo --Part 1
Basic Python 3 grammar (some Python iterations)
python memo
Python memo
python memo
Basic Python grammar for beginners
I learned Python basic grammar
Python memo
Python (Python 3.7.7) installation and basic grammar
Python memo
Java and Python basic grammar comparison
Basic grammar of Python3 system (dictionary)
[Python] Memo dictionary
python beginner memo (9.2-10)
python grammar check
python beginner memo (9.1)
Flask basic memo
Basic Python writing
★ Memo ★ Python Iroha
[Python] EDA memo
Python grammar notes
Python3 metaclass memo
RF Python Basic_02
[Python] Basemap memo
Python beginner memo (2)
[Python] Numpy memo
[Basic grammar] Differences between Ruby / Python / PHP
[Python] I personally summarized the basic grammar.
Basic grammar of Python3 system (character string)
Basic grammar of Python3 series (list, tuple)
Basic grammar of Python3 system (included notation)
Memo # 4 for Python beginners to read "Detailed Python Grammar"
Python basic course (12 functions)
Python I'm also basic
Python class (Python learning memo ⑦)
Python Basic Course (7 Dictionary)
python openCV installation (memo)
Python module (Python learning memo ④)
Python basic course (2 Python installation)
[Go] Basic grammar ② Statement
Python ~ Grammar speed learning ~
Visualization memo by Python
Numpy basic calculation memo
[python] class basic methods
Python test package memo
Python Basic Course (11 exceptions)
[Python] Memo about functions
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Python3 cheat sheet (basic)
python regular expression memo