In our previous post the programs we’ve written have had a simple, sequential flow: each statement is executed once, in order, every time. If you were limited to just this type of programming, it would be very difficult, if not impossible, to write complex applications. Now we'll see how to selectively execute certain portions of our code and repeat parts of your program, how to make our program smarter, capable of making choices and decisions. Specifically, we’ll be looking at the if statements, for loop and while loop. These are known as control flow tools; they control the flow of the program.
Conditional execution
a) Boolean expressions
A boolean expression is an expression that is either true or false. All control flow tools involve evaluating a condition statement. The program will proceed differently depending on whether the condition is met. The most common condition statement is the comparison statement. If we want to
compare whether two variables are the same, we use the == operator (double =).
For instance, if you write x == y, you are asking the program to check if the value of x is equal to the value of y. If they are equal, the condition is met and the statement will evaluate to True. Else, the statement will evaluate to False.
Other comparison operators include != (not equal), < (smaller than), > (greater than), <= (smaller than or equal to) and >= (greater than or equal to). The list below shows how these signs can be used and gives examples of statements that will evaluate to True.
Here I'd like to clarify that True and False are special values that belong to the class bool; they are not
strings. Try this in your prompt and see the result -
>>> type(True)
>>> type(False)
Let us summarize the comparison operators -
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x is the same as y
x is not y # x is not the same as y
Note: = is an assignment operator and == is a comparison operator. There is no such thing as =< or =>.
b. Logical operators
In python there are three logical operators: and, or, and not. The semantics (meaning) of
these operators is similar to their meaning in English.
For Example: If x =20, y =15, now
1. x > 0 and x < 10 is true only if x is greater than 0 and less than 10. Hence in our case it is True
2. x%2 == 0 or x%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3. In our case it is True
3. when we say not x>y, the not operator negates a boolean expression, so not (x > y) is true if x > y is false; that is, if x is less than or equal to y. In our case again this is True.
c. Conditional statements
Conditional statements also known as control statements transform the program from being just a list of instructions to something that can make decisions on the fly based on the information that it receives. It would be useful to be able to tell the program to perform different actions according to whether certain conditions are satisfied.
So control statements are nothing but a series of statements that a program follows to get the desired
results. Let's first try to understand what are control statements and why they form an essential part of any programming language. You might have used the ATM machine to withdraw money. What do you do when you insert your debit card? The very first thing you watch on the screen are the options to chose from the menu. Now you have to perform certain actions, else your card would be turned away after some time, in case you keep the computer waiting for a long time. When you choose to withdraw, you have to provide the correct amount, which is required to be withdrawn from the machine. If you provide the wrong amount, the computer will immediately give the message "Please enter the correct amount". What happened here? Did you notice? Here computer is merely following
instructions. It has been ordered to accept only the correct amount and prompt an error message on input of the wrong amount. This is one such scenario where you can see the use of control statements.
The if statement:
The simplest form is the if statement:
if one condition is true:
then perform one set of actions;
if another condition is true:
then perform another set of actions.
Each if-then pair is a conditional statement. Before we get into that, let’s look at how to specify
conditions.
Values can be compared using the following comparison operators:
• <: Less than
• <=: Less than or equal
• >: Greater than
• >=: Greater than or equal
• ==: Equal
• !=: Not equal
These affect the fundamental data types in different ways, each time giving us an answer of True or False. Operands are the bits of data on the left and right of the operator in an expression. The operands on either side of the comparison operator must be of types that can be compared. The operands and the comparison operator together are a conditional expression.
Python might not throw an error if you compare illogical types, so it is a good idea to test your
conditional expressions thoroughly and check the data that goes into them.
See the program below and it's output.
The if...else statement :
The next control statement is if...else :
if condition :
statements-1
else:
statements-2
Lets see a simple program which will check whether the input was an odd number or an even number.
If we enter 15 then the output is as shown below-
The program first takes input from the user, then converts the input into an integer (why this was required?) and then using the if...else construct it prints the entered number as odd or even.
The if...elif...else statement
If there are a series of actions to be executed, then the if...elif...else block can be used. Most of the programming languages provide the if...else if...else control block, while Python has shortened else if to elif but the principle remains the same, that is, it divides the complete control block into number of blocks for specific action to be executed.
if condition-1:
sequence of statements-1
elif condition-n:
sequence of statements-n
else:
default sequence of statements
The following program explains the concept-
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
Inline if
An inline if statement is a simpler form of an if statement and is more convenient if you only need to perform a simple task. The syntax is:
do Task A if condition is True else do Task B
For instance,
num1 = 11 if userInput=="1" else 12
This statement assigns 11 to num1 (Task A) if userInput equals to “1”. Else it assigns 12 to num1 (Task B).
Another example is-
print ("This is task A" if userInput == "1" else "This is task B")
This statement prints "This is task A" (Task A) if userInput equals “1”. Else it prints "This is task B" (Task B).
Depending up on the values of x and y the print statement of if condition was printed. Try to make some simple programs to have a better understanding of these control statements. In the next post we'll discuss about Loops in Python.
Conditional execution
a) Boolean expressions
A boolean expression is an expression that is either true or false. All control flow tools involve evaluating a condition statement. The program will proceed differently depending on whether the condition is met. The most common condition statement is the comparison statement. If we want to
compare whether two variables are the same, we use the == operator (double =).
For instance, if you write x == y, you are asking the program to check if the value of x is equal to the value of y. If they are equal, the condition is met and the statement will evaluate to True. Else, the statement will evaluate to False.
Other comparison operators include != (not equal), < (smaller than), > (greater than), <= (smaller than or equal to) and >= (greater than or equal to). The list below shows how these signs can be used and gives examples of statements that will evaluate to True.
Here I'd like to clarify that True and False are special values that belong to the class bool; they are not
strings. Try this in your prompt and see the result -
>>> type(True)
>>> type(False)
Let us summarize the comparison operators -
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x is the same as y
x is not y # x is not the same as y
Note: = is an assignment operator and == is a comparison operator. There is no such thing as =< or =>.
b. Logical operators
In python there are three logical operators: and, or, and not. The semantics (meaning) of
these operators is similar to their meaning in English.
For Example: If x =20, y =15, now
1. x > 0 and x < 10 is true only if x is greater than 0 and less than 10. Hence in our case it is True
2. x%2 == 0 or x%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3. In our case it is True
3. when we say not x>y, the not operator negates a boolean expression, so not (x > y) is true if x > y is false; that is, if x is less than or equal to y. In our case again this is True.
c. Conditional statements
Conditional statements also known as control statements transform the program from being just a list of instructions to something that can make decisions on the fly based on the information that it receives. It would be useful to be able to tell the program to perform different actions according to whether certain conditions are satisfied.
So control statements are nothing but a series of statements that a program follows to get the desired
results. Let's first try to understand what are control statements and why they form an essential part of any programming language. You might have used the ATM machine to withdraw money. What do you do when you insert your debit card? The very first thing you watch on the screen are the options to chose from the menu. Now you have to perform certain actions, else your card would be turned away after some time, in case you keep the computer waiting for a long time. When you choose to withdraw, you have to provide the correct amount, which is required to be withdrawn from the machine. If you provide the wrong amount, the computer will immediately give the message "Please enter the correct amount". What happened here? Did you notice? Here computer is merely following
instructions. It has been ordered to accept only the correct amount and prompt an error message on input of the wrong amount. This is one such scenario where you can see the use of control statements.
The if statement:
The simplest form is the if statement:
if one condition is true:
then perform one set of actions;
if another condition is true:
then perform another set of actions.
Each if-then pair is a conditional statement. Before we get into that, let’s look at how to specify
conditions.
Values can be compared using the following comparison operators:
• <: Less than
• <=: Less than or equal
• >: Greater than
• >=: Greater than or equal
• ==: Equal
• !=: Not equal
These affect the fundamental data types in different ways, each time giving us an answer of True or False. Operands are the bits of data on the left and right of the operator in an expression. The operands on either side of the comparison operator must be of types that can be compared. The operands and the comparison operator together are a conditional expression.
Python might not throw an error if you compare illogical types, so it is a good idea to test your
conditional expressions thoroughly and check the data that goes into them.
See the program below and it's output.
The if...else statement :
The next control statement is if...else :
if condition :
statements-1
else:
statements-2
Lets see a simple program which will check whether the input was an odd number or an even number.
If we enter 15 then the output is as shown below-
The program first takes input from the user, then converts the input into an integer (why this was required?) and then using the if...else construct it prints the entered number as odd or even.
The if...elif...else statement
If there are a series of actions to be executed, then the if...elif...else block can be used. Most of the programming languages provide the if...else if...else control block, while Python has shortened else if to elif but the principle remains the same, that is, it divides the complete control block into number of blocks for specific action to be executed.
if condition-1:
sequence of statements-1
elif condition-n:
sequence of statements-n
else:
default sequence of statements
The following program explains the concept-
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
Inline if
An inline if statement is a simpler form of an if statement and is more convenient if you only need to perform a simple task. The syntax is:
do Task A if condition is True else do Task B
For instance,
num1 = 11 if userInput=="1" else 12
This statement assigns 11 to num1 (Task A) if userInput equals to “1”. Else it assigns 12 to num1 (Task B).
Another example is-
print ("This is task A" if userInput == "1" else "This is task B")
This statement prints "This is task A" (Task A) if userInput equals “1”. Else it prints "This is task B" (Task B).
Depending up on the values of x and y the print statement of if condition was printed. Try to make some simple programs to have a better understanding of these control statements. In the next post we'll discuss about Loops in Python.
0 comments:
Post a Comment