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
Check whether a number is even or odd
x=input("Enter a number.")
if x%2==0:
     print “number is even”
    print “number is odd”
Compare two numbers
x=input("Enter first number..")
y=input("Enter second number..")
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 hypotenuses and c > a+b)"a=input()
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
4.Input a point and find the quadrant
x=input("Enter x:")
y=input("enter y:")
if x>0 and y >0:
   print "first quadrant"
elif x<0 and y >0:
   print "second quadrant"
elif x<0 and y <0:
   print "third quadrant"
elif x>0 and y <0:
   print "fourth quadrant"
   print "point at origin"

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.


  1. Great presentation of Python form of blog and Python tutorial. Very helpful for beginners like us to understand Python course. if you're interested to have an insight on Python training do watch this amazing tutorial.


  2. Top 10 hot technologies of 2019 to make a good career in the upcoming year:


Post a Comment

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.
>>>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.
We can also slice a string. Segment of a string is called a slice.
If the first index is not mentioned, the slicing will start from 0.
If the last index is not mentioned, the …

Classes and Objects in Python

Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. The basic components of object oriented programming are classes and objects. A Class is a blue print to create an object. It provides the definition of basic attributes and functions of objects. Object is a running instance of the class having the identity(name), properties( values) and behaviors(functions). The Object oriented program thus consist of object definitions (classes) and most of the computations and functions are mentioned as operations on the object. Each object definition corresponds to some object or concept in the real world, and the functions that operate on these object correspond to the ways real-world objects interact. We have learned objects of string, list, tuple etc…and used the properties and functionalities of these objects which are built into the Python. Now we are going to create our own(user defined) objects. The class provides basic…

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…