Get started with Python! ~ ② Grammar ~

Overview

This is a continuation of the environment construction section of Last time. This time we'll take a quick look at Python's grammar.

Features of Python

Python is called "a simple and easy-to-learn object-oriented language."

Python has long been used as a language for learning programming, Recently, it has been used as Google App Engine, and there are a lot of plugins for machine learning and data manipulation, so it is getting a lot of attention. (In Japan, it's not so noticeable, but it seems to be very popular overseas.)

Official site

This time, I would like to review the grammar using the widely used Python 2.7.x. (Use 2.7.12.)

Python grammar

Semicolon is deprecated

Semicolons at the end of sentences are deprecated in Python grammar. (It is defined in pep8, which will be explained in the next and subsequent articles.) The end of the sentence is represented by a line break.

comment

You can comment with \ #.

Handle Japanese characters

When I put Japanese characters in the code in Python, the following error is thrown.

  File "index.py", line 2
SyntaxError: Non-ASCII character '\xe3' in file index.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for
details

When dealing with Japanese in your code, you need to explicitly declare UTF-8.

# coding: UTF-8
#Above, you can use Japanese on the code
print 'hello' #Greet hello

variable

It can be declared without any prefix.

msg = 'hello from gemcook'

print msg

Data type

The data types that can be handled by Python are as follows.

--Numerical value

Numeric type

Arithmetic of decimals and integers

When you operate on decimals and integers, you get decimals.

Truncation integer

If you divide integers, you will get the result of the truncated division.

print 10 / 3  # 3

If you want to get a decimal, you can do as follows.

print 10 / 3.0  # 3.3333333333

String

When outputting a Japanese character string

Output with "u" (unicode) at the beginning of the character string. (Without u, correct results will not be obtained when searching for strings.)

print 'hello' + 'world'  # helloworld
print u'Is' *5 # IsIsIsIsIs

Escape character

Describe with \.

print 'It\'s a pen!'

When there are many line breaks and escapes

If you enclose it in'''and''', the range will be a line break and forced escape.

print '''
<html lang="ja">
    <body>
    </body>
</html>
'''

Instructions for strings

s = 'abcdefghi'

print len(s) # 9
print s.find('c') # 2(If it doesn't exist-Returns 1)

print s[2] # c
print s[2:5] # cde(Returns up to the 5th previous)
print s[2:] # cdefghi
print s[:5] # abcde
print s[2:-1] # cdefgh(Returns up to one character before the last character)

Conversion of numbers and letters

In other languages such as JS, numeric characters are automatically converted to numbers. ('1' is judged to be 1)

Since Python does not perform type conversion automatically, it is necessary to perform type conversion explicitly.

print 5 + '5' #An error will occur.

If you want to convert to an integer, do as follows.

print 5 + int('5') # 10

The same is true for character strings.

age = 20

print 'i am ' + str(age) + ' years old'

List type

In other languages it is called an array.

sales = [
    255,
    100,
    353
]

The contents of the list can be assigned to any type of element.

sales = [
    255,
    100,
    353,
    'apple'
]

For lists, you can use the same commands as strings.

sales = [
    255,
    100,
    353,
    'apple'
]

sales2 = [
	500,
	'orange'
]

print sales # [255, 100, 353, 'apple']

print sales * 2 # [255, 100, 353, 'apple', 255, 100, 353, 'apple']

print sales + sales2 # [255, 100, 353, 'apple', 500, 'orange']

print len(sales) # 4

print sales[3] # 'apple'

sales[2] = 250

print sales # [255, 100, 250, 'apple']

There is also an existence check command.

sales = [
    255,
    100,
    353,
    'apple'
]

print 100 in sales # True

There is also an instruction to make a list of serial numbers.

print range(3) # [0, 1, 2]

print range(1, 3) # [1, 2]

print range(3, 10, 2) # [3, 5, 7, 9]

List-type convenient instructions

list is a list type variable, and str is a character string type variable.

d = '2013/12/15'

print d.split('/') # [2013, 12, 15]
list = ['a', 'b', 'c']
print string.join(list)

Tuple type

Tuples are basically the same as lists. However, it has the characteristic that the elements cannot be changed.

You can use the same instructions as arrays.

tuple1 = (2, 5, 8)
tuple2 = (5, 5, 5)

print tuple1 + tuple2 # (2, 5, 8, 5, 5, 5)

print 2 in tuple2 # True

tuple1[2] = 10 #This will result in an error.

Mutual conversion of tuples and lists

It is possible to flexibly switch between tuples and lists by using the type conversion command, which is the same as the conversion of character strings and numbers.

array = [
    'dog',
    'cat',
    'tiger'
]

print array # ['dog', 'cat', 'tiger']

tupleChange = tuple(array)

listChange = list(tupleChange)

print tupleChange # ('dog', 'cat', 'tiger')
print listChange # ['dog', 'cat', 'tiger']

In addition to teaching that the data cannot be changed explicitly, the meaning of using tuples is It also leads to an improvement in processing speed.

When you can use tuples, try to use tuples.

Set (collective type)

The set is the same as the list and tuple, and the data is lined up, It has the feature of not allowing duplication.

You can calculate a set as it is called a set type.

How to make a set

a = set([1, 2, 3])
b = set([3, 4, 5])

Also, duplicate data will be ignored.

print set([1, 2, 3, 3, 3, 4, 5]) # set([1, 2, 3, 4, 5])

Set calculation

# coding: UTF-8

a = set([1, 2, 3, 6])
b = set([3, 4, 5, 7])

#Difference set(Things that are in a but not in b)
print b - a # set([1, 2, 6])

#Union(What is in a and b)
print a | b # set([1, 2, 3, 4, 5, 6, 7])

#Intersection(Duplicates in a and b)
print a & b # set([3])

#Only one of a and b
print a ^ b # set([1, 2, 4, 5, 6, 7])

Dictionary type

It is an object in JS. I think the Swift dictionary type is closer to the image.

mugiwara = {
    'luffy': 100000000,
    'zoro': 77000000
}

print mugiwara # {'zoro': 77000000, 'luffy': 100000000}

Note that the output elements are in no particular order.

Regarding assignment and acquisition, it is no different from a list.

mugiwara = {
    'luffy': 100000000,
    'zoro': 77000000
}


print mugiwara['luffy'] # 100000000

mugiwara['zoro'] = 120000000

print mugiwara # {'zoro': 120000000, 'luffy': 100000000}

You can also check the existence of the key with the in command.

mugiwara = {
    'luffy': 100000000,
    'zoro': 77000000
}

print 'luffy' in mugiwara # True

Dictionary type method

This is a method unique to dictionary types.

mugiwara = {
    'luffy': 100000000,
    'zoro': 77000000
}

#Get a list of keys.
print mugiwara.keys() # ['zoro', 'luffy']
#Get a list of values.
print mugiwara.values() # [77000000, 100000000]
# key-Get a list of values.
print mugiwara.items() # [('zoro', 77000000), ('luffy', 100000000)]

How to embed data in string type

It is also possible to embed other types in the string type without having to bother to perform type conversion.

a = 3000000000
b = 1.234
c = 'luffy'
d = {
    'choppa': 50,
    'usoppu': 300000000
}

#Incorporate integer values
print 'decimal: %010d' % a # 3000000000
#Incorporate decimal numbers
print 'float: %.1f' % b # 1.2
#Incorporate strings
print 'name: %s' % c # luffy
#Incorporate dictionary type
print 'berry: %(choppa)d' % d # 30000000
#Incorporate multiple values
print '%s: %d' % (c, a) # luffy: 300000000

Integer value

--Represented by% d (decimal) --By inserting a digit in front, you can display by the number of digits. --You can fill 0 by putting 0 before the number of digits.

Small number

--Represented by% f (float) --You can specify the number of digits after the decimal point by putting .X in front.

String

--Represented by% s (string)

Dictionary type

--% ([keyName]) Expressed as [character of type value].

Other

--It is also possible to assign multiple values. --In that case, enclose it in ().

Type check

The Python type check is as follows.

score = 70

print type(score) # <type, int>

You can also return with True / False.

score = 70

print isinstance(score, int) # True
print isinstance(score, str) # False

Conditional branch

Use if as usual. The conditional expression () is unnecessary. The processing after the condition is judged is indented and expressed.

# coding: UTF-8

score = 70

if 60 < score < 80:
    print 'ok' # 'ok'

Comparison operator

A comparison operator.

Logical operator

Logical operators are more intuitive. (With JS&&, ||, !)

if else statement

The if else statement is almost the same as other languages. Keep in mind that only elif is a bit characteristic.

score = 70

if int(score) > 60:
    print 'ok'
elif score > 40:
    print 'soso'
else:
    print 'ng'

Conditional branch in one line

In most languages, there is a way to draw a conditional branch on one line. (JS ternary operator, etc.)

Conditional branching is a bit tricky in one line of Python, Let's memorize the whole thing to write simple code.

score =70

print 'ok' if score > 60 else 'ng'

repetition

You can use the for statement. The syntax is as follows.

List type loop

sales = [13, 3523, 31, 238]
result = 0

for sale in sales:
    result += sale
else:
    print result

The following is a process that is executed only once when the repetition is completed.

range()

If you simply want to display a serial number of numbers, you can use range ().

for i in range(10):
    print i # 0 1 2 3 4 5 6 7 8 9 

continue and break

Use continue and break to skip or end the loop process.

for i in range(10):
	if i == 3:
		continue
	elif i == 5:
		break

Dictionary type loop

Dictionary-type loops use the iterXXXX () function.

# coding: UTF-8

mugiwara = {
    'luffy': 300,
    'zoro': 100,
    'sanji': 50
}

# key,Get both values.
for key, value in mugiwara.iteritems():
    print 'key: %s, value: %d' % (key, value)

#Get only the key.
for key in mugiwara.iterkeys():
    print key

#Get only value.
for value in mugiwara.itervalues():
    print value

while loop

There is also a while loop.

# coding: UTF-8

n = 0

while n < 10:
    print n
    n += 1
else:
    print 'finish'

function

It's an ordinary function. Register multiple processes at once.

Use the def keyword.

As a grammar rule (pep8), when defining a function, make two blank lines.

# coding: UTF-8


def sayHello():
    print 'hello'

sayHello()

argument

Of course, it is also possible to take an argument.

# coding: UTF-8


def sayHello(name, num):
    print 'hello, %s.' % name * num

sayHello('Luffy', 2) # hello, Luffy.hello, Luffy.

Argument initialization

Set the initial value with = on the registration side. (In pep8, there is no space between them.)

# coding: UTF-8


def sayHello(name, num=3):
    print 'hello, %s.' % name * num

sayHello('Luffy') # hello, Luffy.hello, Luffy.hello, Luffy.

Argument specification

It is also possible to explicitly specify the argument on the execution side.

# coding: UTF-8


def sayHello(name, num=3):
    print 'hello, %s.' % name * num

sayHello('Luffy') # hello, Luffy.hello, Luffy.hello, Luffy.
sayHello(num=2, name='Zoro') # hello, Zoro.hello, Zoro.

return statement

If you use the return command on the registration side, you can return the result of the function as a simple value.

# coding: UTF-8


def sayHello(name='no name'):
    return 'hello, %s' % name

print sayHello(name='Nami')

Definition of empty function

For the time being, you may want to define only the substance of the function and describe the processing of the contents later. In such a case, in other languages, I think that an empty function is defined as follows. (At the time of JS)

index.js



#Only the entity, the description of the contents is not yet a function
function sayHello() {
}

In Python, the function is not defined by {}, and the end of the sentence is expressed by indentation, so the pass instruction is prepared only for defining an empty function.


def sayHello2():
    pass
    
print sayHello2() # None

You can avoid the is not defined error by using the pass command.

Variable scope

In Python, variables within a function are valid only within the function.

# coding: UTF-8


name = 'Luffy'


def sayHello():
    name = 'Zoro'

#Not Zoro
print name # Luffy

map

It is an instruction to execute a function for each element of the list. The map command is executed as follows.

# coding: UTF-8

listItems = [2, 5, 8]


def double(x):
    return x * x

map(double, listItems) # [4, 25, 64]

lambda instruction

In Python, it's also possible to define an anonymous function that you only use once. I have defined a lambda that just doubles the target value with map.

# coding: UTF-8

listItems = [2, 5, 8]

result = map(lambda x: x * x, listItems)

print result # [4, 25, 64]

Specify any argument immediately after lambda. (map assigns the elements of the list to x one by one.) lambda is an image that only the value is returned in the return statement.

Object (class instance)

Creating a class

# coding: UTF-8


#As a cliché, take an object as an argument of class.
class User(object):
    # __init__Is the JS constructor
    #The first argument self is always required at initialization
    def __init__(self, name):
        self.name = name
    #When using the property method of the target class in the function
    #Take self as the first argument.

    def greet(self):
        print 'my name is %s' % self.name

bob = User('Bob')
tom = User('Tom')

print bob.name # 'Bob'
bob.greet() # my name is Bob
tom.greet() # my name is Tom

point

--The object of the argument of class is specified as a cliché when creating a class. --__init__ is an initialization method when a class is instantiated, and is prepared by Python. --Whenever you define a function, the first argument self (this for JS) is required. --Instantiation is not new.

Class inheritance

When inheriting a class, describe the class name of the inheritance source in the argument of class.

# coding: UTF-8


class User(object):
    def __init__(self, name):
        self.name = name

    def greet(self):
        print 'my name is %s' % self.name


class SuperUser(User):
    def shout(self):
        print '%s is SUPER!' % self.name

luffy = SuperUser('Luffy')
luffy.shout() # Luffy is SUPER!

module

It's packed with useful instructions that Python has prepared in advance.

Please refer to the Official Site for what kind of modules are available.

There are three main types of modules that Python prepares.

Built-in module

Modules originally prepared without using import statements such as len, split, join

Standard module

Modules prepared by Python but not usable without import

External module

Module to be used by importing after installing the module with pip

The following is an example of importing an external module.

# coding: UTF-8

import math
import random

#Import only date module in datetime module
from datetime import date

print math.ceil(5.2)  # 6.0

for i in range(5):
    print random.random()

print date.today() # 2016-10-08

point

For large modules such as datetime, it is possible to cut out only the necessary parts. In that case, use the from command.

Summary

Python has a unique syntax, but I think it's basically easy to remember and fairly readable. I think it's a pleasant language to write.

Next time, I'd like to explore Django, Python's most popular framework.

Recommended Posts

Get started with Python! ~ ② Grammar ~
Get started with Python! ~ ① Environment construction ~
Link to get started with python
How to get started with Python
Get started with Python in Blender
Django 1.11 started with Python3.6
1.1 Getting Started with Python
Get started with MicroPython
Get Started with TopCoder in Python (2020 Edition)
Get date with python
Get started with Mezzanine
Getting Started with Python
How Python beginners get started with Python with Progete
[Blender x Python] Let's get started with Blender Python !!
Python hand play (let's get started with AtCoder?)
Get started with Python on macOS Big Sur
A layman wants to get started with Python
[Cloud102] # 1 Get Started with Python (Part 1 Python First Steps)
Get country code with python
Get started with Django! ~ Tutorial ⑤ ~
Get Twitter timeline with python
Get started with influxDB + Grafana
Get Youtube data with python
Getting Started with Python Django (1)
Get started with Django! ~ Tutorial ④ ~
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Get started with Django! ~ Tutorial ⑥ ~
Get thread ID with python
Getting Started with Python Django (6)
Get stock price with Python
Get home directory with python
Get keyboard events with python
IfcOpenShell python bindings get started
Python3 | Getting Started with numpy
Getting Started with Python Django (5)
Get Alembic information with Python
Get started with Python in 30 minutes! Development environment construction & learn basic grammar
I tried to get started with blender python script_Part 01
I tried to get started with blender python script_Part 02
started python
Getting Started with Python responder v2
Get reviews with python googlemap api
Getting Started with Python Web Applications
Getting Started with Python for PHPer-Classes
Get the weather with Python requests
Get web screen capture with python
Get the weather with Python requests 2
How to get started with Scrapy
[Small story] Get timestamp with Python
How to get started with Django
Get Qiita trends with Python scraping
Get started with machine learning with SageMaker
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with Python for PHPer-Functions
Get weather information with Python & scraping
Let's get started with Python ~ Building an environment on Windows 10 ~
Minimum knowledge to get started with the Python logging module
Get additional data in LDAP with python
Step notes to get started with django