This is a continuation of the environment construction section of Last time. This time we'll take a quick look at Python's grammar.
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.)
This time, I would like to review the grammar using the widely used Python 2.7.x. (Use 2.7.12.)
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.
You can comment with \ #.
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
It can be declared without any prefix.
msg = 'hello from gemcook'
print msg
The data types that can be handled by Python are as follows.
--Numerical value
When you operate on decimals and integers, you get decimals.
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
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
Describe with \.
print 'It\'s a pen!'
If you enclose it in'''and''', the range will be a line break and forced escape.
print '''
<html lang="ja">
<body>
</body>
</html>
'''
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)
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'
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 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)
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.
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.
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.
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])
# 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])
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
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)]
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
--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.
--Represented by% f (float) --You can specify the number of digits after the decimal point by putting .X in front.
--Represented by% s (string)
--% ([keyName]) Expressed as [character of type value].
--It is also possible to assign multiple values. --In that case, enclose it in ().
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
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'
A comparison operator.
=
Logical operators are more intuitive. (With JS&&, ||, !)
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'
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'
You can use the for statement. The syntax is as follows.
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
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 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
There is also a while loop.
# coding: UTF-8
n = 0
while n < 10:
print n
n += 1
else:
print 'finish'
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()
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.
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.
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.
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')
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.
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]
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.
# 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
--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.
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!
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.
Modules originally prepared without using import statements such as len, split, join
Modules prepared by Python but not usable without import
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
For large modules such as datetime, it is possible to cut out only the necessary parts. In that case, use the from command.
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