Next is about conditions and repetition
Meaning in Japanese It ’s a pretty important position in programming.
#format
if #First condition
elif #Second to n conditions
else #Other than the nth condition
#Example of use
#After the condition ":Don't forget to indent the output
n = 3
if n == 1:
print("No. 1 processing")
elif n == 2:
print("No. 2 processing")
elif n == 3:
print("No. 3 processing")
else: #When all the above conditional expressions are not satisfied
print("Processing other than the above")
#output:No. 3 processing
True if basic conditions are met If it does not come out, falsa is returned.
code | Contents |
---|---|
a==b | equal |
a!=b | Not equal |
a>b | a is greater than b |
a>=b | a is equal to or greater than b |
a<b | a is less than b |
a<=b | a is equal to or less than b |
A and B #Conditional expressions for both A and B are satisfied
A or B #Either A or B conditional expression is satisfied
not conditional expression#Result reversal
Example of use
A = 1
B = 2
print(A==1 and B==2)
# true
print(not B < A)
# true
Processing that repeats while the condition is met
while
n = 5
while n >2: #If n is greater than 0, perform the following processing
print(n)
n -= 2 #n-1
#Output result 5 3
x = 5
while x != 0:
x -= 1
if x != 0:
print(x)
else:
print("end")
I will post more about the list later We will go through the contents of multiple variables.
moji = ["A", "B", "C"]
for ji in moji: #Number of elements contained in animals = Repeat processing 3 times
print(ji)
#Output result
A
B
C
break End of repetition
break
li = [1, 2, 3]
for n in li:
print(n)
if n >= 3:
print("Confirm 3 or more")
break #end of for statement processing
continue Used when you want to skip processing
continue
li = [10, 20, 30, 40] #Number of elements contained in storages=Repeat processing 6 times
for n in li:
if n < 30: #If n is less than 30, no processing is performed(skip)
continue
print(n)
#Output result
3
4
There is also a repeat method that mixes index and key and value.
It is used when you want to display the index in the for statement.
index display
li = ["iti", "ni"]
for index, value in enumerate(li):
print(index, value)
#Output result
0 a
1 b
It can be output by preparing the variable of the assignment destination.
Repeating multiple lists
li = [[1, 2, 3], [4, 5, 6]]
for a, b, c in li:
print(a, b, c)
#Output result
1 2 3
4 5 6
However, if the original data does not contain the number statement data, an error will occur.
Multiple list repetition error
li = [[1, 2, 3], [4, 5]]
for a, b, c in li:
print(a, b, c) #Get an error
#Output result
not enough values to unpack (expected 3, got 2)
By using a function called items () You can use both keys and values.
Dictionary-style repetition
man = {"name": "yamada", "hair": "black", "arm": "left"}
for hidari, migi in man.items():
#The key is stored in hidari and the value is stored in migi.
print(hidari+" is "+migi)
#Output result
name is yamada
hair is black
arm is left
Recommended Posts