Python(Page 5)

 12345678910

Page-5

Flow of control

We know that statements in a python program are executed one by one in the order they are written. This order of the program is known as the flow of control. 

This flow of control can be implemented using control structures. Python provided two types of control structures -

1. Selection

2. Repetition

Selection 


In python, the selection is achieved by decision-making. We use if...else statements in our program for the purpose of decisions making.

Syntax-

if condition:

    Statement (s) 


Here, the condition tells the interpreter if the statements following the "if condition" (indented statement(s)) is to be executed or not. If the condition is true, statement (s) will be executed otherwise not. 

Check out the below example, 

age = int(input("Enter your age "))

if age >= 18:

 print("Eligible to vote")


Here, in the first line, the user enters the age that is converted into an integer by int() function. This value is saved in the age variable. In the next line, the value in age is checked if it is more than or equal to 18. if found true, the next statement i.e. print("Eligible to vote") is executed otherwise it is not executed. 


if...else Statement-

age = int(input("Enter your age "))

if age >= 18:

 print("Eligible to vote")

else

  print("Not Eligible to vote")


We can also use "else" statement. When the condition written in "if" goes false, the control goes in the else. So, if the value in the "age" variable is less than 18, we get "Not Eligible to vote" as output. 


if...elif( if else if ) Statement-

Sometimes, we need to use more than one conditions in our program. So, we can  use chain of "if.. else" statements, called if...elif(if else if).

Syntax-


if condition:

statement(s)

elif condition:

statement(s)

elif condition:

statement(s)

else:

statement(s)

Example-Program to check if a number is positive, negative or zero

Example 2- Program to check whether a number is even or odd



Indentation

Whenever we need to create a block of statements in python, we leave a white space or tab before the respective statement, it is called indentation. 

For example-

if age>=18:

    print("Voter is Eligible")

print("Thank you")

Here, we can see that the first print statement is written leaving some space in the same line. It means the print statement is creating a block with "if" condition. But, another print statement is written without any indentation, which means it is out of "if block".


 12345678910



No comments:

Post a Comment