First Python ~ Coding 2 ~

Target person

This is a continuation of Previous article. In this article, we will move the topic to Python lists, conditional branching, and loop processing based on the previous article [graph_plot.py](https://qiita.com/kuroitu/items/8542b88d486d1dbf92a5#draw graph). .. If you don't mind skipping everything, go to [Draw a discontinuous function](#Draw a discontinuous function).

table of contents

--[Python list](#python list) -[Conditional branch and loop processing](# Conditional branch and loop processing) -[if statement](#if statement) -

[for statement and while statement](#for statement and while statement) -[for statement](#for statement) -[while statement](#while statement) -[Draw a discontinuous function](#Draw a discontinuous function) - [Troublesome? ](#Troublesome)

Python list

In the previous article (https://qiita.com/kuroitu/items/8542b88d486d1dbf92a5#How to use numpy), I mentioned that there are no arrays in Python. Instead, Python comes standard with a data structure called a List. This time I will touch on it a little.

What is a list?

Let's start with a brief description of the list.

list_sample.py

list_sample.py


x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x)

x.append(10)
print(x)

#print(x + 3)
#TypeError occurs

print(x + [3])
print(x * 3)

x = np.array(x)
print(x)
x = list(x)
print(x)

Lists are similar in concept to arrays and can be used as follows:

list_sample.py


x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x)

Did you notice that the output result is the same as the x defined in this x, [numpy_calc.py](https://qiita.com/kuroitu/items/8542b88d486d1dbf92a5#numpy usage)? In other words, you can see that lists and arrays have similar data structures. The biggest difference is that the ** data size is variable **.

list_sample.py


x.append(10)
print(x)

10 has been added. This ʻappend` method is a function [^ 1] that the list type data structure has, and is for adding an element. Of course, trying to do the same with a numpy array will only give an error. In numpy, to resize the array once defined, you need to copy it somewhere (internally). By allocating a large amount of memory in the point list in advance, you can save the time required to allocate memory when adding elements. ** In short, each has its advantages / disadvantages. ** ** There are other functions in the list that delete elements. Also, the list does not have the ability to broadcast numpy arrays.

list_sample.py


#print(x + 3)
#TypeError occurs

However, you can do the following:

list_sample.py


print(x + [3])
print(x * 3)

If it is an addition between lists, an element will be added. Multiplication of a list and a natural number is a list that repeats the list itself by the number of numbers. [^ 2] ** Other operations cannot be typeError ** In addition, numpy arrays and lists can be converted to each other.

list_sample.py


x = np.array(x)
print(x)
x = list(x)
print(x)

This concludes the introduction of the list knowledge required in this article. In summary

--A list is like an array with variable data size --Numpy and list can be converted to each other

This article is OK if you only know.

Conditional branching and loop processing

Conditional branching is the process of ** "○○ if certain conditions are met, XX otherwise" **. (This process is similar to human decision making, isn't it?) Loop processing is a process that ** "repeats the same process until a certain condition is met" **. (This is a machine-like process)

Let's actually do how to write the code concretely.

ʻIf` statement

Speaking of conditional branching in Python, only the ʻif statement is [^ 3]. People who have done C language etc. may wonder, "Well, isn't there a switch? " There is no such thing as a switch` statement in Python. You have to write it one by one. ~~ It's troublesome. ~~ For the first time person, it may be lucky to remember less. For the time being, let's use this conditional branch.

if_sample.py

if_sample.py


x = 5
if x > 0:
    #Conditional expression x>If 0 is true, the process here
    print("x is greater than 0.")
else:
    #Conditional expression x>If 0 is false, the process here
    #That is, x<=If it is 0, it is the process here
    if x == 0:
        #Conditional expression x==If 0 is true, the process here
        # <note>
        # ==Is a conditional expression that both sides of the expression are equal
        #On the contrary, the operation of whether both sides of the expression are not equal is!=is
        print("x is 0.")
    else:
        #Conditional expression x==If 0 is false, the process here
        #That is, x!=If it is 0, it is the process here
        print("x is less than 0.")

if x > 0:
    print("x is greater than 0.")
elif x == 0:
    print("x is 0.")
else:
    print("x is less than 0.")

These two ʻif statements have exactly the same behavior. The upper one is written using only ʻif else, and the lower one is written using the grammar ʻif elif else. As you can see, you can write a ʻif statement inside a ʻif` statement (called ** nesting **). Of course, you can nest more, but it will be difficult to read, so try to ** minimize nesting as much as possible **. In other words, the code below is easier to read.

Grammar summary

if_grammer_summary.py


if (Conditional expression 1):
    # (Conditional expression 1)Is true(True)Then execute the process described here
#-----from here-----
elif (Conditional expression 2):
    # (Conditional expression 1)Is fake(False)so(Conditional expression 2)Is true(True)Then execute the process described here
elif (Conditional expression 3):
...
else:
    #All conditional expressions are false(False)Then execute the process described here
#-----So far-----
#All are optional. In other words, only the first if is OK.

for and while statements

Next is loop processing. There are two types of Python loop processing, for and while. There are two reasons, because sometimes I want to use them properly, but I like it because I can convert the for statement to the while statement and the while statement to the for statement so that they perform equivalent processing. I'd like to say ... but I personally recommend using the ** basically for statement. ** ** The reason will be later ...

for statement

First of all, from the for statement.

for_sample.py

for_sample.py


for i in range(10):
    print(i)
print("----------")

for i in range(1, 10):
    print(i, end=" ")
    if i > 5:
        print("\n{} > 5".format(i))
        print("Break out of the loop")
        break
else:
    print("This statement is not printed.")

By the way, the upper for statement is output vertically from 0 to 9. At the bottom, up to 6 should be output side by side, and should end with "6> 5" and "Exit loop". (Since it's incidental, I'm using some functions that I haven't introduced. If you're curious, let's google.)

The for statement is easier to understand if you look at the grammar.

for_grammer_summary.py


for (Variable name) in (Arrays, lists, etc.):
    (Write the process you want to repeat here)
else:
    (Write here the processing when the loop ends normally and the processing you want to do when the loop is never executed)

The range function returns something like a list up to a specified number [^ 5]. The break statement is for forcibly breaking the loop. In the for statement, the numerical values specified by ** (array, list, etc.) ** are sequentially assigned to ** (variable name) ** and processed.

In the first loop of for_sample.py

--0 is assigned to the variable ʻi --Theprint function prints 0 --1 is assigned to the variable ʻi --The print function prints 1

  • ...

The process proceeds like this.

The second loop was written to introduce the for else statement. You can use ʻelse for looping, which is rare in Python in other languages. In ʻelse, write the processing you want to be performed when the loop ends normally. In other words, if the ** break statement forcibly terminates the loop, that process will not be performed. ** ** It's not used very aggressively, but you can write cleaner code when you want to get rid of all nested for statements.

nested_for.py

nested_for.py


#with else
for i in range(10):
    for j in range(10):
        print(i, j)
        if i * j > 10:
            # i = 2, j =Enter here at 6
            break
    else:
        continue
    break

#without else
flag = False
for i in range(10):
    for j in range(10):
        print(i, j)
        if i * j > 10:
            # i = 2, j =Enter here at 6
            flag = True
            break
    if flag:
        break

The continue statement is for passing through the subsequent processing and moving to the next loop.

while statement

Next is the while statement.

while_sample.py

while_sample.py


i = 0
while i < 10:
    print(i)
    i += 1
print("----------")

i = 0
while i < 10:
    print(i, end=" ")
    if i > 5:
        print("\n{} > 5".format(i))
        break
    i += 1
else:
    print("This statement is not printed")

You can see that this while_sample.py is a loop process equivalent to for_sample.py. The syntax of the while statement is as follows:

while_grammer_summary.py


while (Conditional expression):
    (Write the process you want to repeat here)
else:
    (Write here the processing when the loop ends normally and the processing you want to do when the loop is never executed)

The feature of the while statement is that it loops as long as the conditional expression is satisfied. ** The big difference is that the for statement determines the number of loops in advance, while the while statement can be indefinite. ** ** This leads to why I personally don't want to use the while statement.

If you change the first loop of while_sample.py as follows and execute it, a large amount of 0 will continue to be output. ** << Caution >> ** ** Please keep in mind how to stop when you execute. ** **

while_sample.py


i = 0
while i < 10:
    print(i)
    #i += 1

** << How to stop >> ** Click ■ at the top to stop. With jupyter notebook, execution can be interrupted with a simple operation, which is convenient ~ while_error.gif

This happens because the value of the variable ʻi does not change, so the conditional expression ʻi <10 continues to be satisfied, and the processing is performed indefinitely. This situation is called an ** infinite loop **. This time, the error is easy to understand because it is output by the print function, but what if this occurs in 1000 lines of code without the output by the print function?

The code I wrote so hard doesn't work due to an error for some reason! not The code I wrote so hard doesn't respond even though there are no errors!

It will be the situation. When you're a beginner, you don't notice infinite loops so easily, which can be a headache. For the above reasons, there are few loops that can only be written with a while statement, so let's ** basically use a for statement **.

Let's draw a discontinuous function

It's been a long time, but let's write a discontinuous function using conditional branching and loop processing! Let's change the function f part of [graph_plot.py](https://qiita.com/kuroitu/items/8542b88d486d1dbf92a5#draw graph) as follows.

graph_plot.py


#List version
def f(x):
    result = []
    for i in x:
        if i < 0:
            result.append(i + 3)
        else:
            result.append(i ** 2)
    return result

graph_plot.py


#Version using numpy array
def f(x):
    result = np.zeros(len(x))
    for i in range(len(x)):
        if x[i] < 0:
            result[i] = x[i] + 3
        else:
            result[i] = x[i] ** 2
    return result

It is OK if a graph like this is plotted. discontinuous.png

Troublesome?

Is it annoying? no doubt. So I will also introduce a smart way of writing.

graph_plot.py


def f(x):
    return np.where(x < 0, x + 3, x ** 2)

numpy's where function is the so-called ternary operator. Let's google for details. By the way, if you do your best, even the standard writing style will be smart as it is.

graph_plot.py


def f(x):
    return [i + 3 if i < 0 else i ** 2 for i in x]

It's a combination of list comprehension and the ternary operator of the ʻif` statement.

list_comprehension_grammer.py


[(processing) for (Variable name) in (Arrays, lists, etc.)]

ternary_operator_grammer.py


(Processing when the conditional expression is true) if (Conditional expression) else (Conditional expressionが偽の時の処理)

However, it is difficult to read and complicated. ** You can see the greatness of the package. ** **

First Python series article

-First Python ~ Environment Construction ~ -First Python ~ Coding ~ -First Python ~ Assignment ~

[^ 1]: To be exact, it is the ʻappendmethod of the list type class. [^ 2]: Integer values less than or equal to 0 return an empty list. try it. [^ 3]: Thetry` statement can be said to be a conditional branch. [^ 4]: When the left limit and the right limit at that point match, and the value at that point and the limit value match, it is said that the function is continuous. In other words, if the functions are connected neatly, it is continuous. [^ 5]: Actually returns an iterator (loopable) object.

Recommended Posts

First Python ~ Coding 2 ~
First time python
First Python 3 ~ First comparison ~
First python [O'REILLY]
First Python 3rd Edition
First Python image processing
[Python] Python / Scikit-learn's first SVM
First Python miscellaneous notes
[Python] Chapter 01-01 About Python (First Python)
First Fabric (Python deployment tool)
Python
First neuron simulation with NEURON + Python
First simple regression analysis in Python
Competitive programming, coding test template: Python3
First Python 3 ~ The beginning of repetition ~
R / Python coding rule link summary
Web scraping with Python First step
First Python 3 ~ Extra: Numerical Random Fantasy ~
[GUI with Python] PyQt5-The first step-
Prepare your first Python development environment
Comply with Python coding standard PEP8
Python (from first time to execution)
C / C ++ programmer challenges Python (first step)
See python for the first time
Atom preferences for comfortable Python coding
The first step in Python Matplotlib
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
First Flask
Python memo
Continuously play the first Python Sukusta MV
Python comprehension
Python Singleton
Python basics ④
Python Memorandum 2
Python increment
atCoder 173 Python
[Python] function
First draft
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial