SoFunction
Updated on 2024-10-28

Easy if and loop judgment techniques in Python

When writing code, it is often necessary to make judgments based on certain conditions and execute different branches of code based on the results of the judgments.

# Individual conditions
a =1
if a==1:
    print(11111)

if a==2:
    print(2222)
else:
    print(333)

# Multiple conditions, add as many as you want #
if a==1:
    print(11111)
elif a==2:
    print(22222)
else:
    print(33333)

circular judgment

If we needed to print 100 numbers from 1 to 100, we certainly wouldn't be foolish enough to write 100 lines of print code, but would use a loop to handle similar repetitive tasks.

while loop

The idea of a while loop is to keep executing the code in the loop body as long as a condition is true, until the condition is no longer true.

flag = 0
while flag<10:
    print(flag)
    flag +=1   
# Always remember to change the condition variable in the loop body #
# Otherwise it may lead to a dead loop

for loop

The number of loops in a for loop is generally predetermined, and iterates over a flag variable from a start value to an end value.

# x starts at 0 and goes all the way to 9 #
for x in range(0,10):
    print(x)

Lists and dictionaries can be easily traversed with for loops.

li = [1,2.1,'Hello']
# Iterate through the list, where item is just a temporary variable.
for item in li:
    print(item)

dict = { k1:1,k2:2.1,k3:'Hello'}
# Iterate through all the keys of the dictionary, the key here is also just a temporary variable, the name doesn't matter.
for item in ():
    print(item)

# Iterate through all the values of the dictionary, where value is also a temporary variable with an unimportant name.
for item in ():
    print(item)

# Iterate over key and value at the same time
for key,value in ():
    print(key,end='|') 
    print(value)

cyclic control

There are three main types of loop control: pass, continue, and break.

pass means do nothing, just take up a line of code; continue means immediately exit the loop, continue to execute the subsequent rounds of the loop; break means immediately out of the loop, the subsequent rounds of the loop is no longer executed.

for x in range(0, 10):
    if x == 5:
        pass 
    else:
        print(x)

 for x in range(0, 10):
    if x == 5:
        continue
    print(x)

for x in xrange(0, 10):
    if x == 5:
        break    
    print x

to this article on the easy to master Python if and loop judgment skills in the article is introduced to this, more related python if judgment and loop judgment content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!