12.Selection statement if-else , if elif,match case example programs

Python code Indentation

Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python, however, uses indentation.
A code block (body of a  function,  loop, etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.

Generally, four whitespaces are used for indentation and are preferred over tabs.

Conditional Statement- if-else

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.

Simple if statement
if condition:
     block of statements1

if-else statement
if condition:
     block of statements1
else:
    block of statements2

if-else if statement
if condition:
      block of statements1
elif condition:
      block of statements2
else:
     block of statements3

Note that the block of statements are indented on the same column.

The condition specified 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).




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.
the special value None.

All other values are considered to be True.

Example Programs
Check whether a number is even or odd

x=int(input("Enter a number...:"))
if x%2==0:
     print("number is even")
else:
    print("number is odd")

Compare two numbers

x=int(input("Enter first number.."))
y=int(input("Enter second number.."))
if x>y:
     print(f"{x} is greater than {y}")
elif x<y:
     print (f"{x} is smaller than {y}")
else:
     print (f"{x} and {y} are equal")

We can also write nested if statements
x=int(input("Enter first number.."))
y=int(input("Enter second number.."))
if x>y:
     print(f"{x} is greater than {y}")
else:
    if x<y:
        print (f"{x} is smaller than {y}")
    else:
        print (f"{x} and {y} are equal")
Program to find the roots of a quadratic equation ( university question)
import math
print("enter a b and c the coefficients line by line")
a=int(input())
b=int(input())
c=int(input())
if a==0:
    print("Not a quadratic eqtn..root is ", -c/b)
else:
    d=b*b-4*a*c
    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))
    else:
       print("roots are imaginary")
We can also find the complex root using cmath module
import math,cmath
print("enter a b and c the coefficients line by line")
a=int(input())
b=int(input())
c=int(input())
if a==0:
    print("Not a quadratic eqtn..root is ", -c/b)
else:
    d=b*b-4*a*c
    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))
    else:
       print("roots are imaginary")
       print("root1",-b+cmath.sqrt(d)/(2*a))
       print("root2",-b-cmath.sqrt(d)/(2*a))
Output
enter a b and c the coefficients line by line
1
2
3
roots are imaginary
root1 (-2+1.4142135623730951j)
root2 (-2-1.4142135623730951j)
Program that accepts the length of three sides of a triangle as input and determine whether or not the triangle is a right angled triangle
a=int(input("enter side a..:"))
b=int(input("enter side b..:"))
c=int(input("enter side c..:"))
if a+b>c and a+c>b and b+c>a:
    if a**2+b**2==c**2:
       print("Right angled triangle")
    else:
       print("Not a right angled triangle")
else:
   print("given sides does not form a triangle")

Input a point and find the quadrant
x=int(input("Enter x:"))
y=int(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")
else:
   print("point at origin")

Write a Python code to check whether a given year is a leap year or not 
A leap year is a year, which is different than a normal year having 366 days instead of 365.
A leap year comes once in four years, in which February month has 29 days. With this additional day in February, a year becomes a Leap year.
Some leap years examples are - 1600, 1988, 1992, 1996, and 2000.

Below conditions are used to check that year is a leap year or not.
Year must be divisible by 4
Year is divisible by 400 and not divisible by 100.

year=int(input('Enter the year:'))
if (year%4==0)and(year%400==0 or year%100 !=0):
    print(year , 'is a Leap Year')
else:
    print(year,'is Not a Leap Year')

Assignment in if
signal='red'
action ='go' if signal=='green'  else 'stop'
print(action)

output:
stop

match case statement in python 3.10
match  case statement is similar to switch case statement C programming. Multiple if else statement(if elif ladder) can be replaced with match case statement in Python 3.10.Note that this statement is not available in older versions.

match statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it’s more similar to pattern matching in languages like Rust or Haskell. Only the first pattern that matches gets executed and it can also extract components (sequence elements or object attributes) from the value into variables.

The simplest form compares a subject value against one or more literals:
n=int(input('Enter a  day number'))
match n:
     case 1:
          print("Sunday")
    case 2:
         print("Monday")
    case 3:
          print("Tuesday")
    case 4:
         print("Wednesday")
   case 5:
         print("Thursday")
   case 6:
          print("Friday")
   case 7:
         print("Saturday")
    case _:
            print("invalid day number")

Note: it has got many more advanced  matching features than the switch statement in C.

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

46.Classes and Objects in Python- Accessors and mutators