Learning notes from the beginning of Python 1

I will write a memo when learning Python (version 3) from the beginning.

The knowledge of Python itself starts from the state of 0. (2013/11/10 ~) The content was reviewed and the description was corrected. (2017/01/02)

The site you are looking at when learning

Coding style PEP8 (recommended coding style)


Python has PEP 8 as a style guide that most projects follow. It recommends a very readable and eye-friendly coding style. All Python developers should read it at some point. Here are the most important points:

Use 4 spaces for indentation and no tabs.

The four whitespaces are exactly halfway between the small indentation (which can be deeply nested) and the large indentation (easy to read). Tabs are confusing and should not be used.

Wrap lines so that the width of the source code does not exceed 79 characters.

This will make it easier for users with smaller displays to read, and will also allow source code files to be lined up on larger displays.

Use blank lines to separate large code blocks within a function, class, or function.

If possible, write the comment on the same line as the code.

Use docstring.

Put spaces before and after the operator and after the comma, not just inside the parentheses: a = f (1, 2) + g (3, 4).

Give the class or function a consistent name. By convention, CamelCase is used for class names and lower_case_with_underscores is used for function and method names. Always use self as the name of the first argument of the method (see Class First Look for classes and methods).

If you plan to use your code around the world, don't use quirky encodings. In any case, Python's default UTF-8 or plain ASCII works best.

Similarly, non-ASCII characters should not be used in identifiers if even the slightest amount of other language-speaking people may read or maintain the code.


Install using pyenv. You can use git.


Introduction for Debian

$ git clone https://github.com/yyuu/pyenv.git ~/.pyenv
$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
$ exec $SHELL
$ pyenv install 3.4.3
$ pyenv global 3.4.3
$ pyenv rehash

If you are using zsh, the file to write the environment variable settings should be ~ / .zshrc.

On the pyenv site, it is described to write in ~ / .zshenv, but with the emacs setting There was a case where pyenv could not be used well because of interference, so I used ~ / .zshrc temporarily.

pyenv rehash is used when deploying Python packages using pip If there is a command that passes through Path, it needs to be executed.

When I run pyenv rehash, the path to the command goes.

If you get the following error:

Ignoring ensurepip failure: pip ? requires SSL/TLS

Solved by installing the required packages in Debian by referring to the following.

Common build problems https://github.com/yyuu/pyenv/wiki/Common-build-problems


sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev

If you need to upgrade pip itself when using pip, follow the instructions Do the following:


$ pip install --upgrade pip
$ pyenv rehash

Executing a Python script

$ python sample.py

When you execute a Python script, it will be processed in order from the top written in the script.

Unlike other programming languages, you don't need a function like main.

In the case of Unix / Linux environment, if the created Python script sample.py has execute permission and Shebang is written in the first line of the script, the script is . It can be executed directly in the form of /sample.py. On Windows, there is no Shebang function, so this execution method is impossible, so execute it as python sample.py.

In recent Windows Python 3 series, it seems that the same description as Shebang can be done by another mechanism.

$ ./sample.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

print("Hello Python!") # => Hello Python

Shebang and magic comments

Shebang (Shebang, Shebang)

In a Unix / Linux environment, write Shebang on the first line of the script and execute the script itself to execute the program (for example, Python) described in Shebang and add the script to that program. The contents can be passed and operated.

In other words, if you execute the above sample.py like $ ./sample.py, Shebang will execute the python program, and the contents of sample.py will be passed to the python program and processed. To.

Magic comment

Magic comments can be written on the first or second line of the script.

At the beginning of the line that describes the magic comment, write the comment character corresponding to the script language.

Magic comment

# -*- coding: utf-8 -*-

In the magic comment, write the character encoding in that file (sample.py in this case).

When a script is executed, the python interpreter (a program that interprets and operates the Python language description) expects the characters in the script to be in the specified character encoding.

In other words, if there is a description of ʻutf-8 in the magic comment, the Python interpreter expects the encoding of the characters in the script file to be ʻutf-8 and processes it while interpreting the script file. I will go.

Python3 expects ʻutf-8as the default encoding, but you can also include any encoding such asSJISin the magic comment. In that case, it is necessary to set the characters described in the script file toSJIS`. If this correspondence is not correct, an error will occur when executing the script.

If it matches the following regular expression, it will be treated as a magic comment. Actually, you need a comment character (# in Python) at the beginning of the line. coding[=:]\s*([-\w.]+)

This regular expression should be understood in the following sense.

  1. There is the word coding
  2. Immediately after coding, = or :
  3. There may or may not be any number of spaces immediately after 2.
  4. One or more letters consisting of alphabetic alphabets, numbers or underscores (ie [a-zA-Z_0-9]) or -

Magic comment

# -*- coding: utf-8 -*-

The above is established as a magic comment.

Interpretation of encoding by editor

When the editor opens a file, I don't know the encoding of the file Since the encoding information is misaligned, it cannot be displayed or written correctly.

In the editor (vi or emacs), check the first line of the file, and if it does not apply, look at the second line and if there is a specific description, handle the character encoding in the file with the expectation that it is as described. There is a function.

There is something in common with the above magic comment and this particular description (which seems to be called an encoding pragma), so If you write the magic comment correctly, the editor will open the file in that encoding.

I will quote Mr. Matsumoto's article.

Yukihiro Matsumoto talks a lot about "The Ruby Programming Language" The 7th "M17N" may open http://www.oreilly.co.jp/community/blog/2009/05/m17n-open-the-door-into.html

Since encoding can be used, when using multibyte characters, encoding pragma, we call it a magic comment, but if you do not specify "#--coding: utf-8--", an error will occur. May appear. This "-*-" symbol is a symbol that Emacs uses when checking what the character code of a file is, so it is a two bird with one stone that Emacs can understand it and Ruby can understand it. (Omitted) So Emacs understands the coding like this, but vim doesn't understand it and writes "fileencoding = utf-8". Therefore, Ruby recognizes that it is an encoding name if there is a sequence of "[: or =] " after "coding" in AdHoc. If it is the shortest, it will be recognized even if you write something completely different, such as "coding" or "transcoding". I'm not sure if it's stupid or smart, ― It means Ruby that can be measured well. I'm doing my best. However, this is not the origin of Ruby, and Python does the same.

# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8

――The first line is a simple pattern of magic comment format --The second line is the Emacs encoding pragma format. --The third line is the encoding pragma format of vi (vim?)

Recommended Posts

Learning notes from the beginning of Python 1
Learning notes from the beginning of Python 2
Study from the beginning of Python Hour1: Hello World
Study from the beginning of Python Hour8: Using packages
First Python 3 ~ The beginning of repetition ~
Existence from the viewpoint of Python
python learning notes
Omit BOM from the beginning of the string
The beginning of cif2cell
the zen of Python
Get the contents of git diff from python
The story of low learning costs for Python
Finding the beginning of Abenomics from NT magnification 2
Finding the beginning of Abenomics from NT magnification 1
The wall of changing the Django service from Python 2.7 to Python 3
O'Reilly python3 Primer Learning Notes
Basics of Machine Learning (Notes)
[Python] Get the text of the law from the e-GOV Law API
About the ease of Python
Mathematical understanding of principal component analysis from the beginning
Get the return code of the Python script from bat
Python points from the perspective of a C programmer
Deep Learning from scratch The theory and implementation of deep learning learned with Python Chapter 3
Python data analysis learning notes
Othello ~ From the tic-tac-toe of "Implementation Deep Learning" (4) [End]
Summary of the basic flow of machine learning with Python
[Maya Python] Crush the contents of the script 2 ~ list Notes
Beginning with Python machine learning
About the features of Python
The Power of Pandas: Python
DJango Note: From the beginning (simplification and splitting of URLConf)
The result of Java engineers learning machine learning in Python www
Different from the import type of python. from A import B meaning
What beginners learned from the basics of variables in python
The story of Python and the story of NaN
[Python] The stumbling block of import
Python: Application of supervised learning (regression)
Notes on using MeCab from Python
DJango Memo: From the beginning (preparation)
pyenv-change the python version of virtualenv
Change the Python version of Homebrew
[Python] Understanding the potential_field_planning of Python Robotics
Review of the basics of Python (FizzBuzz)
Use the Flickr API from Python
Notes on accessing dashDB from python
About the basics list of Python basics
Learn the basics of Python ① Beginners
How to know the number of GPUs from python ~ Notes on using multiprocessing with pytorch ~
[Python] Try to graph from the image of Ring Fit [OCR]
I want to output the beginning of the next month with Python
[Python] Get the update date of a news article from HTML
python learning
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
Evaluate the accuracy of the learning model by cross-validation from scikit learn
Important unit seen from the Python lecture materials of Kyoto University
List of disaster dispatches from the Sapporo City Fire Department [Python]
Carefully derive the interquartile range of the standard normal distribution from the beginning
Chapter 1 Introduction to Python Cut out only the good points of deep learning made from scratch
[Examples of improving Python] Learning Python with Codecademy
DJango Memo: From the beginning (model settings)
[Understanding in 3 minutes] The beginning of Linux