[Introduction to python] A high-speed introduction to Python for busy C ++ programmers

Overview

We have summarized the points for those who can use C ++ but do not understand python to acquire the minimum programming notation that allows quick machine learning. If you know this, you can use the minimum functions.

Benefits of Python

Since the library is extensive, you can easily write complicated code by writing in C ++. Web cooperation is relatively easy. There is a lot of information on the net.

How to use Python (example)

The following all libraries exist. Mastering the library means mastering python. ・ Machine learning ・ Web scraping ・ Excel operation ・ Data preprocessing ・ Visualize

Verification environment

python 3.8.2 Ubuntu 18.04

Environment

In the case of linux, python3 is included as standard, so there is no need to build an environment. If you want to run it on Anaconda, please refer to here. Anaconda is explained here [https://py-prog.com/whats-anaconda-and-its-merit-for-python-programming/) Anaconda makes it easy to create virtual environments. In python, which installs a lot of packages, you often want to change the environment, so if you want to use it seriously, Anaconda may be indispensable.

Recommended development environment

IDE ・ PyCharm ・ Spyder editor ・ Atom ・ VS code

List of differences between C ++ and Python

C++ Python
Variable type Yes None
Variable assignment copy Pointer
Function delimiter {}Braces :And indent
Arithmetic operator C++In addition to**Add exponentiation
Logical operator &&,ll,! and,or,not
Code break ; new line
Pointer Clear 不Clear
Comment out // #
Importing external libraries #include import
compile necessary Unnecessary
main function Yes None
Matrix calculation(standard) impossible Possible with numpy library

Difference in variable type

Since python is a dynamically typed language, the variable types that are commonplace in C ++ do not exist. Therefore, the variable is defined only by the variable name as it is. The type is determined by the assigned value.

a=1234 #Integer type
b=12.345 #Floating point type
c="hello world" #String type
d=[1,2,3,4] #List type

Pointer

There are no explicit pointers in python. Instead, the assignment to the variable is passing a reference rather than a copy, because the variable is both a value holder and a pointer. ** ** If you change the value of the assignment destination, the value of the variable of the assignment source will also change, so be careful of the difference in handling. (For list) Refer to the following https://qiita.com/maruman029/items/21ad04e326bb4fb6f71a

1 code range

In the case of C ++, 1 code is recognized no matter how many line breaks are made unless the delimiter ; is added, but in the case of python, the line break is a clear delimiter.

Indent

In python, the indent indicates the scope range. Therefore, if even one character is out of indentation, it will not be recognized as a code in the same range. It's a very indentable language, so coding can be harsh if you don't use the editor's indentation formatting feature. For example, the following code will result in an indentation error. Be aware that indentation often shifts and bugs occur in the loop.

a=1234 
b=12.345 
 c="hello world" #Not in the same range
d=[1,2,3,4] 

Global variables

Global variables in C ++ can be accessed as they are from functions, but in the case of python, they cannot be assigned unless they are declared locally as global variable name in the function.

a = 123


def Global():
    global a
    a = 456
    print("global variable:", a)


Global()

Difference in writing

Some main functions are omitted for readability.

Standard output

You don't need \ n because python is an automatic line break.

c.c


int a=123;
printf("%d\n",a);

python.py


a=123
print(a)

Importing external libraries

c++.cpp


#include "hogohoge.h"

python.py


import hogehoge 

Array

In python it is called a "list". The memory area of the python array is dynamically allocated, so you can add elements later. Use append () to add an element. If you substitute with ʻa [3] = 4` like C ++, an error will occur, so be careful.

c++.cpp


int a[4]={1,2,3,};
int b = a[2];
printf("%d\n", b);

a[3] = 4;
printf("%d\n", a);

python.py


a=[1,2,3]
b=a[2]
print(b)

a.append(4)
print(a)

Looking at the python code, I find ʻa.append (4) . This is a list method, a function used to manipulate lists. In python, variables and external libraries are treated as a kind of object, and you can access the methods provided in python with . method`. There are various other methods to insert in the middle, so here will be helpful.

Variable array

An array whose value cannot be changed later. In c ++, it is declared as const, but in pyton, it is called a tuple and is written differently from the list.

tupl.cpp


const int a[4] = {1, 2, 3, 4};
b = a[2];
printf("%d", b);

tupl.py


a = (1, 2, 3, 4)
b = a[2]#Get element
print(b)

Variable labeling

Python has a feature called a dictionary. It's like an array that can store data with a combination of keys and values. You can call it by specifying the key. Therefore, readability is improved. It may be easier to understand if you imagine it as something similar to a c ++ enum.

python.py


lang={"c":1,"python":2,"ruby":3}#Creating a dictionary
print(lang["python"])

lang["ruby"]=4#Swap elements
print(lang["ruby"])

lang["java"]=3 #Add element
print(lang)

if statement

Python does not have a delimiter such as {} like c ++. Therefore, by opening the next line of ʻif hogehoge:` by one tab, * the indent is changed to clearly indicate that it is an if statement process. If you bring pirnt to the left end, it will be indented the same as the if statement, so it will be the process executed at the outside of the if. Also shift the indent when nesting.

c++.cpp


int a = 7;
int b = 12;
if (a <= 10 && b <= 10)
{
    printf("Both a and b are 10 or less");
}
else if (a % 2 == 0)
{
    printf("a is even");
}
else
{
    printf("Does not meet the conditions")
}

python.py


a = 7
b = 12
if a <= 10 and b <= 10:
    print("Both a and b are 10 or less")
elif a % 2 == 0:
    print("a is even")
else:
    print("Does not meet the conditions")

for statement

In the case of c ++, if you want to retrieve the contents of the array one by one, you have to specify the number of elements in the array and loop. In the case of python, all the elements are fetched one by one just by throwing the list.

for.cpp


int ls[3] = {1, 2, 5};
for (int i = 0; i < sizeof ls / sizeof ls[0]; i++)
{
    printf("%d\n", ls[i]);
}

for (int i = 0; i < 3; i++)
{
    printf("%d\n", i);
}

for.py


ls = [1, 2, 5]
for i in ls:
    print(i)

for i in range(3):
    print(i)

1 2 5 0 1 2

while statement

while.cpp


int a = 0;
while(a < 3)
{
    printf("%d", a);
    a += 1;
}

while.py


a = 0
while a < 3:
    print(a)
    a += 1
    

0 1 2

function

When receiving a variadic argument, prefix the formal argument with *. When expanding the contents of a list or tuple to an argument and passing it, add * before the actual argument.

function.cpp


int Add(a, b)
{
    c = a + b;
    return c;
}

int Add3(int *c)
{
    int d = 0;
    d = c[0] + c[1] + c[2];
    return d;
}

int main()
{
    printf("%d\n", Add(1, 2));

    const int e[3] = {1, 2, 3};
    printf("%d\n", Add3(e));
}

function.py


def Add(a, b):
    c = a + b
    return c

def Add3(*c):  #Receive all arguments as variable super arguments
    d = c[0] + c[1] + c[2]
    return d


def main():
    print(Add(1, 2))
    print(Add3(1, 2, 3))
    e = (4, 5)
    print(Add(*e))  #It is also possible to expand the argument of a list or tuple and pass it
    return


if __name__ == "__main__":
    main()

class

Class definition

classdefine.cpp


class Hoge
{
public:
    int a;
    Hoge(int a)
    {
        this->a = a;
    }
    void add(int b)
    {
        printf("%d\n", a + b);
    }
    void mutipl(int b)
    {
        printf("%d\n", a * b);
    }
}

classdefine.py


class Hoge:
    def __init__(self, a):
        self.a = a
    
    def add(self, b):
        print(self.a + b)
    
    def mutipl(self, b):
        print(self.a * b)

In c ++, the constructor has the same name as the class, but in the "class" of python, the constructor is represented by def __init __ (self, a):, and the variables in the class are declared as self.a in the constructor. To do. The definition itself can be done from anywhere. Access the instance variable via "self" by passing "self" which is a reference of the class itself to the argument of the member function. Be sure to write self as an argument.

Manipulating the class

classcntrol.cpp


Hoge hoge(3);
hoge.add(4);
hoge.mutipl(4);

classcontrol.py


hoge = Hoge(3)
hoge.add(4)
hoge.mutipl(4)

Class inheritance

Inheritance.cpp


class Fuga : public Hoge
{
public:
    void subtract(int b)
    {
        printf("%d\n", a - b);
    }
    void divide(int b)
    {
        printf("%d\n", a / b);
    }
}

Fuga fuga(3);
fuga.add(4);
fuga.mutipl(4);
fuga.subtract(4);
fuga.divide(4);

Inheritance.py


class Fuga(Hoge): #Inherit Hoge
    def subtract(self, b):
        print(self.a - b)

    def divide(self, b):
        print(self.a/b)

fuga = Fuga(3)
fuga.add(4)
fuga.mutipl(4)
fuga.subtract(4)
fuga.divide(4)

Python's flagship library

Numpy (matrix operation library)

Matrix operations can be done very easily by using this. Required for machine learning. This person describes how to use it in detail, so please refer to it.

Matplotlib (graph drawing library)

Please refer to this article for how to write.

Supplement

Replace import module

In python, external libraries are treated as objects, but you can replace them with ʻas` because it's a hassle to write long names.

import numpy as np

Module installation

pip3 install module_name

Executing a Python script

python3 file_name

anaconda

python file_name

Standard library

File operations are fairly easy in python. https://qiita.com/hiroyuki_mrp/items/8bbd9ab6c16601e87a9c

Object specification import

https://note.nkmk.me/python-import-usage/

Finally

It's still just a small part of python, so it's a good idea to find out if there are any features you're interested in.

reference

Yukinaga Gazuma (Author) "First Deep Learning: Neural Network and Back Propagation Learned with Python"

Recommended Posts

[Introduction to python] A high-speed introduction to Python for busy C ++ programmers
An introduction to Python for C programmers
Introduction to Python For, While
Introduction to Protobuf-c (C language ⇔ Python)
An introduction to Python for non-engineers
Use a scripting language for a comfortable C ++ life-OpenCV-Port Python to C ++-
A super introduction to Python bit operations
[Introduction to Python] How to use the in operator in a for statement?
An introduction to Python for machine learning
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
An introduction to self-made Python web applications for a sluggish third-year web engineer
[Introduction to Python3 Day 23] Chapter 12 Become a Paisonista (12.1 to 12.6)
[Introduction to Udemy Python3 + Application] 43. for else statement
Introduction to Programming (Python) TA Tendency for beginners
Understand Python for Pepper development. -Introduction to Python Box-
Introduction to Python language
Introduction to OpenCV (python)-(2)
[Introduction to Python] How to get the index of data with a for statement
Try to make a Python module in C language
Introduction to Linear Algebra in Python: A = LU Decomposition
[Introduction to Python] How to write repetitive statements using for statements
[Python] How to call a c function from python (ctypes)
A quick introduction to pytest-mock
A road to intermediate Python
A super introduction to Linux
Introduction to serial communication [Python]
Python started by C programmers
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
An introduction to Python Programming
~ Tips for beginners to Python ③ ~
[Introduction to Udemy Python3 + Application] 42. for statement, break statement, and continue statement
Experiment to make a self-catering PDF for Kindle with Python
A simple way to avoid multiple for loops in Python
How to define multiple variables in a python for statement
How to make a Python package (written for an intern)
Introduction to Python for VBA users-Calling Python from Excel with xlwings-
[Python] Introduction to graph creation using coronavirus data [For beginners]
Prolog Object Orientation for Python Programmers
[Introduction to Udemy Python 3 + Application] 58. Lambda
[Introduction to Udemy Python 3 + Application] 31. Comments
How to write a Python class
Introduction to Pyblish, a framework for supporting pipeline construction Part 1 Overview
Solve ABC163 A ~ C with Python
To add a C module to MicroPython ...
Introduction to Python Numerical Library NumPy
An introduction to Mercurial for non-engineers
Practice! !! Introduction to Python (Type Hints)
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python] How to split a character string with the split function
Python learning memo for machine learning by Chainer Chapter 8 Introduction to Numpy
[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)
Python learning memo for machine learning by Chainer Chapter 10 Introduction to Cupy
[Introduction to Python] I compared the naming conventions of C # and Python.
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
From building a Python environment for inexperienced people to Hello world
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)