~ Tips for Python beginners from Pythonista with love ① ~

Motivation

My name is @hanaken_Nirvana and I'm the CEO of Liaro and the window door at #HiveShibuya.

The company is developing a video recommendation app, but I basically write it in Python from API to recommendation engine (including Deep Learning * and NLP) (Scala in some places ...). In the startup area, there are many RoRs and I wanted the Python population to increase, but I thought, "Artificial intelligence! I'm often asked to teach Python because of the boom, so I'll write a memo for that time, focusing on Python-like grammar for Python beginners.

** Well, I'm not a Python contributor, I'm just a Python user, so if you make a mistake, I'd like you to point out ʕº̫͡ºʔ **

Interactive format

Normally you need to write code in a file and execute it, but in Python you can use it as an interpreter by writing "python" in the console.

python:Python3.5.0


% python
Python 3.5.0 (default, Feb  8 2016, 19:02:32) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello world!!')
Hello world!!
>>> 

Indent

Python is indentable. If the indent is misaligned, an error will occur. The difference between tabs and spaces is also useless (2 series interprets 1 tab = 8 spaces, but 3 series is not). It is recommended to indent with 4 spaces. The following is an example of adding an even number from 0 to 9.

python:Python3.5.0


>>> i = 0
>>> for j in range(10):
...     if j % 2 == 0:
...     i += j
  File "<stdin>", line 3
    i += j
    ^
IndentationError: expected an indented block
>>> 
>>> for j in range(10):
...     if j % 2 == 0:
...         i += j
... 
>>> i
20

The darkness of 2.x and 3.x

The darkness of backward compatibility

In the first place, Python nowadays is roughly divided into 2.x series and 3.x series. Apart from that, the 3.x series is not always the latest and is being developed at the same time. The reason why there are two lines is that Python has a culture that values backward compatibility. Therefore, even if the version is upgraded, the functions you were using will not be lost. "(After upgrading) it broke even though I didn't do anything." Nothing like that happens. It's good for mental health for those who don't evolve. However, the specifications become bloated and complicated because of backward compatibility (character code, class, print statement, exception handling, etc ...). Ruby and the like are throwing away old specifications, but under the influence of that, let's throw away old bad specifications at once! The development of the 3.x series started with that feeling. So it works on 2.x, but it doesn't work on 3.x! What often (and vice versa)

Then which one should be used

Well, I'm throwing away the bad old specifications, so if you want to use it from now on, I recommend the 3.x series. However, there are some libraries that can only be used with 2.x, and there are times when you have to use 2.x.

Character code

The first stumbling block is the character code.

File encoding

It is delicate whether this should be included in the character code chapter, but at the beginning of the .py file, write the following to specify the encoding.

File encoding is utf-In case of 8


# coding:utf-8

And if you write it incidentally, you can encode / decode the character string as follows *.

python:Python3.5.0


>>> hoge = "Ah"
>>> hoge.encode("utf-8")
b'\xe3\x81\x82'
>>> hoge = b'\xe3\x81\x82'
>>> hoge.decode("utf-8")
'Ah'

The above is 3.x series, but the encoding / decode writing method is the same for 2.x series.

2. About x system

From the point of view of 2.x, there are str type and unicode type even in the type that handles characters. Normally, if you enclose it in single quotes or double quotes (either'python'or "python" is OK in Python), it becomes str type, and if you prefix it with u, it becomes unicode type.

The difference between the two is first look at the output below.

python:Python2.7.9


>>> "Ah" #str
'\xe3\x81\x82'
>>> u"Ah" #unicode
u'\u3042'

The str type is a byte string encoded by each character code (utf8, Shift_JIS, etc ...), and the unicode type is the code point. * This was only str type in early Python and could only handle ascii characters (white eyes)

Therefore, I made another type called unicode type so that it can handle multi-byte characters (with backward compatibility in mind). This is a typical bad old spec. .. ..

By the way, encode / decode is like this.

python:Python3.5.0


>>> hoge = "Ah"
>>> hoge.encode("utf-8")
b'\xe3\x81\x82'
>>> hoge = b'\xe3\x81\x82'
>>> hoge.decode("utf-8")
'Ah'

3. About x system

Next, let's talk about 3.x. In 3.x series, str type without prefix is unicode type in 2.x. If you want to handle it as a byte string, add b to the prefix. It looks like the following.

python:Python3.5.0


>>> "Ah" #str
'Ah'
>>> "Ah".encode("utf-8") #byte
b'\xe3\x81\x82'

If you think about this, you can see that the 3.x series is easier to handle.

operator

The following is a brief summary of the operators and operations that can be used. ** The version has been revised in response to @ nobolis's suggestions **

Algebraic operator

python:Python2.7.9


>>> 1 + 1 #Addition
2
>>> 1 - 1 #Subtraction
0
>>> 1 * 2 #Multiply
2
>>> 1 / 2 #division
0
>>> 1 / 2.0 #division
0.5
>>> 3 // 2.0 #division(Truncate)
1.0
>>> 5 % 4 #remainder
1
>>> 2 ** 2 #Exponentiation
4

There are two points to note. First, only in the case of 2 systems, the result will be int type by division between int types. So if you need a decimal point, you need to divide at least one by float. And the other is that // is not a quotient but a truncated division ** (although it depends on how you define the remainder mathematically in the first place). For the sake of clarity, the behavior when the calculation result is a negative value is shown below.

python:Python3.5.0


>>> -3 // 2.0
-2.0
>>>

In this case, it is -3 / 2.0 = -1.5, but if you truncate it, it will be rounded to -2.0, which is less than -1.5 instead of ** -1.0. ** ** This is mathematically justified, with q as the quotient and r as the remainder, the division ʻA / b = q remainder r` Can be expressed as. In other words

b * q + r = a (a,b>0)
b > r >= 0

is. If you try to extend this to a negative value as it is, you need to round it toward minus infinity instead of rounding it toward zero. ** If you want to round to zero, write in ʻint (a / b) `. ** **

Bit operator

python:Python3.5.0


>>> ~10 #Bit inversion
-11
>>> 10 & 14 #Logical AND
10
>>> 10 | 14 #Logical sum
14
>>> 10 ^ 14 #Exclusive OR
4
>>> 10 << 1 #Left shift operation
20
>>> 10 >> 1 #Right shift operation
5
Boolean operator

python:Python3.5.0


>>> True and False
False
>>> True or False
True
>>> not True
False

The following was added with comments from @shiracamus.

4.1. Truth value judgment

The following values are considered false: ・ None ・ False -Zero in numeric type. For example, 0, 0.0, 0j. -Empty sequence. For example,'', (), []. -Sky mapping. For example {}. · When an instance of a user-defined class, if that class defines bool () or len () methods, those methods return an integer 0 or a bool value False. All other values are considered true — so many types of objects are always true.

4.2. Boolean operation

Boolean operation If x is a value that is determined to be true If x is a value that is determined to be false
x and y Value of y Value of x
x or y Value of x Value of y
not x False True

python:Python3.5.2


>>> 'abc' and 'xyz'
'xyz'
>>> 'abc' and ''
''
>>> 'abc' or 'xyz'
'abc'
>>> 'abc' or ''
'abc'
>>> '' or 'xyz'
'xyz'
>>> not 'abc'
False
>>> not ''
True
>>> for i in range(1, 20):
...  print(i%15==0 and 'FizzBuzz' or i%3==0  and 'Fizz' or i%5==0 and 'Buzz' or i)
...
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Comparison operator

python:Python3.5.0


>>> 1 == 2
False
>>> 1 != 2
True
>>> 1 < 2
True
>>> 1 > 2
False
>>> 1 <= 2
True
>>> 1 >= 2
False
>>> 1 is 2
False
>>> 1 is not 2
True
>>> 1 in [1,2,3,4]
True
>>> 1 not in [1,2,3,4]
False

The difference between == and ʻis is that == returns True, but ʻis returns False if the values are the same. In other words, == requires the same value, and ʻis` must be the same (same instance). An example is shown below.

python:Python3.5.0


>>> a = [1,2,3,4] #List type object
>>> b = [1,2,3,4]
>>> a == b
True
>>> a is b
False
>>> a = b
>>> a is b
True

print statement

The print statement is basically written as follows

python:Python2.7.9


>>> print("Hello world!!")
Hello world!!
>>> print "Hello world!!"
Hello world!!

The latter writing method cannot be used in 3.x series. In chronological order, the former was written later, and the syntax, which is different from the others only in the print function, seems strange, so I prepared it (probably).

** @ shimizukawa pointed out in the comments and added the following. Thank you! ** ** I completely forgot because I didn't write like print ("Hello", "world !!") in 2 series, but the print statements in parentheses are 2.x series and 3.x. It's a little different depending on the system.

python:Python3.5.0


>>> print("Hello", "world!!")
Hello world!!
>>>

python:Python2.7.9


>>> print("Hello", "world!!")
('Hello', 'world!!')
>>>

In the case of 3 series, it is the same as print" Hello "," world !! " in 2 series as described above. However, it is displayed as a tuple in the 2nd system. So, if you want to operate the 2nd system in the same way as the 3rd system, do as follows.

python:Python2.7.9


>>> from __future__ import print_function
>>> print("Hello", "world!!")
Hello world!!
>>> 

By the way, this __future__ is a module that can operate the functions of 3 series in 2 series. By importing unicode_literals for the character code, you can handle the character string in unicode like 3 series.

python:Python2.7.9


>>> from __future__ import unicode_literals
>>> "Ah"
u'\u3042'
>>> 

String type join

It's a little derailed, but you can also use + when combining string types, but since there is a notation called .format, I will write that as well.

python:Python3.5.0


>>> hoge = "Hoge"
>>> fuga = "Fuga"
>>> print("hoge:"+hoge+", fuga:"+fuga)
hoge:Hoge, fuga:Fuga
>>> print("hoge:{}, fuga:{}".format(hoge, fuga))
hoge:Hoge, fuga:Fuga
>>> 

for statement

This is an example of adding a number from 1 to 9 to the list type and printing the for statement and the elements of the list.

python:Python3.5.0


>>> a  = []
>>> for i in range(1,10):
...     a.append(i)
... 
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in a:
...     print(i)
... 
1
2
3
4
5
6
7
8
9
>>> 

if-else statement

Basically, it looks like the following.

python:Python3.5.0


>>> a  = []
>>> for i in range(1,10):
...     if i % 2 == 0:
...         a.append(i)
...     else:
...         a.append(i*i)
... 
>>> a
[1, 2, 9, 4, 25, 6, 49, 8, 81]

By the way, you can also write as follows as a ternary operator.

python:Python3.5.0


>>> "Yes" if 1 < 2 else "No"
'Yes'
>>> "Yes" if 1 > 2 else "No"
'No'

Exception handling

The basic exception handling is as follows (3 series).

python:Python3.5.0


>>> try:
...     "A".hoge()
... except Exception as e:
...     print(e)
... finally:
...     print("Be sure to execute")
... 
'str' object has no attribute 'hoge'
Be sure to execute

Exception catches all exceptions, so write a specific exception class when you actually use it.

python:Python3.5.0


>>> try:
...     "A".hoge()
... except AttributeError as e:
...     print(e)
... finally:
...     print("Be sure to execute")
... 
'str' object has no attribute 'hoge'
Be sure to execute

Else that appears in various places

By the way, else can be used for other than if statements. The following is an example of a for statement and exception handling.

python:Python3.5.0


>>> for i in range(1,5):
...     print(i)
... else:
...     print("Last run")
... 
1
2
3
4
Last run
>>> for i in range(1,5):
...     print(i)
...     if i == 4:
...         break
... else:
...     print("Not executed when break")
... 
1
2
3
4
>>>

python:Python3.5.0


>>> try:
...     "A".lower()
... except AttributeError as e:
...     print(e)
... else:
...     print("Execute when not catching exception")
... finally:
...     print("Be sure to execute")
... 
'a'
Execute when not catching exception
Be sure to execute
>>>
>>> try:
...     "A".hoge()
... except AttributeError as e:
...     print(e)
... else:
...     print("Not executed when catching an exception")
... finally:
...     print("Be sure to execute")
... 
'str' object has no attribute 'hoge'
Be sure to execute

tired

I'm tired, so I'll continue after ②. .. ..

Click here for Tips② Click here for Tips ③

Recommended Posts

~ Tips for Python beginners from Pythonista with love ① ~
~ Tips for Python beginners from Pythonista with love ② ~
~ Tips for beginners to Python ③ ~
Tips for calling Python from C
INSERT into MySQL with Python [For beginners]
Tips for dealing with binaries in Python
Tips for using python + caffe with TSUBAME
[Python] Read images with OpenCV (for beginners)
WebApi creation with Python (CRUD creation) For beginners
[For beginners] Try web scraping with Python
Causal reasoning and causal search with Python (for beginners)
Wrap C with Cython for use from Python
python textbook for beginners
Wrap C ++ with Cython for use from Python
OpenCV for Python beginners
[Introduction for beginners] Working with MySQL in Python
Tips for speeding up python code correctly with numba
Learning flow for Python beginners
[Tips] Handle Athena with Python
Python3 environment construction (for beginners)
Python #function 2 for super beginners
Basic Python grammar for beginners
100 Pandas knocks for Python beginners
Python for super beginners Python #functions 1
[Python + Selenium] Tips for scraping
Python #list for super beginners
With skype, notify with skype from python!
Tips for Python beginners to use Scikit-image examples for themselves 4 Use GUI
Tips for developing apps with Azure Cosmos DB in Python
[For beginners] Summary of standard input in Python (with explanation)
[For beginners] Script within 10 lines (4. Connection from python to sqlite3)
Introduction to Python for VBA users-Calling Python from Excel with xlwings-
Tips for Python beginners to use the Scikit-image example for themselves
Get data from analytics API with Google API Client for python
Solve AtCoder Problems Boot camp for Beginners (Medium 100) with python
Call C from Python with DragonFFI
Python Exercise for Beginners # 2 [for Statement / While Statement]
Using Rstan from Python with PypeR
Install Python from source with Ansible
Create folders from '01' to '12' with python
Tips for running Go with docker
Python for super beginners Python # dictionary type 1 for super beginners
Getting Started with Julia for Pythonista
Python #index for super beginners, slices
Run Aprili from Python with Orange
<For beginners> python library <For machine learning>
[TouchDesigner] Tips for for statements using python
Python #len function for super beginners
Call python from nim with Nimpy
Beginners use Python for web scraping (1)
Run unittests in Python (for beginners)
Beginners use Python for web scraping (4) ―― 1
Read fbx from python with cinema4d
Python #Hello World for super beginners
Python for super beginners Python # dictionary type 2 for super beginners
Getting Started with Python for PHPer-Functions
[Pandas] I tried to analyze sales data with Python [For beginners]
Get html from element with Python selenium
[Note] Get data from PostgreSQL with Python
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
WEB scraping with Python (for personal notes)