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.
--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. *** ***
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.
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.
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 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 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.
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]
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.
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}
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.
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
There is no do-while in Python. Only a while loop.
flag = True
while flag:
flag = False
#Exit in one loop
CC-BY: Akito D. Kawamura (@aDAVISk)
Recommended Posts