So far you studied simple statements in Python. A simple statement consisted of one single statement which had no logic control relation to other statements before or after that statement. Simple statements are stand alone statements which are syntactically correct to use individually. When your program consists of only simple statements, the interpreter runs the statements one at a time in a sequence and once all the simple statements are executed, the program exits. However, you can change this sequential pattern of execution using Control Statements.

Control Statements

Control Statements provide mechanisms to control the execution of a program based on certain conditions and thereby deviate from the sequential order. Python provides conditional if statement and loop structures - while and for as part of Control Statements.

Control Statements become part of a compound statement and should all be executed together based on the control statement's conditional result.

Compound Statement

A compound statement contain groups of statements which all go together to form the compound statement. They span multiple lines and will generally have indentation which marks the groups to be executed as one block together. Although you may write a compound statement without indentation, it is recommended to use indentation. When you do use the indentation, Python is strict about the number of indents you use relative to its predecessor statement. If you do not indent correctly you get IndentationError

Conditional if statement

A very common conditional that is used in almost all programming languages is an if statement.

Before you proceed further on if let us understand the relational and logical operators available which are used in if and while statements.

The following are the relational operators in Python which all evaluates to True or False based on the expression. The two operands 9 and 8 shown below can be replaced by any expression consisting of one or more variables.

Operator name Notation Example Result
Greater than > 9 > 8 True
Less than < 9 < 8 False
Greater than or equal to >= 9 >= 8 True
Less than or equal to <= 9 <= 8 False
Equal to == 9 == 8 False
Not equal to != 9 != 8 True

The following are the logical operators in Python

Operator name Notation Example Result Comment
logical AND and
9>8 and 5>4
True Returns True if both expressions on either side of and evaluate to True. This operator evaluates the second expression only if the first expression evaluates to True
logical OR or 8>9 or 5>4 True Returns True if either one of the expressions on either side of or evaluate to True. This operator evaluates the second expression only if the first expression evaluates to False
logical NOT not not 9>8 False Reverses the value of the Boolean expression

If Conditional Flowchart

The following flowchart depicts the control flow of the program based on the result of the boolean expression

x % 2 == 0

If 'x' is an even number then the x % 2 == 0 return True, in which case the program enters the block of code which prints out 'You input an even number' and then 'Good bye'. If the conditional evaluates to False, then the program skips the block of code which prints 'You input an even number' and outputs only the 'Good bye'. So the program instead of going in a sequential order, takes a deviation based on a conditional expression.

image alt text

The if Statement:

if (conditional expression which evaluates to True, False or any other literal value) :

_conditional expression is made up of one or more logical and relational expressions including combinations of both types which, on the whole, evaluates to True or False.

Note: You can also use arithmetic expressions or variables which evaluate to any literal value. If the expression evaluates to None or '0' then it is treated as False. Any other literal value is considered True_

A colon ':' should follow immediately after the conditional expression. If the conditional expression evaluates to True, then the program of execution starts from the indented statements after the : If the conditional evaluates to False then the program of execution skips the indented block after : and executes the statements after the if block.

The code for the above flowchart


x = int(input())
if(x%2 == 0):
  print("You input event number")
print("statement after the if block")

The if...else Statement:

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

The syntax of an if...else is:

if (boolean_expression) :
  //Executes when the Boolean expression is true
else :
  //Executes when the Boolean expression is false

Run the above code and input an even and odd number and study how the if or else block gets executed based on boolean expression evaluation. The same execution can be visualized with the flow chart below.

image alt text

else is optional in an if statement.

The if...elif...else Statement:

An if - else statement can be followed by an optional elif...else statements. When using if , elif , else statements there are few points to keep in mind.

  • An if can have zero or one else and it must come after any if's.
  • An if can have zero to many elif's and they must come before the final else.
  • Once an elif succeeds, none of the remaining elif's or the final else's will be tested.

Now let us take a grading calculation as an example below to use the if- elif-else operators:

score = int(input("Please enter your score: "))
if score > 90:
    print("Congratulations! you scored an 'A' grade")
elif score > 80:
    print("Congratulations! you scored a 'B' grade")
elif score > 70:
    print("Congratulations you scored a 'C' grade")
else:
    print("Sorry you failed.")

In the above program, you first get the input from the user, and then evaluate the first conditional if (score > 90) which is of the form

if (conditional expression which evaluates to True or False) :

If the conditional expression evaluates to True, then the program of execution starts from the indented statements after the : If the conditional evaluates to False then the program of execution skips the indented block after : and proceeds to elif statement and checks for conditional again. The same logic is applied on all other conditionals all the way till the else statement. The last else statement is executed if all conditionals expression above evaluated to False.

Question

In the above conditional is it important to keep the first conditional as score > 90? If you change the order and instead have score > 70 as the first conditional, then will it still provide the desired functionality? Why or Why not?

Short Hand If Notation

If you have only one statement to execute, you can put it on the one line.


a = 3
b = 2
if b > a: print("b is greater than a")

Short Hand If-Else

Similarly, if you have only one statement to execute, one for if, and one for else, you can put it all on one line.

a = 3
b = 2
print (a) if b > a else print(b)

Note there are no colon's used in these notations and this only works when the conditional has to execute just one line of code based on the conditional

Short Hand Multiple if-else

a = 3
b = 3
print(a) if a > b else print('equals') if a == b else print(b)

results matching ""

    No results matching ""