[python Programming] basics 2 - statements: loop, condition, break, pass, continue

This article introduces all statements in python language, judgment statement if, loop statement for and while, as well as break, continue, pass and other statements used.

First of all, let's talk about the views of a Han batch who works with C + + (but is not proficient at all) on python programming. As we all know, both conditional and circular statements are followed by a pair of curly braces {}. The curly braces are the statements executed under this condition, but Python does not have curly braces. It marks which clauses are the executors under which conditions in its way. In this way, the statement is forced to have a neat structure, which is a good point. Another point is that whether a loop or a conditional statement, there is a colon after the judgment condition to indicate the start of execution.

In python, it is not necessary to enclose the judgment conditions in parentheses.

The rest are summarized later. Let's start the formal content.

1, Conditional statement (if else)

Example sentence 1:

a=1
while a<7:
    if a%2==0 :
        print("%d is even" % a)
    else:
        print(a,"is odd")
    a+=1

It can be seen that it is relatively simple and can be summarized as follows:

(1) if and else should be followed by colons to indicate the beginning of the judgment body;

(2) The judgment conditions can be < =, &, |, or the continuous region of 1 < a < 3 (different from C);

(3) The end of the execution body is marked by statement alignment;

(4) It is important to include the judgment conditions when several judgment conditions need to be met at the same time:

if (a%2==0) & (a<5) & (a>2) :

Example 2:

num = 3
if num == 3:            # Determine the value of num
    print('boss')
elif num < 0:           # Output when the value is less than zero
    print('error')
else:
    print('roadman')

It should be noted that,

(1) Else if is abbreviated as elif;

(2) Because python does not support switch, you can only use elif in multiple cases;

Example 3:

num = 9
if num >= 0 and num <= 10:  # Judge whether the value is between 0 and 10
    print('hello')

num = 5
if num > 0 or num < 4:  # Judge whether the value is less than 0 or greater than 10
    print('hello')
else:
    print('undefine')

To express that multiple conditions are true at the same time, you can use not only & and |, but also and or. When using the latter, you don't need to enclose each condition in parentheses.

Example sentence 4:

a=1
while a<7:
    if a%2==0: print("%d is even" % a)
    else: print(a,"is odd")
    a+=1

Simple sentences can be added directly after the colon without starting another line.

2, Circular statement

Loop type: it is divided into for loop and while loop, and they should be nested with each other.

Loop control statement:

(1) break statement: terminate the loop and jump out of the whole loop;

(2) continue statement: jump out of this cycle and execute the next cycle;

(3) pass statement: an empty statement to maintain the integrity of the structure;

Note: the above three are loop control statements, which can end / jump out of the loop rather than jump out of the judgment statement.

1. while statement

Example sentence 1:

i = 1
while i < 10:
    i += 1
    if i%2 > 0:     # Skip when odd, output when even
        continue
    print(i)

The above is a simple example sentence, using continue.

Example 2:

count = 0
while count < 5:
   print (count, " is  less than 5")
   count = count + 1
else:
   print (count, " is not less than 5")

In python, while else statements can execute else statement blocks when the loop condition is false. This can be used to mark the end of judgment. It is suggested that you can use it, but it is not very useful.

Example 3:

numbers=[12,37,5,42,8,3]
odd=[]
even=[]
while len(numbers)>0:
    number=numbers.pop()
    if number%2==0:
        even.append(number)
    else:
        odd.append(number)
print(even)
print(odd)

This is a complex example sentence, which involves the append() and pop() operations of the list. It will not be explained in detail here.

2. for statement

The general format is for expr   in rangeexpr: loop body.

range() is generally used. The specific examples are as follows.

Example sentence 1:

for letter in 'Python':  # First instance
    print("Current letter: %s" % letter)

fruits = ['banana', 'apple', 'mango']
for fruit in fruits:  # Second instance
    print('Current fruit: %s' % fruit)
print("Good bye!")

Output instance:
Current letter: P
 Current letter: y
 Current letter: t
 Current letter: h
 Current letter: o
 Current letter: n
 Current fruit: banana
 Current fruit: apple
 Current fruit: mango
Good bye!

Note: Generally speaking, if a string or a list is written directly in the range after for, the previous single variable represents each character in the string or each element in the list.

There are many ways to access each element in the list or each character in the string. For example, you can also use the len() function. There are two parameters in the range() function here, which represent the upper and lower limits of (one parameter is the upper limit, and the lower limit is 0)

fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
    print('Current fruit : %s' % fruits[index])

print("Good bye!")

Output:
Current fruit : banana
 Current fruit : apple
 Current fruit : mango
Good bye!

Example 2:

for num in range(20):  # Iterate numbers between 10 and 20
   for i in range(2,num): # Iteration according to factor
      if num%i == 0:      # Determine the first factor
         break            # Jump out of current loop
   else:                  # else part of the loop
      print ('%d Is a prime number' % num)

Output:
0 Is a prime number
1 Is a prime number
2 Is a prime number
3 Is a prime number
5 Is a prime number
7 Is a prime number
11 Is a prime number
13 Is a prime number
17 Is a prime number
19 Is a prime number

Here, in range(), I write one parameter and two parameters respectively. And I suddenly found that this else is really clever. If the for loop body is not executed, it will be executed. It makes up for the fact that such things in C language must add a flag parameter record. You can pay attention to it.

3. continue, pass statements

Example sentence 1:

var = 6
while var > 0:
    var = var -1
    if var == 2 or var == 4:
        continue
    print ('Current value :', var)
print ("Good bye!")

continue has the function of deleting. I hope to write it down and put it into use.

Example 2:

pass is an empty statement to maintain the integrity of the structure. python 3.X can be written or not. It is generally used to occupy the position of def function.

# Occupy position
def sample(n_samples):
    pass
for letter in 'Python':
   if letter == 'h':
      pass
      print 'This is pass block'
   print 'Current letter :', letter
print "Good bye!"

Output:
Current letter : P
 Current letter : y
 Current letter : t
 This is pass block
 Current letter : h
 Current letter : o
 Current letter : n
Good bye!

Summary:

(1) End with a line without a semicolon at the end of each line;

(2) Each statement is followed by a colon;

(3) Pay attention to the use of brackets for & and |, and and or;

(4) Pay attention to the else statement in the loop statement, which is cleverly applied to make up for the deficiency in C language;

(5) continue is used to delete, pass is used to occupy the position of def function;

(6) The range() function is divided into one parameter and two parameters;

(7) Various functions in the list, append() and pop();

(8) Traversal of strings, lists, tuples, etc;

Keywords: Python

Added by noaksey2000 on Sat, 04 Sep 2021 06:44:38 +0300