This time too, it's a continuation of the basics of Python.
Click here for the last time [You will be an engineer in 100 days --Day 28 --Python --Basics of Python language 4] (https://qiita.com/otupy/items/f9324f682df276b44ed3)
Until the last lecture, the basic data types of python and I have told you how to use operators.
Conditional branching, repetition, etc. in python There is a grammar to control the program.
We call it a control statement.
Control statements are used for programming Indispensable It comes out everywhere.
Let's hold down how to write and how to use it.
The if statement is a syntax for conditional branching.
** How to write an if statement **
if condition:
processing
if condition:
processing
else:
processing
if condition:
processing
elif condition:
processing
・ ・ ・
First of all, in the case of IF alone
Write the condition and write the :
semicolon at the end.
#print if the condition is met in the if statement
if 1<2:
print('2 is bigger than 1')
2 is bigger than 1
The processing in the if statement can be executed only when that condition is met.
Note that when using control statements, the block that writes the process is
You have to shift it by 4 blanks by saying indent
.
You can also use the tab button for the four blanks.
if 1<2:
print('2 is bigger than 1')
IndentationError: expected an indented block
If you do not indent
, an error will occur.
#The condition is True or False
hh = 8
if hh== 8:
print(hh)
8
In the if statement, the condition can be bool type
or boolean
.
Next, if the conditions are not met Write ʻelse:` after the if statement You can also write branch processing when the conditions are not met.
hh = 7
if hh== 8:
print('{}It's time, everyone gathers'.format(hh))
else:
#If the conditions are not met, this will be executed.
print('{}It's time, everyone disbanded'.format(hh))
It's 7 o'clock, everyone disbanded
When there are multiple conditions ʻElif Condition: You can increase the condition with`.
hh = 9
if hh== 8:
print('{}It's time, everyone gathers'.format(hh))
elif hh==9:
#If the conditions are met, it will be executed.
print('{}It's time, everyone is late'.format(hh))
else:
#If the conditions are not met, this will be executed.
print('{}It's time, everyone disbanded'.format(hh))
It's 9 o'clock, everyone is late
In the if statement, it is executed only when the conditions are met.
You only need to use ʻelse or ʻelif
when you want to branch the condition.
When the condition spans multiple conditions
You can create a hierarchy of if statements by saying nested
.
In that case, indent
is performed for the hierarchy of the if statement.
aa = 2
bb = 50
if aa == 2:
if bb == 50:
print('Egashira{0}Time{1}Minutes'.format(aa,bb))
else:
print('Egashira{0}Time'.format(aa))
else:
print('Egashira')
Egashira 2:50
Please note that the processing changes depending on the position of indent
.
By using nesting under any conditions You will be able to write them separately.
However, if you use too much nesting I don't understand. It's hard to see.
If it gets too deep I think it is better to review the processing and conditions in the first place.
Also, if you do not write any processing in the if statement, an error will occur.
if 1<2:
SyntaxError: unexpected EOF while parsing
If you can't think of any processing, write pass
for the time being.
if 1<2:
pass
pass
represents a process that does nothing.
If you write only the control statement and execute it without writing the process
It will cause an error and can be used to avoid it.
In python, the block processed by indent
changes.
So whether it is the process in the if statement or the process before it
Because the whole process may change significantly
Think about what you want to do and do indent
.
If you want to repeat
the process in python, use for
.
** How to write for **
for Arbitrary variable name in iterable object:
processing
** What is an iterable object? ** **
A iterable object
is an object that can be repeated.
In short, it is an object that has multiple elements.
For example, if you store a string
in a variable
aaaa = 'abcde12345'
print(aaaa)
abcde12345
This will be the object
of the string.
Because object-oriented treats data
as object
The variable
that stores the data is also the same as the object
.
So what is a iterable object
?
This means that it can be repeated
It is a object with multiple elements
.
In short, it becomes an object with a data structure such as list type
, dictionary type
, and string type
.
The Python language uses this object to iterate.
** Simple for statement example **
#Repeat 5 times
for i in [1,2,3,4,5]:
print(i)
1 2 3 4 5
This is the simplest repetition.
Please indent
the part of the repeated processing in the for
statement.
I wrote the number of times to repeat after ʻin It is performed for the number of elements of
Iterable Object`.
The variable ʻi written after
for` is
It will be a variable that can be used in the iteration.
Each time the first of this list is assigned to this ʻi` The second time is the second ... Because it is a mechanism It is a mechanism that processing is executed for the number of elements in this list.
The list works the same even if you assign it to a variable.
#Store 6 elements in a list type variable
sample_list =[ 1,2,3,4,5,6]
#Repeat 6 times
for i in sample_list:
print(i)
1 2 3 4 5 6
** If you want to specify the number of times **
Generate the value for the number of times with the range ()
function.
Because the number of times part used for for
must be iterable object
Instead, use the range ()
function to create an object and substitute it.
Since the range ()
function can create a specified number of objects
It is a mechanism that can be used as a substitute for specifying the number of for statements.
** How to write the range function **
range (integer value)
range (start, end)
range (start, end, interval)
The range ()
function is only for the integer value specified in the argument
It will generate a number.
You can also adjust the start and end numbers and intervals by adding arguments.
#Create an object with 10 numbers
print(range(10))
range(0, 10)
The result of the range function
is of type range
.
However, this is not a list type
, so it is difficult to understand.
Let's convert it to list type
.
print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This makes it a list type
and makes it easier to understand the contents.
The range ()
function starts from 0 and generates integer values for the arguments.
Please note that since it starts from 0, the end does not reach the specified value.
It is the specified value -1
.
for i in range(3):
print(i)
0 1 2
#When executing only 4 times with the range function
for i in range(4):
print(i)
0 1 2 3
When specifying start and end, it starts from the first argument and ends with the second argument.
In this case, the values from 5
to one before 10
are generated.
#From 5 to 9
for i in range(5,10):
print(i)
5 6 7 8 9
If you specify the third argument, you can decide how much to add. If you specify a minus, you can also subtract.
#Even number from 2 to 10 before
for i in range(2,10,2):
print(i)
2 4 6 8
#By skipping 3 pieces from 20 to 10 before
for i in range(20,10,-3):
print(i)
20 17 14 11
** Repeat with string **
Repetition is basically executed by the number of elements using some object
Whether to execute the specified number of times using the range ()
function
It means that.
If you specify a character string, it will be executed for that number of characters.
#When executing as many as the number of character string type characters
for i in 'apple':
print(i)
a p p l e
** If you break in the middle of the repetition (break) **
If you want to exit the process in the for statement, use break
.
When break is executed, the block of the for statement will be exited.
li = ['Alice', 'in', 'Chains']
for name in li:
if name == 'in':
print('!!BREAK!!')
#Exit here
break
#No second processing
print(name)
Alice !!BREAK!!
In this case, the condition of the if statement is caught in the second repetition, and
The print statement and break
in it are executed.
In that case, if you exit in the middle, the subsequent processing will not be performed. As a result, it came off before the second print.
You can also use ʻelse in the for statement. The ʻelse
part is executed at the very end.
for i in ['Alice', 'in', 'Chains']:
print(i)
else:
#Executed after the for statement
print('Processing Exit')
Alice in Chains Processing Exit
If the picture ends in the middle due to break ʻElse` processing is not executed.
li = ['Alice', 'in', 'Chains']
for name in li:
if name == 'in':
print('!!BREAK!!')
break
print(name)
else:
#Not executed after break
print('!!FINISH!!')
Alice !!BREAK!!
** If you want to skip the process in the middle of the process (continue) **
break
completely skips the process
If you want to skip only part of the process and continue the process
Use continue
.
li = ['Alice', 'in', 'Chains']
for name in li:
if name == 'in':
print('!!continue!!')
#Skip processing here
continue
#Not executed after continue
print(name)
else:
#Last run
print('!!FINISH!!')
Alice !!continue!! Chains !!FINISH!!
The for statement is used frequently in the program Required for programs.
While thinking about how to assemble the process We will use the for statement.
Especially rather than writing complicated processing that is done more than once Because it is easier to finish with one for sentence Please also study how to use it.
The end of the control statement is a while statement.
In the for statement, the number of repetitions was fixed, While continues repeating until the condition is met.
How to write while
while condition:
processing
You will need indent
where you write the process.
while True:
However, if you write like this, it will be repeated all the time. It never ends.
If you want to stop on jupyter notebook
Press the square button (stop)
at the top of the screen to stop.
The while statement must write a process that exits the condition Be careful as it will result in an endless loop.
While statement example:
sample_int =1
while sample_int <= 10:
print(sample_int)
sample_int = sample_int + 1
1 2 3 4 5 6 7 8 9 10
In this way, in the while statement using variables etc. as conditions If you change the variable so that it does not meet the conditions You can get out of the while repetition.
Prepare variables for counting in advance,
It is possible to exit the while statement
by using a flag value.
It will be a general usage.
You can use continue
and break
as well as for.
i=0
while i<5:
if i ==2:
i+=1
continue
print(i)
i+=1
0 1 3 4
i=0
while i<5:
if i ==2:
break
print(i)
i+=1
0 1
continue
is as long as the conditions are met
Note that the iterations will continue to run.
Control statements such as conditional branching and repetition It's an important part of programming that exists in every language.
Understand the grammar so that the program can be executed correctly Let's be able to write code.
71 days until you become an engineer
Otsu py's HP: http://www.otupy.net/
Youtube: https://www.youtube.com/channel/UCaT7xpeq8n1G_HcJKKSOXMw
Twitter: https://twitter.com/otupython
Recommended Posts