Featured

    Featured Posts

Python Tutorial 7:Conditional Statement In Python


Conditional Statement In Python

 §  If for some reason you want to interrupt this flow and execute certain statements, only, if certain condition is met, then we use conditional statements.

 §  Conditional expressions, involving keywords such as if, elif, and else, provide Python programs with the ability to perform different actions depending on a Boolean condition: True or False.



 §  When you want to justify one condition while the other condition is not true, then you use "if statement".

   if statement
 §  This is the simplest decision-making statement in Python. It is used to decide if a particular block of code needs to be executed or not. Whenever the given condition is True, then the block of code inside it gets executed, else it does not. 

The syntax for if statement:

if condition:
    body
§  The if statements check the condition. If it evaluates to True, it executes the body of the if statement. If it evaluates to False, it skips the body.

 if else statement

 §  The statements written within the else block get executed whenever the if condition is False. You can imagine the flow of execution this way,
Syntax:
if condition:
      body
else:
    body

Example

if True:

    print "It is true!"

else:

    print "This won't get printed.."

# Output: It is true!

if False:

    print "This won't get printed.."

else:

    print "It is false!"

# Output: It is false!


In Python you can define a series of conditionals using if for the first one, elif for the rest, up until the final (optional) else for anything not caught by the other conditionals.



Syntax:

if expression-1

 Statement-1



elif expression-2

 Statement-2

elif expression-3

 Statement-3




v Write a python program to enter number from 1 to 9 and print in words. If user enter number apart from 1 to 9 then it will print 'Number is allowed only between 0-9

n=int(input('enter number'))

if n==1:

    print("One")

elif n==2:

    print("Two")

elif n==3:

    print("Three")

elif n==4:

    print("Four")

elif n==5:

    print("Five")

elif n==6:

    print("Six")

elif n==7:

    print("Seven")

elif n==8:

    print("Eight")

elif n==9:

    print("Nine")

else:

    print('Number is allowed only between 0-9')

Boolean Logic Expressions

 §  Boolean logic expressions, in addition to evaluating to True or False, return the value that was interpreted as True or False. It is Pythonic way to represent logic that might otherwise require an if-else test.


And operator

 §  The and operator evaluates all expressions and returns the last expression if all expressions evaluate to True. Otherwise it returns the first value that evaluates to False:

print(10 and 20)      #output will be 20

print(10 and 0)        #output will be 0

print(0 and 10)        #output will be 0

print(10 and 20 and 30) #output will be 30

print(10 and "Python")  #output will be python

print(0 and "python")   #output will be 0

print("python" and 10)  #output will be 10

print("" and "python")  #output will be “ ”

print(" " and"python")  #output will be python

Or operator

 §  The or operator evaluates the expressions left to right and returns the first value that evaluates to True or the last value (if none are True).      

print(10 or 20)#output will be 10

print(10 or 0)#output will be 10

print(0 or 10)#output will be 10

print(10 or 20 or 30)#output will be 10

print(10 or "Python")#output will be 10

print(0 or "python")#output will be python

print("python" or 10)#output will be python

print("" or "python")#output will be

print(" " or "python")#output will be

print(None or 1)#output will be 1

print(0 or [])#output will be []



Testing for multiple conditions

 §  A common mistake when checking for multiple conditions is to apply the logic incorrectly.

 §  trying to check if two variables are each greater than 2.

 §  If you write the statement in such way

if (a) and (b > 2)

 §  this gives an unexpected result because bool(a) evaluates as True when a is not zero.
    
a=int(input('enter first number'))
b=int(input('enter first number'))
if a and b>2:
    print("Yes")
else:
    print("No")


 § Each variable needs to be compared separately.

a=int(input('enter first number'))

b=int(input('enter first number'))

if a>2 and b>2:

    print("Yes")

else:

    print("No")

 §  Another, similar, mistake is made when checking if a variable is one of multiple values. The statement in this example is evaluated as - if (a == 3) or (4) or (6). This produces an unexpected result because bool (4) and bool(6) each evaluate to True

a=1

if a==3 or 4 or 5 or 6:

    print('Yes')

else:

    print('No')



#output will be Yes

 §  Again each comparison must be made separately

a=1

if a==3 or a==4 or a==5 or a==6:

    print('Yes')

else:

    print('No')

#output will be No


 §  Using the in operator is the canonical way to write this.

n=int(input('enter number'))

if n in(10,20,30):

    print('Yes')

else:

    print('No')

Program to Check Whether a Number is Prime or Not

v What us Prime Number

 §  If a whole number greater than 1, is divisible by the 1 and itself then it is known as Prime Number.

 §  A prime number is a number which is divisible by only two numbers: 1 and itself. So, if any number is divisible by any other number, it is not a prime number.

Different View of the Logic

 §  The number cannot divisible by any number between 2 to n-1


Example-1:

import java.util.Scanner;

public class PrimeNumber {



     static boolean isPrime(int n) {

              boolean flag = false;

              if(n>1) {

              for(int i=2;i<=n-1;i++) {

            // condition for nonprime number

                        if(n%i==0) {

                                  flag=true;

                                  break;

                        }

              }

              }

              if(!flag)

                        return true;

              else

                        return false;

     }

     public static void main(String[] args) {

              // TODO Auto-generated method stub

    Scanner sc=new Scanner(System.in);

    System.out.println("Enter number");

    int num=sc.nextInt();

    boolean res=isPrime(num);

    if (res)

        System.out.println(num + " is a prime number.");

    else

        System.out.println(num + " is not a prime number.");

     }

}



Example-2:

§  The number can’t divisible by any number between 2 to n/2.

import java.util.Scanner;

public class PrimeNumber {

          static boolean isPrime(int n) {

                    boolean flag = false;

                             int i=2;

                  while(i <= n/2)

                  {

                      // condition for nonprime number

                      if(n% i == 0)

                      {

                          flag = true;

                          break;

                      }



                      ++i;

                  }



                  if (!flag)

                      return true;

                  else

                      return false;

              }

         

                   public static void main(String[] args) {

                   // TODO Auto-generated method s*- nhgtub

    Scanner sc=new Scanner(System.in);

    System.out.println("Enter number");

    int num=sc.nextInt();

    boolean res=isPrime(num);

    if (res)

        System.out.println(num + " is a prime number.");

    else

        System.out.println(num + " is not a prime number.");



          }

}

Example-3:

§  The number can’t divisible by any number between 2 to sqrt(n)

import java.util.Scanner;



public class PrimeNumber {



          static boolean isPrime(int n) {

                    boolean flag = false;

                             int i=2;

                  while(i <= Math.sqrt(n))

                  {

                      // condition for nonprime number

                      if(n% i == 0)

                      {

                          flag = true;

                          break;

                      }



                      ++i;

                  }



                  if (!flag)

                      return true;

                  else

                      return false;

              }

         

                   public static void main(String[] args) {

                   // TODO Auto-generated method stub

    Scanner sc=new Scanner(System.in);

    System.out.println("Enter number");

    int num=sc.nextInt();

    boolean res=isPrime(num);

    if (res)

        System.out.println(num + " is a prime number.");

    else

        System.out.println(num + " is not a prime number.");



          }

}

Example-4:

§  A number which having only two factors is known as prime number

for e.g.: -

3 having two factor 1 ,3 so 3 is a prime number

6 having more than two factor 1,2,3,6 so 6 is not a prime number.

import java.util.Scanner;



public class PrimeNumber {



          static int factorCount(int n) {

                   int count=0;

                   for(int i=1;i<=n;i++) {

                             if(n%i==0)

                                      count++;

                   }

                   return count;

          }

          static boolean isPrime(int n) {

                   int c=factorCount(n);

                   if(c==2)

                             return true;

                   else

                             return false;

                            

          }

          public static void main(String[] args) {

                   // TODO Auto-generated method stub

Scanner sc=new Scanner(System.in);

System.out.println("Enter number");

int n=sc.nextInt();

boolean res=isPrime(n);

if(res==true)

          System.out.println(n+" is a Prime Number!");

else

          System.out.println(n+" is not a Prime Number!");

          }



}


www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews