Skip to main content

Decision Making-Conditional Execution

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest way to do is to use a if statement.

In programming and scripting languages, conditional statements or conditional constructs are used to perform different computations or actions depending on whether a condition evaluates to true or false. (Please note that true and false are always written as True and False in Python.)

The condition usually uses comparisons and arithmetic expressions with variables. These expressions are evaluated to the Boolean values True or False. The statements for the decision taking are called conditional statements, alternatively they are also known as conditional expressions or conditional constructs. 

if condition:
            block of statements1
            block of statements2]


if condition:
            block of statements1
[elif condition:
            block of statements2
            block of statements3]
statements with in [] are optional

the condition after the if statement is evaluated and block of statements1 will be executed if the condition is true else block of statements2 will be executed.

conditions are specified with relational and logical operators which will return a Boolean value ( True or False).

Equality Operators             ==       !=         <>
Comparison Operators       <          <=       >          >=
Logical operators                 and     or        not


if x%2==0:
            print “number is even”
            print “number is odd”

if x>y:
            print “ x is greater than y”
elif x<y:
            print “x is smaller than y”
            print “x and y are equal”

You can also write nested if statements

if x==y:
            print “ x and y are equal”
if x<y:
                        print “x is smaller than y”
                        print “x is larger than y”

Unfortunately it is not as easy in real life as it is in Python to differentiate between true and false:
The following objects are evaluated by Python as False:
  • numerical zero values (0, 0L, 0.0, 0.0+0.0j),
  • the Boolean value False,
  • empty strings,
  • empty lists and empty tuples,
  • empty dictionaries.
  • plus the special value None.

All other values are considered to be True.

Sometimes, it is useful to have a body with no statements, in that case you can use pass
statement. Pass statement does nothing.

if condition:

Sample Programs ( All university questions)
1.Program to find the roots of a quadratic equation
import math
print "enter a b and c the coefficients"
if a==0:
    print "Not a quadratic eqtn..root is ", -c/b
    if d==0:
        print "only one root",-b/(2*a)
    elif d>0:
        print "roots are real"
        print "root1",-b+math.sqrt(d)/(2*a)
        print "root2",-b-math.sqrt(d)/(2*a)
        print "roots are imaginary"
2.Write a program that accepts the length of three sides of a triangle as input and determine whether or not the triangle is a right triangleprint "enter a b and c the three sides ( c is the hypotinous and c > a+b)"
if a+b > c and a+c >b and b+c >a:
    if a**2+b**2==c**2:
        print "Right angled triangle"
        print "Not a right angled triangle"
    print "given sides does not form a triangle"
3.Write a program to get the absolute value of a number without using the abs() function
n=input("enter a number....")
if n<0:
    print "absolute value=",-n

    print "absolute value=",n

Try the following program using if else or if elif statement
1)Compare two numbers
2)Check whether the given number is even or odd.
3)Find the biggest of 3 numbers
4)Read internal marks( out of 50) and external mark( out of 100) and print passed /failed in internal or external ( use KTU criteria..45%)
5)Check whether the given number is zero, positive or negative.
6)Find the roots of a quadratic equation ( ax^2+bx+c)
7)Read length of 3 sides and check whether it forms a triangle.
(All you have to do is use the Triangle Inequality Theorem, which states that the sum of two side lengths of a triangle is always greater than the third side. If this is true for all three combinations of added side lengths, then you will have a triangle.) 
8)Check the type of a triangle after reading the three sides ( scalene, isosceles, equilateral)
9) Check the type of a triangle after reading the three vertices ( scalene, isosceles, equilateral)
From the vertices length of the sides can be computed using the distance formulae.
A scalene triangle is a triangle that has three unequal sides.
An isosceles has two equal sides and two equal angles.
An equilateral triangle is a triangle with all three sides of equal length and also has three equal 60 degree angles.
10) Read  a mark ( out of 100) and print the corresponding grade.
 Percentage Range   Grade
            >=90                            O
            >=85 and <90            A+
>= 80 and <85           A                                
> =70 and <80           B+
> =60 and <70           B
> =50 and <60           C
>=45 and <50            P
<45                              F
11) answer = raw_input("Do you like Python? ")
if  the answer is "yes" print "That is great!" else print "That is disappointing!".
If the user input something else print “Enter yes/no”
12)Check whether a given year is Leap Year or not. A year is leap year if following conditions are satisfied

        1) Year is multiple of 400
        2) Year is multiple of 4 and not multiple of 100.

13)Write a program to check the quadrant of a given point(x,y)( University question)
14)Write a program to get the absolute value of a number without using the abs() function.(university question)
15)Write a program that accepts the length of three sides of a triangle as input and determine whether or not the triangle is a right triangle.( university question)
16)Given three points (x1,y1 ) ,(x2,y2) and (x3,y3), check whether they form a triangle.

Popular posts from this blog

Strings in Python

Strings are compound data type made of sequence of characters. Hence from the string, the individual charters can also be directly accessed. Strings are created by using single quotes or double quotes or triple quotes.
Example: >>>s1="Python Programming" >>>s2='Python Programs' >>>s3="""Python is a powerful Programming language"""
This will create a string object s1, s2 and s3 using different forms.
Individual characters can be accessed using different subscripts( +ve or –ve) with the string object.
Example >>>s="Python" >>>s[0] ‘P’ >>>s[2] ‘t’ >>>s[5] ‘n’ >>>s[-1] ‘n’ >>>s[-3] ‘h’ >>>s[-6] ‘P’
We can also slice a string. Segment of a string is called a slice.
>>>s[1:3] ‘yt’
If the first index is not mentioned, the slicing will start from 0. >>>s[:3] ‘Pyt’
>>>s[2:6] ‘thon’
If the last index is not mentioned, the slicing will go till the end o…

User Defined Functions in Python

So far we have only seen the functions which come with Python either in some file (module) or in interpreter itself (built in), but it is also possible for programmer to write their own function(s) and are called User Defined Functions. These functions can then be combined to form a module which can then be used in other programs by importing them.
In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition.
To define a function keyword def is used. After the keyword comes an identifier of the function, followed by parenthesized list of parameters and the colon which ends up the line. Next follows the block of statement(s) that are the part of function. A block is one or more lines of code, grouped together so that they are treated as one big sequence of statements while executing. In Python, statements in a block are written with indentation. Usually, a block begins when a li…

Files in Python , Exception handling

While a program is running, its data is in main memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a secondary storage device(hard disk, pen drive, DVD,CD etc). When there are a large number of files, they are often organized into directories (also called “folders”). Each file is identified by a unique name, or a combination of a file name and a directory name. By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to open it. When you’re done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well. To open a fil…