In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "detailed explanation of Python Loop statement Code". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
.1 while cycle
Loop statement is one of the commonly used statements in programming. Any programming language has a while loop, and Python is no exception. The format of the while loop is as follows.
While (expression):... Else: …
The execution of the while loop: when the loop expression is true, the statements in the while are executed in turn. Until the value of the loop expression is False, the flow of the program goes to the else statement. The else clause and the parentheses on both sides of the expression can be omitted.
Note: the else clause in the while loop is also part of the loop, and the else clause will be executed at the end of the last loop.
The following code demonstrates the use of a while loop. The program first requires the input of five numbers, and then outputs the five numbers in turn.
# while loop numbers = input ("enter several numbers separated by commas:") .split (",") print (numbers) x = 0 while x
< len(numbers): # 当x的值小于输入字数的个数的时候,执行循环内容 print (numbers[x]) x += 1 # 一个循环结束时给x加1 【代码说明】 第2行代码使用input()捕获输入。按照提示输入5个数字,并用逗号分隔。input()根据输入的逗号,生成一个列表。 第3行代码输出列表numbers的内容。 第4行代码定义变量x的值为0。 第5行代码循环列表numbers。 第6行代码输出列表中第x+1个数字的值。 第7行代码,每次循环使变量x增1。 下面【例3-6】中的这段代码演示了else子句在while循环中的使用。当变量x的值大于0时,执行循环,否则输出变量x的值。 【例3-6.py】 # 带else子句的while循环 x = float(input("输入x的值:")) # 接收用户输入的数字并转换为float类型 i = 0 while(x != 0): # Python 3中的不等于不再使用,一律使用!= if(x >0): X-= 1 # if x is greater than 0, minus 1 else: X + = 1 # if x is less than 0, add 1 ii = I + 1 print ("% d cycle:% f"% (I, x)) else: print ("x equals 0:", x)
[code description]
Line 2 enters the value of the variable x.
Line 3 defines the variable I, which represents the number of cycles.
The fourth line of code gives the loop condition x! = 0. If x is not equal to 0, line 5 is executed; otherwise, the contents of the else clause are executed.
The fifth line of code determines whether the value of the variable x is greater than 0.
Line 6, if the value of x is greater than 0, subtract 1 for each loop.
The seventh line of code determines whether the value of the variable x is less than 0.
Line 8, if the value of x is less than 0, add 1 for each loop.
In line 9, each loop increases the value of the variable I by 1.
Line 11, the loop ends, and the else clause outputs the value of the variable x. The output (assuming the input number is 0): X equals 0:0.
When using loop statements, you should pay attention to the Boolean value of loop expressions to avoid endless loops. An endless cycle is a cycle in which the condition of the cycle is always true. For example:
I = 1 while I > 0: # I is always greater than 0 ii = I + 1 print (I)
This code is an endless loop, and the value of the variable I is always greater than 0.
2. For cycle
The for loop is used to iterate through a collection, accessing each item in the collection in turn. The format of the for loop is as follows.
For variable in collection:... Else: …
For... In... The execution of a loop: each loop takes a value from the collection and assigns that value to the variable. Collections can be tuples, lists, dictionaries, and other data structures. The else clause can be omitted.
Note: the else clause in the for loop is also part of the loop, and the else clause will be executed at the end of the last loop.
For... In... The loop is usually used with the range () function, which range () returns a list, for... In... Iterate through the elements in the list. The declaration of the range () function is as follows:
Class range (object) range (stop)-> range object range (start, stop [, step])-> range object
[code description]
Range () returns a range object, and the element value of the list is determined by three parameters: the parameter start represents the value at the beginning of the list, and the default value is 0; the parameter stop represents the value at the end of the list, which is indispensable; and the parameter setp represents the step size, that is, the value of each increment or decrease, and the default value is 1.
The code in the following [examples 3-7] iterates through the list generated by range (), filtering out positive, negative, and 0 numbers.
[example 3-7.py]
# for in statement for x in range (- 1,2): if x > 0: print ("positive:", x) elif x = 0: print ("zero:", x) else: print ("negative:", x) else: print ("end of loop")
[code description]
The second line of code iterates through the list generated by range (- 1). The three numbers returned by range (- 1, 0, 1) are-1, 0, and 1, respectively. At the end of each loop, the values of the variable x are-1, 0, and 1, respectively.
Line 3 determines whether the value of the variable x is greater than 0.
Line 4 outputs the value of a positive number. The output is "positive number: 1".
Line 5 determines whether the value of variable x is equal to 0.
Line 6 of the code, the output is "zero: 0".
Line 8 of the code that outputs the value of a negative number. The output is "negative number:-1".
Line 9 does not end the for loop, which ends after the execution of the else clause. The output is "negative number:-1".
In C and Java languages, for statements with the following structure are supported.
For (expression 1; expression 2; expression 3) statement block
Python does not support such for loops. If you need to write a loop with similar functionality, you can use a while loop. For example:
X = 0 while x < 5: print (x) xx = x + 2
The writing of while cycle is trivial and needs to be compared and judged. Therefore, you can also use a for loop with the help of the range () function. For example:
For x in range (0,5,2): print (x)
[code description]
The output number is in the range of [0p5), excluding 5. At the end of each cycle, the value of x is added by 2. Output result:
0 2 4
The traditional for loop is implemented in only two lines of code here. If you want to use a conditional expression as a condition for a loop, you can construct the range () function to implement it.
3. Break and continue statements
The break statement can make the program jump out of the loop statement, thus executing the program outside the loop body, that is, the break statement can end the loop ahead of time. For example, break statements are used to simulate the switch branch structure.
Operator = "+" x = 1 y = 2 for case in switch (operator): # switch can only be used for for... In... If case ('+'): print (x + y) break if case ('-'): print (x-y) break if case ('*'): print (x * y) break if case ('/'): print (x / y) break if case (): # default branch print ("")
[code description]
Break is used in line 7. When the value of the variable operator is "+", the expression x + y is executed, then the switch branch structure is broken, and the subsequent case branches are not executed. The output is 3. The later break has the same effect. When a case is matched, the program will jump out of the switch.
If the first case does not use the break clause, the program outputs two values, 3 and-1. Because the branch structure is not broken after the output expression x + y is executed, the program flows to the following case. Then continue to evaluate the value of the expression x-y, and exit the branch structure only when you encounter the following break statement. The break statement has a similar effect in the loop structure. This code in [example 3-8] looks for the value entered by the user from 0 to 99.
[example 3-8.py]
X = int (input ("enter the value of x:") y = 0 for y in range (0100): if x = = y: print ("find number:", x) break else: print ("not found")
[code description]
The first line of code captures the value entered by the user, converts it to an int type, and assigns it to the variable x.
Line 2 defines a variable y, which is used to temporarily store the values of the list that needs to be traversed.
Line 3 uses for... In... Loop through the list returned by range (0,100). The return value of range (0,100) is 0, 1, 2, … 、 99 .
Line 4 determines whether the entered value is equal to the value in the list. If the condition is true, output the number found and exit the loop immediately. When the loop ends, the subsequent else clause will not be executed.
Line 7, when the entered value is not found, the code after the else clause will be executed.
Note: break statements cannot be run outside the loop body or branch statements, otherwise the Python interpreter will prompt the following error.
SyntaxError: 'break' outside loop
The continue statement is also used to jump out of the loop, but unlike break, using the continue statement does not jump out of the entire loop body, but just jumps out of the current loop and continues to execute the rest of the loop.
X = 0 for i in [1, continue 2, 3, 4, 5]: if x = = I: continue x + = I print ("the value of x is", x)
[code description]
Line 1 assigns x to 0.
Line 2 uses for...in... Statement traverses the list [1, 2, 3, 4, 5].
Line 3 compares x to I, and if x is equal to the value I, execute the continue statement on line 4, stopping the current loop, that is, no longer executing line 5, and moving on to the next loop.
Line 6 prints out the final result, with an output of 12.
This is the end of "detailed explanation of Python Loop statement Code". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.