Python - SPLessons

Python Control Statements

Home > Lesson > Chapter 9
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Python Control Statements

Python Control Statements

shape Description

Computers are great at crunching piles of data, and piles of data usually take the form of sequences, streams, tables and so on. Such data sets usually need to be iterated over. At the very least, some statements may need to be executed more than once. Loops in C and iteration statements are used for this purpose. The following are the basic loops available in every programming languages.

For loop

shape Description

For loop consists of statements which can be executed until the condition becomes false. The following is the syntax. [c]for <variable> in <sequence>: [/c] The following is the flow pattern of the for loop. The following is an example. [c]num=5 for a in range (1,10): print num * a [/c] Now compile the code result will be as follows. [c] 5 10 15 20 25 30 35 40 45 [/c]

While loop

shape Description

While loop checks the condition until it becomes true. If the condition is false, the flow control comes out of while loop. The following is the syntax. [c] while <expression>: Body [/c] The following is the flow pattern of the while loop. The following is an example. [c]a=15 while a>0: print "Value of a is",a a=a-5 [/c] Now compile the code result will be as follows. [c] Value of a is 15 Value of a is 10 Value of a is 5[/c]

If else

shape Description

If statement is used to return the true value, following is the conceptual figure which can guide simply. In the following figure if condition is true then it goes for action otherwise it checks for the alternative action finally code will be closed. The following is the syntax. [c] if(condition): False statements else: True statements [/c] The following is the flow pattern of the if else loop. The following is an example. [c]year=2000 if year%400==0: print "It is a leap year" else: print "It is not a leap year" [/c] Now compile the code result will be as follows. [c]It is a leap year[/c]

Break Statement

shape Description

The break proclamation is a bounce explanation that is utilized to pass the control to the end of the circle. At the point when break explanation is connected the control focuses to the line taking after the body of the circle , subsequently applying break proclamation makes the circle to end and controls goes to next line indicating after circle body. The following is an example. [c]for i in [1,2,3,4,5]: if i==4: print "Element found" break print i, [/c] Now compile the code result will be as follows. [c]1,2,3 Element found[/c]

Summary

shape Key Points

  • Loops performs repeated execution to make a condition become true.
  • The for loop initializes variables, checks condition and increments/decrements. This can be used when there is sequential input/output.
  • The while loop executes after the condition becomes true.