[Python] Organizing how to use for statements

1.First of all

My programming is based on MATLAB. When I started Python, there was a tough time because ** How to use For statements ** was very different from MATLAB. Today, I'll organize how to use Python's For statement.

1.1. For statement in Matlab

Format for variable = initial value: incremental: final value statements end

You must declare a for variable and enter its initial value: final value.

x = ones(1,10);

for n=2:6 
    x(n) = 2 * x(n-1);
end

2. For statement in Python

Format for variable in list (or Tuple, Dictionary, etc.): statements

Note that, like Matlab, ** the initial value of a variable: declare a list, not the final value **. The concept of this part is very different.

2.1. Typical For statement

Create a list and print its elements.

test_list = ['one','two','three']
for i in test_list: #<-one, two,Substitute three in order for i.
  print(i)

Result

one two three

2.2. Various For statements

If the list element is Tuple

a = [(1,2),(3,4),(5,6)]

for (first, last) in a:
  print('first element:', first)
  print('last element :', last)
  print('sum of first and last element =', first + last)

Result

first element: 1 last element : 2 sum of first and last element = 3 first element: 3 last element : 4 sum of first and last element = 7 first element: 5 last element : 6 sum of first and last element = 11

2.3. Application

Suppose you take a test for 5 students. If the test score exceeds 60 points, it will be passed. If not, it will be rejected. Create a program that displays pass / fail according to the test score.


score = [90,25,67,45,80] #Test score

number = 0 #Numbers given to students
for mark in score: #<- 90,25,67,45,Substitute 80 in order for mark.
  number = number + 1
  if mark >= 60:
    print("{:d}The second student has passed.".format(number))
  else:
    print("{:d}The second student fails.".format(number))

Result

The first student has passed. The second student fails. The third student has passed. The fourth student fails. The fifth student has passed.

2.4. Frequently used range ()

The for statement is often used with a function called range that automatically creates a list of numbers.

ar = range(1,11) %<- 1,2,3,4,5,6,7,8,9,10

Note that ars created with range () are ** range objects, not lists **.

type(ar)

Result

range

Now let's use the for statement and range () to create the code to find the sum from 1 to 10.

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

print(sum)

Result

55

If the score is 60 or more, the code that outputs the sentence "Pass" can be rewritten as follows.

score = [90,25,67,45,80]

for number in range(len(score)):
  if score[number] >= 60:
    print("{:d}The second student has passed.".format(number))
  else:
    print("{:d}The second student fails.".format(number))

Result

The 0th student has passed. The first student fails. The second student has passed. The third student fails. The fourth student has passed.

2.5. Put a for statement in the list

This code creates a list called a and stores the result of multiplying each element by 3 in a list called result.

a = [1,2,3,4]
result = []
for yoso in a:
  result.append(yoso*3)

print(result)

Result

[3, 6, 9, 12]

This can be made into a simple code as follows by using the method of putting a for statement in the list.

a = [1,2,3,4]
result = [num * 3 for num in a]

Result

[3, 6, 9, 12]

If you triple it to an even number, you can add an if statement as follows.

a = [1,2,3,4]
result = [num * 3 for num in a if num%2 ==0]

Result

[6, 12]

3. Summary

I tried to organize various usages of Python for statement. It's deep.

Recommended Posts

[Python] Organizing how to use for statements
How to use "deque" for Python data
python3: How to use bottle (2)
[Python] How to use list 1
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
[BigQuery] How to use BigQuery API for Python -Table creation-
[For beginners] How to use say command in python!
[Introduction to Python] How to use while statements (repetitive processing)
[Introduction to Python] How to write repetitive statements using for statements
Python: How to use async with
[Python] How to use Pandas Series
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to use python zip function
[Python] How to use Typetalk API
[python] How to use the library Matplotlib for drawing graphs
How to use machine learning for work? 03_Python coding procedure
I didn't know how to use the [python] for statement
[Python] Summary of how to use pandas
[Introduction to Python] How to use class in Python?
How to install and use pandas_datareader [Python]
[python] How to use __command__, function explanation
[Python] How to use import sys sys.argv
Memorandum on how to use gremlin python
[Python2.7] Summary of how to use unittest
python: How to use locals () and globals ()
How to use __slots__ in Python class
How to use Pylint for PyQt5 apps
How to use Python zip and enumerate
[Python] Understand how to use recursive functions
Summary of how to use Python list
How to use regular expressions in Python
[Python2.7] Summary of how to use subprocess
How to use fingerprint authentication for KDE
How to use is and == in Python
[Blender x Python] How to use modifiers
[Question] How to use plot_surface of python
How to use an external editor for Python development with Grasshopper
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to install Python
How to use Pandas 2
How to use Virtualenv
How to use pytest_report_header
How to install python