Python Master RTA for the time being

Python text for those who already know older languages ​​such as C/C ++ and Fortran. For those who have their own things to do, but can't understand what they want to do because they can't read it even if they search for "Python what they want to do", we aim to learn the minimum at the fastest speed.

Minimum line to aim for

--Environment construction (RTA version) --Variables, classes and methods --Console output --Lists and dictionaries --numpy (useful module) -[Bonus] Other syntax

The goal is not to master these, but to get a sense of knowing somehow. Therefore, compatible knowledge of C/C ++ and Fortran is omitted.

*** It may differ slightly depending on the output content and environment. I haven't written any non-essential output instructions. The choice of information is based on your personal opinion. Others may encourage you to learn something else. Don't worry about the details. *** ***

Environment construction (RTA version)

Anaconda (link) is convenient, but if you just want to follow the contents of this article, you can do it with Paiza (link) in the online environment. If you open it with a browser, the environment construction is complete.

Variables, classes and methods

variable

You can use alphabets (large and small), numbers (excluding the first letter) and underscores _ for variable names. There is no variable type declaration. You can assign a string immediately after assigning a number to a variable spam.

spam = 10     #Substitute 10 for spam
spam = "Egg"  #To spam"Egg"Substitute

The semicolon ; at the end of the line is unnecessary. After #, it becomes a comment. Python may use keywords such as spam``egg`` ham related to comedian Monty Python as memes (see here and here for details).

Since all variables are classes, each has a member function (method). However, I will omit a difficult explanation here. Only how to use, the method that is often used is introduced in the string type format method.

Method

Methods are called in the form variable.method (). This variable is called the receiver for the method. The format method is similar to the C/C ++ printf% notation, replacing the {number} part of the string with the content of the argument. The number starts from 0 and corresponds to the first argument, second variable ... of format in order.

fname = "./myFile_{0}.txt"
fname.format(1)                     # "./myFile_1.txt"Returns
fname.format("memo")                # "./myFile_memo.txt"Returns
fname.format("note_{0}").format(10) # "./myFile_note_10.txt"Returns

The last example is a method (method chain) that uses what is returned by a method as the receiver of the next method. First, fname.format ("note_ {0} ") returns "./myFile_note_{0}.txt ", and then "./myFile_note_{0}.txt ".format (10) It will be executed and "./myFile_note_10.txt" will be returned.

Some methods are destructive, which change the contents of the receiver, while others are non-destructive. You can remember it while using it.

You can also build your own methods. Defined with def method name (formal argument):.

def myMethod(ivar):
   return ivar        #Returns a value
# End of myMethod
spam = myMethod("Egg")

In C/C ++, it is enclosed in {}, in Fortran it is enclosed in BEGIN END, but in Python it is managed by colon: and indentation. A range with more indents than a line with a colon : is a block. Before you get used to it, it's a good idea to put a comment (# after the same level of indentation as def) to indicate the end of the method.

Console output

Console output is done with the print method. The argument is a string or variable. You can list multiple arguments with ,, but the variables themselves can be confusing. Let's use the format method well.

spam = 10
egg = 22
print("spam and egg: {0}, {1}".format(spam, egg))
print("Contents of spam and egg: ", end="") #Do not break at the end
print(spam, egg)
# =>
#spam and egg: 10, 22
#Contents of spam and egg: 10 22

By adding the end =" " option, you can remove the line break that automatically enters at the end.

Lists and dictionaries

list

Lists are matrices in C/C ++ and Fortran. Operate with an integer index. The list is enclosed in [].

ar = [10,11,12,13,14]
ar[0]    # => 10
ar[-1]   # => 14
ar[1:3]  # => [11,12]
ar[-2:]  # => [13:14]
ar[-2:5] # => [13:14]
ar[::3]  # => [10,13]

The list can be manipulated with [first index: last index: amount to increase index]. Unlike C/C ++ and Fortran, the index feels like it is at the beginning of each element. See the figure below. You can use both the index that increases from the beginning with 0 start and the index that starts with -1 at the end of the element and decreases by -1 to the front. If omitted, it will be adjusted to the highest number range. So, if you want to specify the elements of the values ​​13 and 14 in the figure, you can use the expressions 3: 5 and -2: 5 3: -2: so that they are sandwiched between indexes. ..

You can also have multiple lists.

ar = [[1,2,3],[4,5,6]]
ar[0]    # => [1,2,3]
ar[0][1] #=> 2

It is processed from the outside in order from the one closest to the variable. It's the same feeling as a C/C ++ array.

dictionary

A dictionary is like an array that uses arbitrary values ​​(keys, numbers or strings) instead of indexes. You cannot specify the range. The dictionary is defined by {key 1: value 1, key 2: value 2}. Any value is fine.

dct = {"spam":300,10:"ten","egg":[0,1,2]}
dct["spam"] # => 300
dct[10]     # => "ten"
dct["egg"]  # => [0,1,2]

Manipulating lists and dictionaries

Extract values ​​in order

You can retrieve the values ​​one by one with for. Define the block (indent with :) as you did for the method. This can be done on everything iterable, not just lists and dictionaries.

ar = [10,11,12,13,14]
for ee in ar:
   print("{0}, ".format(ee), end="") #Do not break at the end
# => 10, 11, 12, 13, 14,

dct = {"spam":300,10:"ten","egg":[0,1,2]}
for kk in dct.keys():
   print("{0}, ".format(kk), end="") #Do not break at the end
# => spam, 10, egg
for vv in dct.values():
   print("{0}, ".format(vv), end="") #Do not break at the end
# => 300, ten, [0,1,2]
for kk,vv in dct.items():
   print("{0}:{1}, ".format(kk,vv), end="") #Do not break at the end
# => spam:300, 10:ten, egg:[0,1,2]

Dictionaries can retrieve only keys, only values, both keys and values. Of course, if you use this for syntax, you can do normal for loops, and you can also use multiple for loops.

to add

You can add a value to the end of the list with the append method. You can also join another list to the end with the extend method.

ar = [0,1,2]
ar.append(3)     # => [0,1,2,3]
ar.extend([4,5]) # => [0,1,2,3,4,5]

The dictionary can add keys and values ​​(overwrite values ​​if the keys already exist) with the update method.

dct = {"spam":300,"egg":100}
dct.update({"spam":200,"ham":200}) # => {"spam":300,"egg":100,"ham":200}

numpy (useful module)

When dealing with matrices etc., you will want to add values ​​in list + list. The module (library in C/C ++) that makes it possible is numpy. Use the import syntax to import modules.

import numpy as np
ar = np.array([0,1,2])
ar + np.array([0,2,4]) # => [0,3,6]
ar + 1                 # => [1,2,3]
ar * 3                 # => [0,6,9]

The as np after the import numpy is a paraphrase declaration that the imported one will be treated as np thereafter. This simplifies even long module names. numpy is customarily abbreviated as np. np.array () will convert the list of arguments to an array for numpy called numpy.ndarray. With this array type, you can add arrays (have the same structure) and perform four arithmetic operations with integers. You can also perform matrix operations such as transpose. The index operation is the same as the standard list.

In addition, numpy also contains trigonometric functions. Call them all with the np. method (). If you want to know more, it is faster to google with "numpy function name" than to read official numpy documentation. There are also random numbers.

[Bonus] Other syntax

with syntax

This is especially common when manipulating files. It defines variables (more accurately, instances) that are valid only within a specific range (block) of the code, and deletes them when the block ends (closes the file if it is a file operation).

with open("myData.txt", "r") as iFile:
   iFile.readline() #Read one line

while syntax

There is no do-while in Python. Only a while loop.

flag = True
while flag:
   flag = False
#Exit in one loop

So far, we've summarized what you need to know before looking up what you want to do with Python if you already know old languages ​​like C/C ++ and Fortran.

CC-BY: Akito D. Kawamura (@aDAVISk)

Recommended Posts

Python Master RTA for the time being
Use logger with Python for the time being
See python for the first time
MongoDB for the first time in Python
Let's touch Google's Vision API from Python for the time being
Try using FireBase Cloud Firestore in Python for the time being
The fastest way for beginners to master Python
For the time being, import them into jupyter
Make a histogram for the time being (matplotlib)
Run yolov4 "for the time being" on windows
I played with Floydhub for the time being
I tried python programming for the first time.
Try using LINE Notify for the time being
virtualenv For the time being, this is all!
[Python] [Machine learning] Beginners without any knowledge try machine learning for the time being
Kaggle for the first time (kaggle ①)
What I got into Python for the first time
I tried Python on Mac for the first time.
Molecular dynamics simulation to try for the time being
I tried python on heroku for the first time
Kaguru for the first time
I will install Arch Linux for the time being.
Next to Excel, for the time being, jupyter notebook
Until you can install blender and run it with python for the time being
I want to move selenium for the time being [for mac]
I tried running PIFuHD on Windows for the time being
[Understand in the shortest time] Python basics for data analysis
[Introduction to Reinforcement Learning] Reinforcement learning to try moving for the time being
For the time being, try using the docomo chat dialogue API
I want to create a Dockerfile for the time being.
[For self-learning] Go2 for the first time
What is the python underscore (_) for?
Master the type with Python [Python 3.9 compatible]
Start Django for the first time
Command for the current directory Python
Master the weakref module in Python
Differences C # engineers felt when learning python for the first time
Java programmer tried to touch Go language (for the time being)
Challenge image classification by TensorFlow2 + Keras 1-Move for the time being-
For the time being, I want to convert files with ffmpeg !!
[Blender x Python] Let's master the material !!
I tried tensorflow for the first time
Launch the Discord Python bot for 24 hours.
Call the python debugger at any time
Pandas of the beginner, by the beginner, for the beginner [Python]
Let's try Linux for the first time
Challenge image classification with TensorFlow2 + Keras CNN 1 ~ Move for the time being ~
A useful note when using Python for the first time in a while
[Python] Master the reading of csv files. List of main options for pandas.read_csv.
Since I'm free, the front-end engineer tried Python (v3.7.5) for the first time.
2016-10-30 else for Python3> for:
python [for myself]
Prepare the development environment for Python on AWS Cloud9 (pip install & time change)
I tried using scrapy for the first time
First time python
[Python] I tried substituting the function name for the function name
Created a Python wrapper for the Qiita API
vprof --I tried using the profiler for Python
[Python] matplotlib: Format the diagram for your dissertation
Wagtail is the best CMS for Python! (Perhaps)
Upgrade the Azure Machine Learning SDK for Python