Introduction to Python language

Installation

There is an installer at https://www.python.org/downloads/, so use it to install. Currently (2015/11/15) the latest is Python 3.5.

If you are in a Windows environment, set environment variables. This area may be helpful. http://www.pythonweb.jp/install/setup/index1.html

About python

Python execution

$ python
Python 3.5.0 (default, Nov 15 2015, 16:08:58)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

How to write and execute a script

Write and execute for the time being

write...

test.py


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

def main():
    print('GOGO')

if __name__ == '__main__':
    main()

Run ...

test.py


$ python test.py
GOGO

Commentary line by line

test.py


#! /usr/bin/env python

This is a shebang. (Unix-like promises (read this if you are interested because it is not in the context of Python http://cpplover.blogspot.jp/2013/08/shebang.html))

test.py


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

Character code specification. (Without this, there are cases where you die when writing Japanese comments)

test.py


def main():

Function definition.

test.py


    print('GOGO')

Call the print function, which is one of the built-in functions. 'GOGO' is passing a string as an argument.

test.py


if __name__ == '__main__':

If you run the file as a script, the variable __name__ contains the string __main__. Therefore, when executed as a script, this condition will be True, and the blocks in it will be a good entry point. If imported by the import statement, this block will not be executed because __name__ contains the module name.

test.py


    main()

It is a function call.

Main types

type ()-Examine the type

You can check the type of object with the built-in function type ().

>>> type(1)
<class 'int'>
>>> type('1')
<class 'str'>
>>> type([1, 2, 3])
<class 'list'>
>>> type({'first': 1, 'second': 2})
<class 'dict'>

int --integer

It is an integer.

>>> 3 + 2  #addition
5
>>> 3 - 2  #subtraction
1
>>> 3 * 2  #multiplication
6
>>> 3 / 2  #division(Note that the behavior is different between Python 2 and Python 3.)
1.5
>>> 3 // 2  #division(Decimal truncation)
1
>>> 3 % 2  #Surplus
1
>>> 3 ** 2  #Exponentiation
9

str --string

>>> 'Hello World  '.strip()  #Whitespace before and after/Erase the newline character
'Hello World'
>>> 'Hello World  '.split()  #Split
['Hello', 'World']
>>> 'Hello World  '.lstrip('H')  #Erase the left H character
'ello World  '
>>> 'Hello' + 'World'  #Join
'HelloWorld'
>>> '{0} {1}'.format('Hello', 'World')  #String format
'Hello World'
>>> '{word1} {word2}'.format(word1='Hello', word2='World')  #String format part 2
'Hello World'

list --list

>>> [1, 2, 3]  #Create a list
[1, 2, 3]
>>> [1, 2, 3] + [4, 5, 6]  #Join
[1, 2, 3, 4, 5, 6]
>>> 1 in [1, 2, 3]  #Verify if included(Included case)                                                                                                                                                     
True
>>> 5 in [1, 2, 3]  #Verify if included(Case not included)                                                                                                                                                                       
False

add to

>>> nums = [1, 2, 3]
>>> nums
[1, 2, 3]
>>> nums.append(4)
>>> nums
[1, 2, 3, 4]

Removal

>>> nums = [1, 2, 3, 1]
>>> nums.remove(1)

dict --dictionary

dict is a data structure with name / value pairs.

As an example, let's define a dict that has a pair of fruit names and amounts.

>>> fruits = {
... 'apple': 100,
... 'orange': 50,
... }
>>> 

This fruits contains the following pair of values:

key value
'apple' 100
'orange' 50

If you want to get the value of 'apple', specify the key in [].

>>> fruits['apple']
100
>>> fruits['orange']
50

If you specify a key that does not exist, a KeyError exception will be thrown.

>>> fruits['grape']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'grape'
>>>

A little application

Let's calculate the amount of fruit using the previous fruits. 'apple' is 1 In this case:

>>> fruits['apple'] * 1
100

'apple' is 2 In this case:

>>> fruits['apple'] * 2
200

You can also specify variables in the 'apple' and 2 parts. If you define a variable called name and put'apple'in it to calculate, it will be as follows.

>>> name = 'apple'
>>> fruits[name] * 2
200

Let's put the number part in a variable called count.

>>> count = 2
>>> fruits[name] * count
200

You can calculate without changing the code of the part to be calculated by changing the value of name and count.

>>> name = 'orange'
>>> fruits[name] * count
100
>>> count = 20
>>> fruits[name] * count
1000

The code of the part to be calculated can be used without changing the code. Let's define this as a function to make it easier to reuse.

>>> fruits = {
... 'apple': 100,
... 'orange': 50,
... }
>>>
>>> def calc_fruit_amount(name, count):
...   return fruits[name] * count
...
>>>

The calc_fruit_amount () function calculates the total amount by specifying the name and number of fruits.

>>> calc_fruit_amount('apple', 2)
200
>>> calc_fruit_amount('apple', 3)
300
>>> calc_fruit_amount('orange', 3)
150
>>>

You can see that we are able to calculate the correct amount.

Control syntax

if

Executes the block inside if when the condition following if is True. The if companion is if / elif / else.

fruits.py


fruits = {
    'apple': 100,
    'orange': 50,
    }

def calc_fruit_amount(name, count):
    return fruits[name] * count


def decide_amount(name, count, threshold=1000):
     amount = calc_fruit_amount(name, count)
     if amount > threshold:
           print('high')
     elif amount == threshold:
           print('usually')
     else:  # < threshold
           print('cheap')

decide_amount () determines whether the total amount is greater than, equal to or less than the threshold and prints high / normal / cheap respectively.

for in

It loops by pulling elements one by one from a repeatable object such as a list. Exit when the element is finished.

fruits_list.py



fruits = {
    'apple': 100,
    'orange': 50,
    }

for name in ['apple', 'orange']:
    print('{} {}Circle'.format(name, fruits[name]))

Shows the name and amount of fruits. The following code behaves the same.

fruits_list2.py



fruits = {
    'apple': 100,
    'orange': 50,
    }

for name, amount in fruits.items():
    print('{} {}Circle'.format(name, amount))

try

An exception is thrown if the operation you are trying to perform is not permitted. For example, if you try to get a value with a name that does not exist from fruits, you will get an exception called KeyError.

>>> fruits['ham']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'ham'
>>>

If an exception occurs during script execution, the process will end abnormally there. By properly handling the exception that occurs, you can continue processing without abnormal termination.

In the following example, if calc_fruit_amount is passed a name that does not exist in fruits, an error message will be displayed.

fruits = {
    'apple': 100,
    'orange': 50,
    }

def calc_fruit_amount(name, count):
    try:
        return fruits[name] * count
    except:
        print('{}Does not exist'.format(name))

fizzbuzz

What is fizzbuzz

--The first player says the number "1". --The next player will say the next number of the previous player. ――However, if it is divisible by 3, say "Fizz", if it is divisible by 5, say "Buzz", and if it is divisible by both, say "Fizz Buzz" instead of the number.

It is a play. (Quote: https://ja.wikipedia.org/wiki/Fizz_Buzz)

This is a subject that is often used as a programming exercise.

Implementation example of fizzbuzz


for ii in range(1,101):
    if ii % 15 == 0:
       print('FizzBuzz')
    elif ii % 5 == 0:
       print('Buzz')
    elif ii % 3 == 0:
       print('Fizz')
    else:
       print(ii)

Standard module

You can use standard modules by using the import statement.

>>> import re

--re regular expression --sys Get and operate information about running Python, etc. --os Acquisition and operation of environment information such as the running OS

There are many others. http://docs.python.jp/3.5/library/index.html

Use a third party package

The Python standard library is very rich, but when writing a slightly complicated program or creating a system, it is a very difficult task to create using only the standard library. Some Python users publish their own packages on the Internet. They are called third-party packages. For example, Django, a web application framework, and pandas, which is often used for data analysis, are third-party packages.

Third-party packages can be installed using the pip command. Here we will install the HTTP library.

$ sudo pip install requests

Start Python and import requests.

>>> import requests
>>>

If you see the Python interactive shell prompt mark (>>>), you are successful. If it fails, an Import Error will be displayed.

Try making a GET request over HTTP to example.com.

>>> requests.get('http://example.com/')
<Response [200]>

If you no longer need requests, you can uninstall them with pip uninstall. (y / n) waits for input, so enter y and press the enter key.

Note) In many cases, sudo is required due to permission issues.

$ sudo pip uninstall requests
~abridgement~
Proceed (y/n)? y [ENTER]
  Successfully uninstalled requests-2.7.0
$

requests have been uninstalled.

If you register a third-party library with pypi, you can pip install with just the package name. Most of the commonly used libraries are registered on the pypi.

Virtual environment (venv)

If you proceed with multiple different projects, you will want to use the same package with different versions. For example, if you want to use requests-2.6 for Project A and requests-2.7 for Project X. In this case, if you install it as before, you can only use either version of requests. Python uses venv to solve such problems. venv can create independent Python environments individually. Put the version of the third party package you want to use in each created environment and use it. The handling of the environment differs between OS X / Linux and Windows.

For OS X / Linux

Create a venv environment.

$ pyvenv-3.5 env

Enter the venv environment. (Load the activate script with the source command) If successful, the prompt mark will change.

$ source env/bin/activate 
(env) $

Install requests as an example.

(env) $ pip install requests

You can import the installed requests.

>>> import requests
>>>

Run deactivate to get out of the environment. If successful, the prompt mark will be restored.

(env) $ deactivate
$ 

Requests cannot be imported because it came out of the virtual environment.

>>> import requests
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'requests'

For Windows

Create a venv environment.

c:\Temp>c:\Python35\python -m venv env

Enter the venv environment. (Execute activate.bat) If successful, the prompt mark will change.

c:\Temp>env\Scripts\activate
(env) c:\Temp>

Install requests as an example.

(env) c:\Temp>pip install requests

You can import the installed requests.

>>> import requests
>>>

Run deactivate to get out of the environment. If successful, the prompt mark will be restored.

(env) c:\Temp>deactivate
c:\Temp>

Requests cannot be imported because it came out of the virtual environment.

>>> import requests
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'requests'

What if the virtual environment is no longer needed?

Delete the entire directory when you no longer need the environment. There is no problem because the Python environment from which the virtual environment was created does not disappear. Of course, you can recreate the virtual environment.

OS X / Linux

$ rm -rf env

Windows

c:\Temp> rd /q /s env

Note) If the source code etc. is placed under env, it will also disappear. Please be careful.

Recommended Posts

Introduction to Python language
Introduction to Protobuf-c (C language ⇔ Python)
Introduction to OpenCV (python)-(2)
Introduction to Python Django (2) Win
Introduction to serial communication [Python]
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
An introduction to Python Programming
Introduction to Python For, While
[Chapter 5] Introduction to Python with 100 knocks of language processing
[Chapter 3] Introduction to Python with 100 knocks of language processing
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Chapter 4] Introduction to Python with 100 knocks of language processing
[Introduction to Udemy Python 3 + Application] 58. Lambda
[Introduction to Udemy Python 3 + Application] 31. Comments
Introduction to Python Numerical Library NumPy
Practice! !! Introduction to Python (Type Hints)
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]
[Introduction to Udemy Python 3 + Application] 57. Decorator
Introduction to Python Hands On Part 1
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python] Let's use pandas
Python to switch from another language
[Introduction to Python] Let's use pandas
[Introduction to Udemy Python 3 + Application] Summary
Introduction to image analysis opencv python
[Introduction to Python] Let's use pandas
An introduction to Python for non-engineers
Introduction to Python Django (2) Mac Edition
[AWS SAM] Introduction to Python version
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
[Python Tutorial] An Easy Introduction to Python
Introduction to Scrapy (1)
Introduction to Scrapy (3)
Updated to Python 2.7.9
Introduction to Supervisor
Introduction of Python
Introduction to Tkinter 1: Introduction
Introduction to PyQt
Introduction to Scrapy (2)
[Linux] Introduction to Linux
Introduction to Scrapy (4)
Introduction to discord.py (2)
Introduction to discord.py
"Backport" to python 2
Introduction of Python
[Introduction to Udemy Python3 + Application] 18. List methods
[Introduction to Udemy Python3 + Application] 63. Generator comprehension
[Introduction to Python] How to use class in Python?
[Introduction to Udemy Python3 + Application] 25. Dictionary-type method
[Introduction to Udemy Python3 + Application] 33. if statement
Introduction to Discrete Event Simulation Using Python # 1
[Introduction to Udemy Python3 + Application] 13. Character method
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
[Introduction to Udemy Python3 + Application] 55. In-function functions