[Introduction to Data Scientists] Basics of Python ♬ Conditional branching and loops

Continued from last night. 【Caution】 ["Data Scientist Training Course at the University of Tokyo"](https://www.amazon.co.jp/%E6%9D%B1%E4%BA%AC%E5%A4%A7%E5%AD%A6%E3 % 81% AE% E3% 83% 87% E3% 83% BC% E3% 82% BF% E3% 82% B5% E3% 82% A4% E3% 82% A8% E3% 83% B3% E3% 83 % 86% E3% 82% A3% E3% 82% B9% E3% 83% 88% E8% 82% B2% E6% 88% 90% E8% AC% 9B% E5% BA% A7-Python% E3% 81 % A7% E6% 89% 8B% E3% 82% 92% E5% 8B% 95% E3% 81% 8B% E3% 81% 97% E3% 81% A6% E5% AD% A6% E3% 81% B6 % E3% 83% 87% E2% 80% 95% E3% 82% BF% E5% 88% 86% E6% 9E% 90-% E5% A1% 9A% E6% 9C% AC% E9% 82% A6% I will read E5% B0% 8A / dp / 4839965250 / ref = tmm_pap_swatch_0? _ Encoding = UTF8 & qid = & sr =) and summarize the parts that I have some doubts or find useful. Therefore, I think the synopsis will be straightforward, but please read it, thinking that the content has nothing to do with this book.

Chapter1-2 Python Basics

Operators and operations are summarized for reference. 【reference】 Introduction to Python for Tohoho-Operators

1-2-4 Conditional branch and loop

Python code runs from top to bottom. Syntax for changing the flow and performing conditional branching and iterative processing

1-2-4-1 Comparison operator and authenticity judgment
print(1 == 1)
print(1 == 2)
print(1 != 2)
print(1 > 0)
print(1 > 2)
print((1 > 0) and (10 > 5))
print((1 < 0) or (10 > 5))
print(not (1 < 0))
print(not (1 < 0))
print(not (1 < 0) and (10 > 5))
print(not (1 < 0) and not (10 > 5))
print(5 >= 50 or 5 < 20 and 5 == 5)
print((5 >= 50 or 5 < 20) and 5 == 5)

result

True
False
True
True
False
True
True
True
True
False
True
True

【reference】 Illustration! Thorough explanation of how to specify multiple conditions with and and or in Python if statements! According to the reference, the following code is "False."

x = 5
y = 5
if x >= 50 or x < 20 and y == 5:
   print("True.")
else:
   print("False.")

Reason; and has priority over and However, in the current Operator precedence in Python3, or takes precedence over and, and it becomes True. 【reference】 6.17. Operator precedence (Partially quoted)

Operator Description
:= Assignment expression
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests and identity tests
^ Bitwise XOR
& Bitwise AND
... ...
1-2-4-2 if statement

Basic

if conditional expression 1:
    `Processing to be performed when conditional expression 1 is True`
elif conditional expression 2:
    `Processing to be performed when conditional expression 1 is False and conditional expression 2 is True`
elif conditional expression 3:
    `Conditional expression 1,Processing to be performed when 2 is False and conditional expression 3 is True`
...
else:
    `Processing to be performed when all conditional expressions are False` 
In the conditional expression of the if statement in Python, the following objects are regarded as false False.
・ Bool type False
・ None
・ Numerical value (int type or float type) 0, 0.0
-Empty string''
· Empty containers (lists, tuples, dictionaries, etc.)[], (), {}

Everything else is considered true True.

So far, quoted from the following reference 【reference】 How to write conditional branch by if statement in Python

data_list = [1,2,3,4,5,6,7] 
findvalue = 8
if findvalue in data_list:
    print('{}Is included'.format(findvalue))
else:
    print('{}Is not included'.format(findvalue))
print('find value is{}was'.format(findvalue))

result The last print line is always printed outside the if statement.

8 is not included
find value was 8
format notation

【reference】 [Introduction to Python] How to write a character string with the format function While looking at the reference, I will try the notation that seems to be interesting.

apple  = 50
orange = 100
total = apple + orange

print('Apple:{0}Yen mandarin orange:{1}Yen total:{2}Circle'.format(apple, orange, total))
print('Apple:{}Yen mandarin orange:{}Yen total:{}Circle'.format(apple, orange, total))

list1 = [apple, orange]  #Creating a list
list2 = [total]
print('Apple:{0[0]}Yen mandarin orange:{0[1]}Yen total:{1[0]}Circle'.format(list1,list2))
print('Apple:{0[0]}Yen mandarin orange:{0[1]}Yen total:{1}Circle'.format(list1,list2[0]))
print('Apple:{}Yen mandarin orange:{}Yen total:{}Circle'.format(list1[0],list1[1],list2[0]))
Apples: 50 yen Mandarin oranges: 100 yen Total: 150 yen
Apples: 50 yen Mandarin oranges: 100 yen Total: 150 yen
Apples: 50 yen Mandarin oranges: 100 yen Total: 150 yen
Mandarin oranges: 100 yen Apples: 50 yen Total: 150 yen
Apples: 50 yen Mandarin oranges: 100 yen Total: 150 yen

The notation for floating point is often used, so see below. 【reference】 Python string format (how to use the format method)

line = "{0}Is tall{1:.0f}cm, weight{2:.1f}It is kg.".format("Yamada", 190, 105.3)
print(line)
line = "{1}Is tall{2:^10,.5f}mm, weight{3:.0f}It is kg.".format("Yamada","Mountain", 1900, 105.3)
print(line)

result

Mr. Yamada is 190 cm tall and weighs 105.It is 3 kg.
Mr. Yama's height is 1,900.It is 00000mm and weighs 105kg.
{2:^10,.5f} 1,900.00000
2 index
: Format start
^ Output position
10 Output width
, In a thousand places,
.5 5 digits after the decimal point display
f Floating point number
1-2-4-3 for sentence

The following three types of for statements are often used (numerical value, list type, dictionary type)

1-2-4-4 numerical value

The following is normally turned from 0 to 10. The calculation is addition. It is output each time. range (0,11,1); range (initial value, final value + 1, interval)

s=0
for i in range(0,11,1):
    s += i
    print(s)

result

0
1
3
6
10
15
21
28
36
45
55
list type
s=0
list1 = [0,1,2,3,4,5,6,7,8,9,10]    
for i in list1:
    s += i
    print(s)

result

0
1
3
6
10
15
21
28
36
45
55
Dictionary type
dict_data = {'apple':100,'banana':100,'orange':300,'mango':400,'melon':500}
for dict_key in dict_data:
    print(dict_key,dict_data[dict_key])

result

apple 100
banana 100
orange 300
mango 400
melon 500

Get key and value from dictionary type with dict_data.items () and output

dict_data = {'apple':100,'banana':100,'orange':300,'mango':400,'melon':500}
for key, value in dict_data.items():
    print(key,value)

result

apple 100
banana 100
orange 300
mango 400
melon 500
1-2-4-5 List comprehension
data_list = [1,2,3,4,5,6,7,8,9]
data_list1 = []
data_list1 = [i*2 for i in data_list]
print(data_list1)

result

[2, 4, 6, 8, 10, 12, 14, 16, 18]

Output only when i% 2 == 0 (the remainder when i is divided by 2 is 0)

print([i*2 for i in data_list if i%2==0])
[4, 8, 12, 16]
1-2-4-6 zip function

When there are two lists as shown below, the elements can be extracted in order from each list.

list1 = ['apple','banana','orange','mango','melon']
list2 = [100, 100, 300, 400, 500]
for one, two in zip(list1, list2):
    print(one, two)

result By the way, if the number of elements does not match, the output is made according to the smaller number from the head.

apple 100
banana 100
orange 300
mango 400
melon 500
Create dictionary type data from two lists with zip function
dict_new = {}
list1 = ['apple','banana','orange','mango','melon','pinapple']
list2 = [100, 100, 300, 400, 500]
for one, two in zip(list1, list2):
    dict_new.update({one: two})
print(dict_new)
print(type(dict_new))

result

{'apple': 100, 'banana': 100, 'orange': 300, 'mango': 400, 'melon': 500}
<class 'dict'>
enumerate function
list1 = ['apple','banana','orange','mango','melon','pinapple']
list2 = [100, 100, 300, 400, 500]
for i, name in enumerate(list1):
    print(i, name)

result

0 apple
1 banana
2 orange
3 mango
4 melon
5 pinapple

Start index specification

for i, name in enumerate(list1, 3):
    print(i, name)

result

3 apple
4 banana
5 orange
6 mango
7 melon
8 pinapple

Zip list1 and list2 and add index.

for i, name in enumerate(zip(list1, list2)):
    print(i, name)

result

0 ('apple', 100)
1 ('banana', 100)
2 ('orange', 300)
3 ('mango', 400)
4 ('melon', 500)
1-2-4-7 Iterative processing using while statement
num = 0
s = 0
while num <= 10:
    s += num
    print(s)
    num += 1

result

0
1
3
6
10
15
21
28
36
45
55
continue and break

The result of the code below is the same as above, but while 1: is always True, explaining the role of the process continuation coinue and the process break break.

num = 0
s = 0
while 1:
    if num <= 10:
        s += num
        print(s)
        num += 1
        continue
    break

By the way, if there is no continue, it will end with 0, and if there is no break, the process will not end. Also, if both are not available, the process will not end.

Summary

・ Conditional branching and rules ・ If statement, for statement, inclusion notation, zip function, enumerate function, while statement are summarized.

It is easy to understand if you go back to the basics and arrange them side by side.

Recommended Posts

[Introduction to Data Scientists] Basics of Python ♬ Conditional branching and loops
[Introduction to Data Scientists] Basics of Python ♬
[Introduction to Data Scientists] Basics of Python ♬ Functions and classes
[Introduction to Data Scientists] Basics of Python ♬ Functions and anonymous functions, etc.
[Introduction to Data Scientists] Basics of Probability and Statistics ♬ Probability / Random Variables and Probability Distribution
[Introduction to Data Scientists] Basics of scientific calculation, data processing, and how to use graph drawing library ♬ Basics of Scipy
[Introduction to Data Scientists] Basics of scientific calculation, data processing, and how to use graph drawing library ♬ Basics of Matplotlib
List of Python libraries for data scientists and data engineers
[Introduction to Data Scientists] Basics of scientific calculation, data processing, and how to use the graph drawing library ♬ Environment construction
[Introduction to cx_Oracle] (Part 6) DB and Python data type mapping
[Introduction to Data Scientists] Descriptive Statistics and Simple Regression Analysis ♬
[Introduction to Python] Combine Nikkei 225 and NY Dow csv data
Introduction to Python Basics of Machine Learning (Unsupervised Learning / Principal Component Analysis)
[Introduction to Python] I compared the naming conventions of C # and Python.
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part2-
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part4-
[Introduction to Udemy Python3 + Application] 69. Import of absolute path and relative path
[Introduction to Udemy Python3 + Application] 12. Indexing and slicing of character strings
[Introduction to cx_Oracle] (Part 2) Basics of connecting and disconnecting to Oracle Database
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part3-
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Python3 Day 18] Chapter 8 Data Destinations (8.3.6.2 to 8.3.6.3)
Compress python data and write to sqlite
Easy introduction of python3 series and OpenCV3
Introduction of Python
Basics of Python ①
Basics of python ①
Introduction of Python
[Introduction to Udemy Python 3 + Application] 26. Copy of dictionary
[Introduction to Python3 Day 12] Chapter 6 Objects and Classes (6.3-6.15)
[Introduction to cx_Oracle] (Part 3) Basics of Table Reference
[Introduction to Python3 Day 22] Chapter 11 Concurrency and Networking (11.1 to 11.3)
[Introduction to Python] How to handle JSON format data
[Introduction to Udemy Python3 + Application] 64. Namespace and Scope
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
[Python] Chapter 02-01 Basics of Python programs (operations and variables)
[Introduction to cx_Oracle] (5th) Handling of Japanese data
List of Python code to move and remember
[Introduction to Python] Basic usage of lambda expressions
[Python] From morphological analysis of CSV data to CSV output and graph display [GiNZA]
[Python] Eliminate conditional branching by if by making full use of Enum and eval
[Introduction to Python] How to get the index of data with a for statement
What to use for Python stacks and queues (speed comparison of each data structure)
Full-width and half-width processing of CSV data in Python
[Chapter 5] Introduction to Python with 100 knocks of language processing
Reading Note: An Introduction to Data Analysis with Python
Introduction to Python language
Introduction to OpenCV (python)-(2)
[Introduction to Udemy Python3 + Application] 53. Dictionary of keyword arguments
[Introduction to Python] Summary of functions and methods that frequently appear in Python [Problem format]
[Chapter 3] Introduction to Python with 100 knocks of language processing
# 4 [python] Basics of functions
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Introduction to cx_Oracle] (Part 11) Basics of PL / SQL Execution
[Introduction to Sound] Let's arrange the introduction to sounds of python and R ♬-Listen to the sound of the explosion of Nikkei 255-
Paiza Python Primer 2: Learn Conditional Branching and Comparison Operators
[Python] Chapter 05-01 Control syntax (comparison operator and conditional branching)
[Basics of data science] Collecting data from RSS with python
[Introduction to Udemy Python3 + Application] 52. Tupleization of positional arguments