Home | | Problem Solving and Python Programming | Conditionals - Python

# Conditionals - Python

Conditional statements give us the ability to check conditions and change the behavior of the program accordingly.

Conditionals

## Modulus operator

The modulus operator works on integers and yields the remainder when the first operand is divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the same as for other operators:

>>>        quotient = 7 / 3

>>>        print quotient

2

>>>        remainder = 7 % 3

>>>        print remainder

1

So 7 divided by 3 is 2 with 1 left over.

The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y.

Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.

## Boolean expressions

A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise:

>>>        5 == 5

True

>>>        5 == 6

False

True and False are special values that belong to the type bool; they are not strings:

>>>        type(True)

<type 'bool'>

>>>        type(False)

<type 'bool'>

The == operator is one of the relational operators; the others are:

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

## Logical operators

There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.

Finally, 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. The operands of the logical operators should be boolean expressions. Any nonzero number is interpreted as “true.”

>>>        17 and True

True

### Keyboard input

Python 2 provides a built-in function called raw_input that gets input from the keyboard.

In Python 3, it is called input.

>>>        text = raw_input() What are you waiting for?

>>>        print text

What are you waiting for?

Arthur, King of the Britons!

>>>        print name

Arthur, King of the Britons!

The sequence \n at the end of the prompt represents a newline, which is a special character that causes a line break.

>>>        x = int(input("Please enter an integer: "))

>>>        Please enter an integer: 42

## Conditional statement (if)

Conditional statements give us the ability to check conditions and change the behavior of the program accordingly. The syntax for if statement:

Eg:

num = 3

if num > 0:

print(num, "is a positive number.")

print("This is always printed.")

num = -1

if num > 0:

print(num, "is a positive number.")

print("This is also always printed.")

The boolean expression after if is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens.

## Alternative execution (if… else)

A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this:

if <test_expression>:

<body_1>

else:

<body_2>

Eg:

>>>        Program checks if the number is positive or negative num = 3

if num >= 0: print("Positive or Zero")

else:

print("Negative number")

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed.

## Chained conditionals

Sometimes there are more than two possibilities and we need more than two branches.

The syntax looks like this:

if <test_expression_1>:

<body1>

elif <test_expression_2>:

<body2>

elif <test_expression_3>:

<body3>

….

…..

else:

<bodyN>

Eg:

#In this program,

#we check if the number is positive or

#negative or zero and

#display an appropriate message

num = 3.4

#Try these two variations as well:

#num = 0

#num = -4.5

if num > 0:

print("Positive number")

elif num == 0:

print("Zero")

else:

print("Negative number")

elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

if choice == 'a':

draw_a()

elif choice == 'b':

draw_b()

elif choice == 'c':

draw_c()

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

## Nested conditionals

One conditional can also be nested within another. We could have written the trichotomy example like this:

#In this program, we input a number

#check if the number is positive or

#negative or zero and display

#an appropriate message

#This time we use nested if

num = float(input("Enter a number: "))

if num >= 0:

if num == 0:

print("Zero")

else:

print("Positive number")

else:

print("Negative number")

The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.

Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly.

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:

if 0 < x:

if x < 10:

print 'x is a positive single-digit number.'

The print statement is executed only if we make it past both conditionals, so we can get the same effect with the and operator:

if 0 < x and x < 10:

print 'x is a positive single-digit number.'

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Control Flow, Functions : Conditionals - Python |