Python basics ③

This is the end of the basics.

Functions, built-in functions

You can define and use a group of programs as a function.

Also, the functions that are preset in python itself It is called a built-in function.

Think of it as the program number of a variable

Method

A method is a method that performs processing on a specific value.

Method


value.Method name()

I will write it in the form of.

There is also an instance variable that retrieves value elements and so on. Instance variables have no arguments because they are variables, not functions.

Instance variables


value.Instance variable name

Write in the format.

Taking append as an example, it is as follows.

append


# append()Is a method to use if you want to add only one new element to the list.

alphabet = ["a","b","c","d","e"]
alphabet.append("f")
print(alphabet) 
# ["a", "b", "c", "d", "e", "f"]Is output

String method (upper / count)

A method for enlarging and counting characters.

city = "Tokyo"
print(city.upper()) #"TOKYO" is output
print(city.count("o")) #"2" is output.

String method (format)

The format () method is a method that can be used for string types, and you can embed variables in strings. Mainly used when inserting variable values into templates. Specify the place where you want to embed the value with {}. The argument does not have to be a string type.

print("I{}birth,{}Growing up".format("Tokyo", "Saitama"))
#"I was born in Tokyo and raised in Saitama" is output


# {}The value to be inserted in can also specify the order of insertion. You can also insert the same value repeatedly.

print("I{1}birth,{0}Growing up{1}Resident".format("Tokyo", "Saitama"))
#"I was born in Saitama, raised in Tokyo, and lives in Saitama" is output

List type method (index)

The list type has an index number.

The index number is the number when the contents of the list are counted in order from 0.

As a method to find out which index number the desired object is in

index()

there is. Also, the list type was dealt with earlier.

count()

Can be used.


alphabet = ["a", "b", "c", "d", "d"]
print(alphabet.index("a")) 
#Since it is in the 0th index number, "0" is output.
print(alphabet.count("d")) 
# "d"Is in the 3rd and 4th index numbers, so "2" is output.

List type methods (sort, reverse, sorted)

sort()

This will sort the list in ascending order.

reverse()

You can use this to reverse the order of the elements in the list.

As a caveat

If you just want to see the sorted list, use the built-in function sorted () which returns the sorted array.

soted()

Here is a usage example.

# sort()Usage example

list = [1, 10, 2, 20]
list.sort()
print(list) # [1, 2, 10, 20]It will be displayed.

# reverse()Usage example

list = ["Ah", "I", "U", "e", "O"]
list.reverse()
print(list) # ["O", "e", "U", "I", "Ah"]It will be displayed.

function

Create as follows.

"Def function name(): 」

The function simplifies the program because it can organize the necessary processing. It has the advantage of making it easier to understand the overall movement.

The same process can be reused in multiple places, leading to a reduction in the amount of description and an improvement in readability.

def sing():
    print ("sing!")

#The scope of processing is specified by indentation.
#Also, the call to the defined function is "function name".()".

sing() 
 #Output result sing!

argument

If you set an argument when defining a function, You will be able to use that value within the function.

def function name(argument):
def introduce(n):
    print(n + "is")

introduce("Yamada")
#"It's Yamada" is output
#At this time, if you specify the argument as a variable, you can change the output result without changing the argument directly.

def introduce(n):
    print(n + "is")

name = "Yamada"
introduce(name) #"It's Yamada" is output

name = "Tanaka"
introduce(name) #"It's Tanaka" is output
#Variables and arguments defined in the function can be used only in the function.

Multiple arguments

You can specify multiple arguments separated by commas.

def introduce(first, family):
    print("Last name is" + family + "And the name is" + first + "is.")

introduce("taro", "Yamada") 
#"The surname is Yamada and the name is taro." Is output.

Initial value of argument

If you set the initial (default) value to the argument If the argument is blank, the initial value will be set automatically. Argument = Set in the form of initial value.

def introduce(family="Yamada", first="Taro"):
    print("Last name is" + family + "And the name is" + first + "is.")


introduce("Suzuki")
#"The surname is Suzuki and the name is Taro." Is output.
#In this case, only first is set as the initial value and family is"Suzuki"It has been overwritten with.

#If you want to pass only the first argument, introduce(first="Jiro")You just have to specify.

#In addition, it is necessary to always set the initial value in the argument after the argument for which the initial value is set.
#Therefore, it is possible to set the initial value only for the last argument as follows.

def introduce(family, first="Taro"):
    print("Last name is" + family + "And the name is"+ first + "is.")
#However, if you do not set the initial value only for the previous argument and set it for the latter argument as shown below, an error will occur.

def introduce(family="Suzuki", first):
    print("Last name is" + family + "And the name is" + first + "is.")
#The error output in this case is non-default argument follows default argument.

return

Variables and arguments defined in a function cannot be used outside the function. However, you can use return to pass the return value to the caller of the function.

error


def introduce(family = "Yamada", first = "Taro"):
    comment = "Last name is" + family + "And the name is" + first + "is."

print(introduce("Suzuki")) 
#None is output
#There is no return value here, so the output result is None(None)Will be.

def introduce(family = "Yamada", first = "Taro"):
    comment = "Last name is" + family + "And the name is" + first + "is."
    return comment #Pass the return value to the function

print(introduce("Suzuki")) 
#"The surname is Suzuki and the name is Taro." Is output.

In this way, you can use return to pass the return value to the caller of the function.

Function imports (packages, subpackages, modules)

Most recently from a module as a function import It is a format to take out the unit from the package.

There are scipy packages and time modules.

image.png

When using a package or module in a program, the following import process is required.

import scipy #Import scipy package
import time #Import the time module

#When using the methods in the imported package
#Generally, the package name.Subpackage name.Write it as the method name. Remember that it works like a method.

import scipy.linalg

scipy.linalg.norm([1,1])

>Output result
1.4142135623730951

In the example below, the current time is output using a method called time in the time module.

import time

now_time = time.time() #Current time now_Substitute for time

print(now_time) #The current time is output

Also, from package name.subpackage name import method name You can also load the method directly. In this case, when calling the method The package name and subpackage name can be omitted.

from scipy.linalg import norm

norm([1, 1]) #Package name / module name can be omitted

#Output result
1.4142135623730951

from module name You can omit the module name by writing the import method name.

from time import time #Import the time method of the time module

now_time = time() #Module name can be omitted

print(now_time) #The current time is output

By using the import package name as the name You can call the package with any name.


from time import time as t 
#Import the time method of the time module and handle it with the name t

now_time = t()

print(now_time) #The current time is output

class

object

Python is an object-oriented language. An object is a collection of data and procedures (methods) for that data.

A procedure is a description of the processing that an object has. The image of the object is a blueprint. Instantiate (materialize) an object Processing is performed when a message (instruction) is sent.

A method of reusing a program by capturing the processing target as an object and modularizing it. It's called object-oriented.

class

It's like a blueprint for the structure of an object. If you say in large format.

Class: Type Instance: Large format Object: Large format set (class + instance)

image.png

Class contents

Classes include initializers, methods, member variables, and more.

__init__()


class MyProduct: #Define class
    def __init__(self, name, price): #Define initializer
        self.name = name #Store arguments in members
        self.price = price
        self.stock = 0
        self.sales = 0
#Create an instance from the defined class

#Call MyProduct and create product1
product1 = MyProduct("cake", 500)

print(product1.name) #Output name of product1
cake

print(product1.price) #Output price of product1
500

Class rules (self, initializer)

 class MyProduct: #Define class
    def __init__(self,argument): #Define initializer

self refers to the instance body (MyProduct in this case) You can use self to get other member variables of an instance You can call the method.

Example


class MyProduct: #Define class
    def __init__(self, name, price): #Define initializer
        self.name = name #Store arguments in members
        self.price = price
        self.stock = 0 # stock,sales is initialized with 0
        self.sales = 0
#Next, create an instance from the defined class.
#In instantiation, the class(MyProduct)To assign to a variable.

#Call MyProduct and create product1
product1 = MyProduct("cake", 500)

print(product1.name) #Output name of product1
>Output result
cake

print(product1.price) #Output price of product1
>Output result
500

print(product1.stock)
>Output result
0

Class (method)

There are three types of methods that can be defined in a class.

class MyClass:  #name of the class
    def __init__(self,Argument 2,Argument 3, …):  #Initializer
        self.Variable name=initial value#Initialize the variable

    def normal_method(self,Argument 2,Argument 3, …):  #Normal method
        self.name = name
        return name

    @classmethod  #Class method
    #Class methods have a rule that the first argument is cls.
    def class_method(cls,Argument 2,Argument 3, …):
        cls.name = cname
        return cname

    @staticmethod  #Static method
    #Static methods are unconventional and the arguments themselves are not required.
    def static_method(Argument 1,Argument 2,Argument 3, …):
Argument 1.name = sname
        return sname

Class methods have a rule that the first argument is cls Static methods are unconventional and the arguments themselves are not required.

Also, the method call is written as object.method name.

Object.Method name

Class (inheritance, override, super)


#Parent class
class MyProduct:
    def __init__(self, name, price, stock):
        self.name = name
        self.price = price
        self.stock = stock
        self.sales = 0

    def buy_up(self, n): #Purchasing method
        self.stock += n

    def get_name(self): #Product name method
        return self.name

    def sell(self, n): #Sales method
        self.stock -= n
        self.sales += n * self.price

    def summary(self): #Overview method
        message = "called summary().\n name: " + self.name + \
        "\n price: " + str(self.price) + \
        "\n price: " + str(self.get_price_with_tax()) + \
        "\n sales: " + str(self.sales)
        print(message)
#The inheritance procedure is as follows.


#Define MyProductSalesTax by inheriting MyProduct class
class MyProductSalesTax(MyProduct):

    #Set the consumption tax rate as the fourth argument of the initializer
    def __init__(self, name, price, stock, tax_rate):
        #Invoke the initializer of the parent class
        super().__init__(name, price, stock)
        self.tax_rate = tax_rate

    #MyProduct get_Overwrite name
    def get_name(self):
        return self.name + "(tax included)"

    #get_price_with_Add tax
    def get_price_with_tax(self):
        return int(self.price * (1 + self.tax_rate))
# super()You can call the methods of the parent class with. When this program is executed, it will be as follows.

product_3 = MyProductSalesTax("phone", 30000, 100, 0.1)
print(product_3.get_name())
print(product_3.get_price_with_tax())
#Call the summary method of MyProduct
product_3.summary()

phone(tax included) #Output as expected
33000      #Output as expected
called summary() 
name: phone
price: 30000
stock: 100
sales: 0

Character string format specification

The format of the character string output to the console can be formatted using the "format method". Here are some of the formats used to arrange the numerical parts contained in the character string.

: d int type data displayed in decimal notation : .0f Float type Data display only integer part : .2f Float type data up to 2 decimal places Use these formats as shown in the code below.

#Define an approximation of pi
pi = 3.141592
 #Define pi as 3
pi2 = 3
print("Pi is{:d}".format(pi2)) # 「Pi is3」と出力される
print("Pi is{:.0f}".format(pi)) # 「Pi is3」と出力される
print("Pi is{:.2f}".format(pi)) # 「Pi is3.14 "is output.

Recommended Posts

Python basics ⑤
Python basics
Python basics ④
Python basics ③
Python basics
Python basics
Python basics
Python basics ③
Python basics ②
Python basics ②
Python basics: list
Python basics memorandum
#Python basics (#matplotlib)
Python CGI basics
Python basics: dictionary
Basics of Python ①
Basics of python ①
#Python basics (scope)
#Python basics (#Numpy 2/2)
#Python basics (functions)
Python array basics
Python profiling basics
Python #Numpy basics
Python basics: functions
#Python basics (class)
Python basics summary
Python basics ② for statement
Python: Unsupervised Learning: Basics
Python
Basics of Python scraping basics
#Python DeepLearning Basics (Mathematics 1/4)
Python basics: Socket, Dnspython
# 4 [python] Basics of functions
Basics of python: Output
python: Basics of using scikit-learn ①
Python basics: conditions and iterations
Paiza Python Primer 4: List Basics
Basics of Python × GIS (Part 1)
kafka python
Basics of Python x GIS (Part 3)
python + lottery 6
Built-in python
Paiza Python Primer 5: Basics of Dictionaries
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
SNS Python basics made with Flask
Python service
Linux basics
python function ①
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
NumPy basics
Python Memorandum 2
python memo