Pal-Prime Number

 /*

Write a program to create following methods:

i. boolean palindrome(int n), which returns true if n is a palindrome otherwise returns false.

ii. boolean prime(int n), which returns true if n is prime otherwise returns false.

iii. void display() to display all three digits pal-prime numbers. Pal-prime numbers are 

those numbers which are both palindrome as well as prime.

 */

import java.util.*;

class pal_prime

{

   

    boolean isPalindrome(int n)

    {

        int r,k=n,s=0;

        while(n>0)

        {

            r=n%10;

            s=s*10+r;

            n=n/10;

        }

        if(s==k)

        return true;

        else

        return false;

    }

    boolean isPrime(int n)

    {

        int i,c=0;

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

        {

            if(n%i==0)

            c++;

        }

        if(c==2)

        return true;

        else

        return false;

    }

    void display()

    {

        System.out.println("All three digits Pal-Prime number are:");

        for(int i=100;i<=999;i++)

        {

            if(isPalindrome(i)==true && isPrime(i)==true)

            System.out.println(i);

        }

    }

    public static void main(String[]args)

    {

        pal_prime obj=new pal_prime();

        obj.display();

    }

}

Lead Number

 /*

 Write a program to accept a number and check it is a lead number or not.

Lead number is a number in which the sum of the even digits is equal to the sum of the odd digits.

Example- 1452

4+2=6

1+5=6

6==6

so, 1452 is a lead number.*/

import java.util.*;

class lead_no

{

    public static void main(String[]args)

    {

        Scanner sc=new Scanner(System.in);

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

        int n=sc.nextInt();

        int k=n,r,se=0,so=0;

        while(n>0)

        {

            r=n%10;

            if(r%2==0)

            se=se+r;

            else

            so=so+r;

            n=n/10;

        }

        if(se==so)

        System.out.println(k+" is a Lead Number");

        else

        System.out.println(k+" is not a Lead Number");

    }

}

Circular Prime Number

 //Write a program to accept a numbder and check it is a circular prime or not.

//A circular prime is a prime number with the property that the number generated at each intermediate

//step when cyclically permuting its digits will be prime.

//example= 113 is a circular prime number. 113,131,311 is circular prime

//1193,1931,9311,3119

//explanation left thru dry run

import java.util.*;

class circularp

{//class circularp opens

    int n;

    void accept()//method to accept the no

    {

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        n=sc.nextInt();//113

    }

    boolean isprime(int x)//method to check a no is prime or not//113

    {

        int c=0;

        for(int i=1;i<=x;i++)

        {

            if(x%i==0)

            {

                c=c+1;

            }

        }

        if(c==2)

        return true;

        else 

        return false;

    }

    int getnext(int x)//method to generate the next no //113

    {

        int temp=x;//113

        int count=0;

        while(temp>0)

        {

            count++;//3

            temp=temp/10;

        }

        int num=x;//113

        int rem=num%10;//113%10=3

        int div=num/10;//113/10=11

        num=(int)((Math.pow(10,count-1))*rem)+div;//311

        return num;

    }

    boolean iscprime()//method for checking  no is circular prime or not

    

    {

        int nxt=n;//113

    while(isprime(nxt))//true

    {

        nxt=getnext(nxt);//311

        if(nxt==n)//311==113 f

        return true;

    }

    return false;

}

void display()//method to display the result

{

    if(iscprime()==true)

    System.out.println(n+" is a circular prime no");

    else

    System.out.println(n+" is not a circular prime no");

}

public static void main(String[]args)

{//main method opens

    circularp obj=new circularp();

    obj.accept();

    obj.display();

}//main method closes

}//class closes

Narcissistic Number

 //Wap to accept a number and check it is Narcissistic number or not.

//Narcissistic number is a number that is the sum of its own digits each raised 

//to the power of the number of digits.1634=1^4+6^4+3^4+4^4=1634

import java.util.*;

class narcisst

{//class narcisst opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no//153

        int r=0,c=0,s=0,k=n,a=n;//variable r to extract the digits,variable c to count the no digits,variable k and a to store the no,vvariable s to store the sum

        while(n>0)//153>0 t//15>0 t//1>0 t//0>0 false

        {

            c=c+1;//0+1=1//1+1=2//2+1=3

            n=n/10;//153/10=15//15/10=1//1/10=0

        }

        while(a>0)//153>0 t//15>0 t//1>0 t//0>0 false

        {

            r=a%10;//153%10=3//15%10=5//1%10=1

            s=s+(int)Math.pow(r,c);//0+27=27//27+125=152//152+1=153

            a=a/10;//153/10=15//15/10=1//1/10=0

            

        }

        if(s==k)//153==153 true

        System.out.println("It is a narcisst no");

        else

        System.out.println("It is not a narcisst no");

    }//main method closes

}//class closes


    

Amicable Pair Number

 //Wap to accept two numbers and check it is amicable numbers or not.

//the sum of the factor of the first number is equal to the second number and the sum of the factor of

//the second number is equal to the first number, then it is an amicable pair.

//ex- (220,284) are amicable pair

//sum of factors 220=(1,2,4,5,10,11,20,22,44,55,110)=284

//sum of factors 284=(1,2,4,71,142)=220

import java.util.*;

class amicable

{//class amicable opens

    int a=0,b=0;

    void accept()//method to accept the nos

    {

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        a=sc.nextInt();//220

        System.out.println("Enter another no");

        b=sc.nextInt();//284

    }

    int sumfactor(int n)//method to return the sum of the factors

    {

        int sum=0;

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

        {

            if(n%i==0)

            sum=sum+i;

        }

        return sum;

    }

    void display()//method to display the results

    {

        if((sumfactor(a)==b)&&(sumfactor(b)==a))//284==284 true && 220==220 true

        System.out.println(a+" and "+b+" is an amicable pairs");

        else

        System.out.println("Not an amicable pairs");

    }

    public static void main(String[]args)

    {//main method opens

        amicable obj=new amicable();

        obj.accept();

        obj.display();

    }//main method closes

}//class closes


Duck Number

Duck number is a number which has zeroes present in it, but there should be no zero present in the beginning of the number. For example 3210, 7056, 8430709 are all duck numbers whereas 08237, 04309 are not. 

import java.util.*;

class duck

{//class duck opens

    public static void main(String[]args)

    {//main method opens 

       Scanner sc=new Scanner(System.in);

       System.out.println("Enter a no");

       int n=sc.nextInt();//variable n to accept the no

       int p=1,r=0;//variable p to store the product,varible r to extract the digits 

       while(n>0)

       {

        r=n%10;

        p=p*r;

        n=n/10;

       }

       if(p==0)

    System.out.println("It is a duck no");

     else

    System.out.println("It is  not a duck no");

    }//main method closes

}  //class closes

Abundant Number

 //Wap to accept a number and check it is Abundant number or not.

//A number is said to be Abundant if sum of the factors of the number is greater than the number.

import java.util.*;

class abundent

{//class abundent opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept a no//12

        int s=0;//variable s to store the sum of the factors

        for(int i=1;i<n;i++)//1//2//3//4//5//6//7//8//9//10//11//12false

        {

            if(n%i==0)//12%1==0 t//12%2==0 t//12%3==0 t//12%4==0 t//12%5==0 f//12%6==0 t//12%11==0f

            s=s+i;//0+1=1//1+2=3//3+3=6//6+4=10//10+6=16

        }

        if(s>n)//16>12 true

        System.out.println("It is an abundent no");

        else

        System.out.println("It is not an abundent no");

    }//main method closes

}//class closes


Deficient Number

 //Wap to accept a number and check it is Deficient number or not.

//A number is said to be a Deficient number if sum of the factors of the number is less than the number.

import java.util.*;

class deficient

{//class deficient opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no

        int s=0;//variable s to store the sum of the factors

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

        {

            if(n%i==0)

            s=s+i;

        }

        if(s<n)

        System.out.println("It is a deficient no");

        else

        System.out.println("It is not a deficient no");

    }//main method closes

}//class closes


Ugly Number

 // A number is said to be an Ugly number if and only if the number is divisible by 2, 3 and 5. 

import java.util.*;

class ugly

{//class ugly opens

    public static void main(String[]args)

    {//main metjod opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no

        int c=0;//variable c to return the result in 0 or 1

        while(n!=1)//21!=1 t//7!=1 t

        {

            if(n%2==0)//21%2==0 false//7%2==0 false

            {

                n=n/2;

            }

            else if(n%3==0)//21%3==0 t//7%3==0 false

            {

                n=n/3;//21/3=7

            }

            else if(n%5==0)//7%5==0 false

            {

                n=n/5;

            }

            else

            {

                System.out.println("It is not an ugly no");

                c=1;

                break;

            }

        }

        if(c==0)//1==0

        System.out.println("It is an ugly no");

    }//main method closes

}//class closes


Emrip Number

 //Write a program to accept a number and check it is an emrip number or not.

//A number is said to be an emrip if the number is prime backward and forward.

//example-13 and 31 both are prime

import java.util.*;

class emirp

{//class emirp opens

    int n=0;//variable n to accept the no

    boolean isprime(int n)//method to check whether the no is prime or not

    {

        int c=0;

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

        {

            if(n%i==0)

            c=c+1;

        }

        if(c==2)

        return true;

        else

        return false;

    }

    void calculate(int k)//method to check whether both the actual and reverse nos are prime or not 

    {

        int r=0,rev=0,a=k;

        while(k>0)

        {

            r=k%10;

            k=k/10;

            rev=rev*10+r;//91

        }

        if(isprime(a)==true && isprime(rev)==true)

        System.out.println("It is an emirp no");

        else

        System.out.println("It is not an emirp no");

    }

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//13

        int k=n;//13

        emirp obj=new emirp();

        obj.calculate(k);

    }//main method closes

}//class closes


Disarium Number

 //Write a program to accept a number and check it is Disarium number or not.

// A number is said to be Disarium number when the sum of its digit raised to the power of their respective

// positions is equal to the number itself. ex=175 1^1 + 7^2 + 5^3 = 1+49+125 = 175

import java.util.*;

class disarium

{//class disarium opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no//175

        int r=0,s=0,k=n,c=0,check=n;//variable r to extract the digits,variable k and check to store the no

        while(n>0)//175>0 t//17>0 t//1>0 t//0>0 f

        {

         n=n/10; //175/10=17//17/10=1//1/10=0

         c=c+1;//variable c to store the no of digits//c+1=1//1+1=2//2+1=3

        }

        while(k>0)//175>0 t//17>0 t//1>0 t//0>0 false

        {

            r=k%10;//175%10=5//17%10=7//1%10=1

            s=s+(int)Math.pow(r,c);//variable s to store the sum//0+125=125//125+49=174//174+1=175

            c--;//3--=2//2--=1//1--=0

            k=k/10;//175/10=17//17/10=1//1/10=0

        }

        if(s==check)//175==175 true

        System.out.println("It is a disarium no");

        else

        System.out.println("It is not a disarium no");

    }//main method closes

}//class closes


Lucky Number

 //Write a program to accept a number and check it is a luck number or not.

//A number is said to be lucky if it does not contain any similar digit.

//ex- 9654 is a lucky number.

import java.util.*;

class lucky

{//class lucky opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        int r=0,count=0;//variable r to extract the digits,variable count to store the frequency 

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no//9654

        for(int i=0;i<=9;i++)//0//1//2//3//4

        {

            int k=n;//49654

            count=0;

            while(k>0)//9654>0 t//965>0 t//96>0//9>0 //0>0 false

            {

                r=k%10;//9654%10=4//965%10=5//96%10=6//9%10=9

                if(r==i)//4==4 t//5==4 f//6==4 f//9==4 f//4==4 t

                {

                    count=count+1;//1//1+1=2

                }

                k=k/10;//9654/10=965//965/10=96//96/10=9//9/10=0

            }

            if(count>1)//2>1 true

            {

                break;

            }

        }

        if(count>1)//2>1 true

        {

            System.out.println("It is not a lucky no");//49654

        }

        else

        System.out.println("It is a lucky no");

    }//main method closes

}//class closes


Kaprekar Number

 //Wap to accept a number and check it is a Kaprekar number or not.

//A number is said to be a Kaprekar, when a number whose square divide into two parts and the sum 

//of the parts is equal to the original number then it is called Kaprekar.

//ex- 45 --> 45^2 =2025 -->20+25=45

import java.util.*;

class kaprikar

{//class kaprikar opens

    public static void main(String[]args)

    {//main metthod opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no//45

        int sq=n*n;//variable sq to store the square of the no//45x45=2025

        int c=0;//variable c to store the no of digits

        int copy=sq;//variable copy to store the square of the no//2025

        while(sq>0)//2025>0 t//202>0 t//20>0 t//2>0 t//0>0 false

        {

            c=c+1;//0+1=1//1+1=2//2+1=3//3+1=4

            sq=sq/10;//2025/10=202//202/10=20//20/10=2//2/10=0

        }

        int mid=c/2;//variable mid to half the no of digits//4/2=2

        int k=(int)Math.pow(10,mid);//varible k to store the divisor//100

        int f=copy%k;//variable f to store the last part of the square//2025%100=25

        int l=copy/k;//variable l to store the first part of the square//2025/100=20 

        int sum=f+l;//variable sum to store the sum //25+20=45

        if(sum==n)//45==45 true

        System.out.println("It is a kaprikar no");

        else

        System.out.println("It is not a kaprikar no");

    }//main method closes

}//class closes


Pronic Number

pronic number is a number which is the product of two consecutive integers, that is, a number of the form n(n + 1). The first few pronic numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 … etc. 

import java.util.*;

class pronic

{//class pronic opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no

        int sq=(int)Math.sqrt(n);//variable sq to store the square root of the no

        int p=sq*(sq+1);//variable p stores the product of the square root with the next number of the square root 

        if(p==n)

        System.out.println("It is  pronic no");

        else

        System.out.println("It is not a pronic no");

    }//main method closes

}//class closes


Keith Number

 //Write a program to accept a number and check it is a Keith number or not.

//A Keith number is an integer n with d digits with the following property. if a fibonacci like sequence

//is formed with the first d terms. ex- 197 is a keith number

//1,9,7,17,33,57,107,197 

import java.util.*;

class keith1

{

    public static void main(String[]args)

    {

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//197

        int c=0,k=n,k1=n,s=0,sum=0,r=0,s1=n%10,num=n;//variable c to count the digit,k,k1,num to store the number,s,sum to store the sum,r to store the result,s1 to store the last digit

        while(n>0)

        {

            c=c+1;//3

            s=s+(n%10);//17

            n=n/10;

        }

        int s2=s,c1=c;//variable s2 to store the sum,c1 to store the no of digits

        while(c>0)//3>0 t//2>0 t//1>0 t//0>0 f

        {

            sum=sum+s;//0+17=17//17+16=33//33+24=57

            r=k/(int)Math.pow(10,c-1);//197/100=1//97/10=9//7/1=7

            s=sum-r;//17-1=16//33-9=24//57-7=50

            k=k%(int)Math.pow(10,c-1);//197%100=97//97%10=7//7%1=0

            c--;

           

        }

            if(sum==k1)//50==197 f

            System.out.println("It is a keith no");

            else

            {

        

        while(sum<=k1)//50<=197//93<=197//169<=197

        {

            sum=(2*sum)-s1;//2x50-7=93//2x93-17=169//2x169-33=305

            s1=s2;//17//33//

            if(c1>0)//3>0 t//2>0 t

            {

            s2=s2+(s2-(num/(int)Math.pow(10,c1-1)));//17+(17-197/100)=33//33+(33-97/10)=57

            num=num%(int)Math.pow(10,c1-1);//197%100=97//97%10=7

            }

            c1--;

            if(sum==k1)

            break;

            

        

        }

    if(sum==k1)

    System.out.println("It is a keith no");

    else

    System.out.println("It is not a keith no");

}

}//main method opens

}//class opens



Automorphic Number

In mathematics, an automorphic number is a number whose square "ends" in the same digits as the number itself. For example, 52 = 25, 62 = 36, 762 = 5776, and 8906252 = 793212890625, so 5, 6, 76 and 890625 are all automorphic numbers.

 import java.util.*;

class automorphic

{//class automorphic opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no

        int sq=n*n;//variable sq to store the square of the no

        int c=0,k=n;//variable c to store the no of digits,variable k to store the no

        while(k>0)

        {

          c=c+1;

          k=k/10;

        }

        int l=sq%(int)Math.pow(10,c);//varible l to extract the no from the last part of the square

        if(n==l)

        System.out.println("It is an automorphic no");

        else

        System.out.println("It is not an automorphic no");

    }//main method closes

}//class closes


Twin Primes Numbers

Twin Primes are the prime numbers with a difference of 2, e.g., (3, 5), (5, 7), (11, 13), (17, 19), (29, 31) ... etc. In this program isPrime(int n) will return true if the number is prime and false if it is not prime.

 import java.util.*;

class twinprime 

{//class twinprime opens

    int a=0,b=0;

    void input()//method to input the nos

    {

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        a=sc.nextInt();

        System.out.println("Enter another no");

        b=sc.nextInt();

    }

    boolean isprime(int n)//method to check whether a no is prime or not

    {

        int c=0;

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

        {

            if(n%i==0)

            c=c+1;

        }

        if(c==2)

        return true;

        else

        return false;

    }

    void display()//method to print the result

    {

        if(((isprime(a)==true)&&(isprime(b)==true))&&((a-b==2)||(b-a==2)))

        {

            System.out.println("It is a twinprime no");

        }

        else

        System.out.println("It is not a twinprime no");

    }

    public static void main(String[]args)

    {//main method opens

        twinprime obj=new twinprime();

        obj.input();

        obj.display();

    }//main method closes

}//class closes


            

Prime Number

Prime number in Java: Prime number is a number that is greater than 1 and divided by 1 or itself only. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.

 import java.util.Scanner;

class prime

{//class prime opens

    public static void main(String[]args)

    {//main method opens

        

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

       int n=sc.nextInt();//variable n to accept the no

        int c=0;//variable c to count the no of factors

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

        {

           if(n%i==0)

            c=c+1;

        }

        if(c%2==0)

        System.out.println("It is a prime no");

        else

        System.out.println("It is not a prime no");

    }//main method closes

}//class closes

          

Perfect Number

A Perfect number is a positive integer that is equal to the sum of its proper divisors except itself. Let's take an easy example, such as 6. 1, 23 and 6 are the divisors of 6. If we add up all the numbers except 6, we end with the sum of 6 itself. 

import java.util.Scanner;

class perfect

{//class perfect opens

    public static void main(String[]args)

    {//main method opens

        

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

       int n=sc.nextInt();//variable n to accept the no

        int s=0;//variable s to store the sum of the factors

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

        {

           if(n%i==0)

            s=s+i;

        }

        if(s==n)

        System.out.println("It is a perfect no");

        else

        System.out.println("It is not a perfect no");

    }//main method closes

}//class closes

          

Fascinating Number

 //Write a prigram to accept a number and check it is a fascinating number or not.

// A fascinating number is one which when multiplied by 2 and 3, and then after the results

//are concatenated with the original number, the new number contains all the digits from 1 to 9 

//exactly once. example 192

//192 x 1=192 ; 192 x 2=384 ; 192 x 3=576; now concatenating the result =192384576.

import java.util.*;

class fascinating

{//class fascinating opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no//192

        int n2=n*2;//variable n2 to store 2 times the no//192x2=384

        int n3=n*3;//variable n3 to store 3 times the no//192x3=576

        String con=n+""+n2+n3;//variable con to concatente the three nos//192384576

        boolean flag=true;//variable flag to store the result

        for(char i='1';i<='9';i++)//2

        {

            int c=0;//variable c to check the frequency

             

            for(int j=0;j<con.length();j++)//0

            {

                char ch=con.charAt(j);//1

                 

                if(ch==i)//9==1 f

                c++;//1

            }

            if(c>1 || c==0)//1>1 f || 1==0 f

            {

                flag =false;

                break;

            }

           

        }

        if(flag)

        System.out.println(n+" is a fascinating no");

        else

        System.out.println(n+" is not a fascinating no");

    }//main method closes

}//class closes


Bouncy Number

 //Write a pro gram to accept a number and check it is a bouncy number or not.

//Bouncy number- A number which is neither increasing or decreasing is known as Bouncy Number.ex-16237

//Increasing number- A number which is increasing from left to right.ex-2459

//Decreasing number - A number which is increasing from right to left.ex-8631

import java.util.*;

class bouncy

{//class bouncy opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no - 2459

        String k=Integer.toString(n);//variable k to convert the no into String form -"2459"

        int len=k.length();//variable len to find the length - 4

        int k1=n,c=0,c1=0,r=0,s=0,min=0,max=0;//variable k1 to store the no,variable r to extract the digits

        while(k1>0)//2459>0 t//245>0 t//24>0 t//2>0 t//0>0 f

        {

            r=k1%10;//2459%10=9//245%10=5//24%10=4//2%10=2

            s=s*10+r;//variable s to reverse the no//0x10+9=9//9x10+5=95//95x10+4=954//954x10+2=9542

            k1=k1/10;//2459/10=245//245/10=24//24/10=2//2/10=0

        }

        

        while(n>0)//2459>0 t//245>0 t

        {

            r=n%10;//2459%10=9//245%10=5

            if(r>min)//9>0 t//5>9 f

            {

                min=r;//variaable min to store the smallest digit//9

                c=c+1;//variable c to store the no of smallest digits //1

            }

            else 

            {

                break;

            }

            n=n/10;//2459/10=245

        }

        while(s>0)//9542>0 t//954>0 t//95>0 t//9>0 t//0>0 f

        {

            r=s%10;//9542%10=2//954%10=4//95%10=5//9%10=9

            if(r>max)//2>0 t//4>2 t//5>4 t//9>5 t

            {

                max=r;//variable max to store the largest no//2//4//5//9

                c1=c1+1;//variable c1 to store the no of largest digits//0+1=1//1+1=2//2+1=3//3+1=4

            }

            else

            {

                break;

            }

            s=s/10;//9542/10=954//954/10=95//95/10=9//9/10=0

        }

        if(c1==len)//4==4 t

        System.out.println("Increasing order");

        else if(c==len)

        System.out.println("Decreasing order");

        else 

        System.out.println("Bouncy no");

    }//main method closes

}//class closes


Evil Number

 //An Evil number is a positive whole number which has even number of 1's in its binary equivalent.

import java.util.*;

class evil

{//class evil opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no

        int r=0,c=0;//variable r to extract the digits,variable c to count the no of 1s present in the binary notation

        while(n>0)//10>0t//5>0t//2>0t//1>0t//0>0false

        {

            r=n%2;//0//1//0//1

            if(r==1)//f//t//f//t

            c=c+1;//0//1//2

            n=n/2;//10/2=5//5/2=2//2/2=1//1/2=0

        }

        if(c%2==0)//2%2==0 true

        System.out.println("It is an evil no");

        else

        System.out.println("It is not an evil no");

    }//main method closes

}//class closes


Happy Number

 //Wap to accept a number and check it is a Happy Number or not

//A happy number can be defined as a number which will yield 1 when it is replaced by the sum of the 

//square of its digits repeatedly.

import java.util.*;

class happy

{//class happy opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no//31

        int r=0,sum=0,k;//variable r to extract the digit,variable sum and k to store the sum

        sum=n;//31

        while(sum>9)//31>9 true//10>9 true//1>9 false

        {

            k=sum;//31//10

            sum=0;//0//0

            while(k>0)//10>0 t//1>0 t//0>0 f

            {

                r=k%10;//10%10=0//1%10=1

                sum=sum+r*r;//0+0x0=0//0+1x1=1

                k=k/10;//10/10=1//1/10=0

            }

        }

        if(sum==1)//1==1 true

        System.out.println("It is a happy no");

        else 

        System.out.println("It is not a happy no");

    }//main method closes

}//class closes


Smith Number

 /* A Smith number is a composite number, the sum of whose digits is the sum of the digits of its prime 

 * factors obtained as a result of prime factorization(excluding 1).

 * ex- 666 is a Smith Number -->prime factors --> 2,3,3,37

 * sum of the digits=6+6+6=18

 * sum of the digits of the factors=2+3+3+3+7=18

 */

import java.util.*;

class smith

{//class smith opens 

    int sumdigit(int n)//method to find the sum of the digits

    {

        int s=0;

        while(n>0)

        {

            s=s+(n%10);//10

            n=n/10;

        }

        return s;

    } 

    int sumprimefact(int n)//method to find the sum of the prime factors

    {

            int i=2,sum=0;

            while(n>1)//666>1 t

            {

                if(n%i==0)//666%2==0 t//37%37==0 t

                {

                    sum=sum+sumdigit(i);//0+2+3+3+10=18

                    n=n/i;

                }

                else

                i++;

            }

            return sum;

    }

    public static void main(String[]args)

    {//main method opens

            Scanner sc=new Scanner(System.in);

            smith obj=new smith();

            System.out.println("Enter a no");

            int n=sc.nextInt();//666

            int a=obj.sumdigit(n);//18

            int b=obj.sumprimefact(n);//18

            System.out.println("Sum of the digits= "+a);//18

            System.out.println("Sum of the prime factors= "+b);//18

            if(a==b)//18==18 true

            System.out.println("It is a smith no");

            else

            System.out.println("It is not a smith no");

    }//main method closes

}//class closes

    

 

Harshad Number

 //Wap to accept a number and check it is Harshad number or not.

//A number is said to be Harshad, if the number is divisible by sum of its digits.

import java.util.*;

class harshad

{//class harshad opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no 156

        int k=n,r=0,s=0;//variable k to store the no,variable r to extrct the digits,variable s to store the sum

        while(n>0)//156>0 true//15>0 true//1>0 true

        {

            r=n%10;//156%10=6//15%10=5//1%10=1//0>0 false

            s=s+r;//0+6=6//6+5=11//11+1=12

            n=n/10;//156/10=15//15/10=1//1/10=0

        }

        if((k%s)==0)//156%12==0 true

        System.out.println(k+" is  harshad no");

        else

        System.out.println(k+" is not a harshad no");

    }//main method closes

}//class closes


Neon Number

Neon Number is a positive integer, which is equal to the sum of the digits of its square. For example, 9 is a neon number, because 92 = 81, and the sum of the digits 8 + 1 = 9, which is same as the original number.

 import java.util.*;

class neon

{//class neon opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no

        int sq=n*n;//varible sq to store the square of the no

        int r=0,s=0;//variable r to extract the digits,variable s to store the sum

        while(sq>0)

        {

            r=sq%10;

            s=s+r;

            sq=sq/10;

        }

        if(s==n)

        System.out.println(n+" is a neon no");

        else

        System.out.println(n+" is not a neon no");

    }//main method closes

}//class closes


Krishnamurthy Number

 //Write a program to accept a number and check it is Krishnamurthy number or not.

//If the sum of the factorial of all the digits of a number is equal to the original number.

//example- 145 is a Krishnamurthy number. (1+24+120)=145

import java.util.*;

class krishnamurthy

{//class krishnamurthy opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no

        int r=0,f=1,sum=0,k=n;//variable r to extract the digits,variable f to store the factorial,variable k to store the no

        while(k>0)//145>0 t//14>0 t//1>0 t//0>0 false

        {

            r=k%10;//145%10=5//14%10=4//1%10=1

            f=1;

            for(int i=1;i<=r;i++)//1

            {

                f=f*i;//1x1=1

            }

            

            sum=sum+f;//0+120=120//120+24=144//144+1=145

            k=k/10;//145/10=14//14/10=1//1/10=0

        }

        if(sum==n)//145==145 true

        System.out.println(n+" is a krishnamurthy no");

        else

        System.out.println(n+" is not a krishnamurthy no");

    }//main method closes

}//class closes


Magic Number

 Magic number is the if the sum of its digits recursively are calculated till a single digit If the single digit is 1 then the number is a magic numberMagic number is very similar with Happy Number. 2+2+6=10 sum of digits is 10 then again 1+0=1 now we get a single digit number is 1.

import java.util.*;

class magic

{ //class magic opens

    public static void main(String[]args)

    { //main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no

        int r=0,sum=0,k=0;//variable r to extract the digits,variable sum and k to store the sum

        sum=n;

        while(sum>9)

        {

            k=sum;

            sum=0;

            while(k>0)

            {

                r=k%10;

                sum=sum+r;

                k=k/10;

            }

        }

        if(sum==1)

        System.out.println(n+" is a magic no");

        else

        System.out.println(n+" is not a magic no");

    }//main method closes

}//class closes


Armstrong Number

Armstrong Number in Java: A positive number is called armstrong number if it is equal to the sum of cubes of its digits for example 0, 1, 153, 370, 371, 407 etc.

 import java.util.*;

class armstrong

{//class armstrong opens

    public static void main(String[]args)

    {//main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n to accept the no

        int k=n,r=0,s=0;//variable k to store the no,varible r to extract the digits,variable s to store the sum

        while(n>0)

        {

            r=n%10;

            s=s+(r*r*r);

            n=n/10;

        }

        if(k==s)

        System.out.println(k+" is an armstrong no");

        else

        System.out.println(k+" is not an armstrong no");

    }//method closes

}//class closes

        


Palindrome Number

Palindrome number in java: A palindrome number is a number that is same after reverse. For example 545, 151, 34543, 343, 171, 48984 are the palindrome numbers. It can also be a string like LOL, MADAM etc.

 import java.util.*;

class pallinodrome

{      //class pallinodrome opens

    public static void main(String[]args)

    {  //main method opens

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//variable n accepts the no

        int r=0,rev=0,k=n;//variable r to extract the digits,variable rev to reverse the no,variable k to store the no

        while(n>0)

        {

            r=n%10;

            rev=(rev*10)+r;

            n=n/10;

        }

        if(k==rev)

        System.out.println(k+" is a pallinodrome no");

        else

        System.out.println(k+" is not a pallinodrome no");

    }//main method closes

}//class closes


Class 11 - Computer Science with Python Sumita Arora - Chapter 7 - Python Fundamentals

 

Chapter 7

Python Fundamentals

Class 11 - Computer Science with Python Sumita Arora


Multiple Choice Questions

Question 1

Special meaning words of Pythons, fixed for specific functionality are called .......... .

  1. Identifiers
  2. functions
  3. Keywords ✓
  4. literals

Question 2

Names given to different parts of a Python program are .......... .

  1. Identifiers ✓
  2. functions
  3. Keywords
  4. literals

Question 3

Data items having fixed value are called .......... .

  1. Identifiers
  2. functions
  3. Keywords
  4. literals ✓

Question 4

Which of the following is/are correct ways of creating strings ?

  1. name = Jiya
  2. name = 'Jiya' ✓
  3. name = "Jiya" ✓
  4. name = (Jiya)

Question 5

Which of the following are keyword(s) ?

  1. name
  2. Print
  3. print ✓
  4. input ✓

Question 6

Which of the following are valid identifiers ?

  1. my name
  2. _myname ✓
  3. myname ✓
  4. my-name

Question 7

Which of the following are literals ?

  1. myname
  2. "Radha" ✓
  3. 24.5 ✓
  4. 24A

Question 8

Escape sequences are treated as .......... .

  1. strings
  2. characters ✓
  3. integers
  4. none of these

Question 9

Which of the following is an escape sequence for a tab character ?

  1. \a
  2. \t ✓
  3. \n
  4. \b

Question 10

Which of the following is an escape sequence for a newline character ?

  1. \a
  2. \t
  3. \n ✓
  4. \b

Question 11

Which of the following is not a legal integer type value in Python ?

  1. Decimal
  2. Octal
  3. Hexadecimal
  4. Roman ✓

Question 12

Which of the following symbols are not legal in an octal value ?

  1. 7
  2. 8 ✓
  3. 9 ✓
  4. 0

Question 13

Value 17.25 is equivalent to

  1. 0.1725E-2
  2. 0.1725E+2 ✓
  3. 1725E2
  4. 0.1725E2 ✓

Question 14

Value 0.000615 is equivalent to

  1. 615E3
  2. 615E-3
  3. 0.615E3
  4. 0.615E-3 ✓

Question 15

Which of the following is/are expression(s) ?

  1. a+b-5 ✓
  2. a
  3. -5
  4. b-5 ✓

Question 16

The lines beginning with a certain character, and which are ignored by a compiler and not executed, are called ..........

  1. operators
  2. operands
  3. functions
  4. comments ✓

Question 17

Which of the following can be used to create comments ?

  1. //
  2. # ✓
  3. '''
  4. ''' . . . ''' ✓

Question 18

Which of the following functions print the output to the console ?

  1. Output( )
  2. Print( )
  3. Echo( )
  4. print( ) ✓

Question 19

Select the reserved keyword in Python.

  1. else
  2. import
  3. print
  4. all of these ✓

Question 20

The input( ) returns the value as .......... type.

  1. integer
  2. string ✓
  3. floating point
  4. none of these

Question 21

To convert the read value through input( ) into integer type, ..........( ) is used.

  1. floating
  2. float
  3. int ✓
  4. integer

Question 22

To convert the read value through input( ) into a floating point number, ..........( ) is used.

  1. floating
  2. float ✓
  3. int
  4. integer

Question 23

To print a line a text without ending it with a newline, .......... argument is used with print( )

  1. sep
  2. newline
  3. end ✓
  4. next

Question 24

The default separator character of print( ) is ..........

  1. tab
  2. space ✓
  3. newline
  4. dot

Question 25

To give a different separator with print( ) .......... argument is used.

  1. sep ✓
  2. separator
  3. end
  4. tab

Fill in the Blanks

Question 1

keyword is a reserved word carrying special meaning and purpose.

Question 2

Identifiers are the user defined names for different parts of a program.

Question 3

Literals are the fixed values.

Question 4

Operators are the symbols that trigger some computation or action.

Question 5

An expression is a legal combination of symbols that represents a value.

Question 6

Non-executable, additional lines added to a program, are known as comments.

Question 7

In Python, the comments begin with # character.

Question 8

Python is a case sensitive language.

Question 9

The print( ) function prints the value of a variable/expression.

Question 10

The input( ) function gets the input from the user.

Question 11

The input( ) function returns the read value as of string type.

Question 12

To convert an input( )'s value in integer type, int( ) function is used.

Question 13

To convert an input( )'s value in floating-point type, float( ) function is used.

Question 14

Strings can be created with single quotes, double quotes and triple quotes.

True/False Questions

Question 1

Keywords can be used as identifier names.
False

Question 2

The identifiers in Python can begin with an underscore.
True

Question 3

0128 is a legal literal value in Python.
False

Question 4

0x12EFG is a legal literal value in Python.
False

Question 5

0123 is a legal literal value in Python.
True

Question 6

Variables once assigned a value can be given any other value.
True

Question 7

Variables are created when they are first assigned their value.
True

Question 8

Python variables support dynamic typing.
True

Question 9

You can rename a keyword.
False

Question 10

String values in Python can be single line strings, and multi-line strings.
True

Question 11

A variable can contain values of different types at different times.
True

Question 12

Expressions contain values/variables along with operators.
True

Type A : Short Answer Questions/Conceptual Questions

Question 1

What are tokens in Python ? How many types of tokens are allowed in Python ? Examplify your answer.

Answer

The smallest individual unit in a program is known as a Token. Python has following tokens:

  1. Keywords — Examples are import, for, in, while, etc.
  2. Identifiers — Examples are MyFile, _DS, DATE_9_7_77, etc.
  3. Literals — Examples are "abc", 5, 28.5, etc.
  4. Operators — Examples are +, -, >, or, etc.
  5. Punctuators — ' " # () etc.

Question 2

How are keywords different from identifiers ?

Answer

Keywords are reserved words carrying special meaning and purpose to the language compiler/interpreter. For example, if, elif, etc. are keywords. Identifiers are user defined names for different parts of the program like variables, objects, classes, functions, etc. Identifiers are not reserved. They can have letters, digits and underscore. They must begin with either a letter or underscore. For example, _chk, chess, trail, etc.

Question 3

What are literals in Python ? How many types of literals are allowed in Python ?

Answer

Literals are data items that have a fixed value. The different types of literals allowed in Python are:

  1. String literals
  2. Numeric literals
  3. Boolean literals
  4. Special literal None
  5. Literal collections

Question 4

Can nongraphic characters be used in Python ? How ? Give examples to support your answer.

Answer

Yes, nongraphic characters can be used in Python with the help of escape sequences. For example, backspace is represented as \b, tab is represented as \t, carriage return is represented as \r.

Question 5

How are floating constants represented in Python ? Give examples to support your answer.

Answer

Floating constants are represented in Python in two forms — Fractional Form and Exponent form. Examples:

  1. Fractional Form — 2.0, 17.5, -13.0, -0.00625
  2. Exponent form — 152E05, 1.52E07, 0.152E08, -0.172E-3

Question 6

How are string-literals represented and implemented in Python ?

Answer

A string-literal is represented as a sequence of characters surrounded by quotes (single, double or triple quotes). String-literals in Python are implemented using Unicode.

Question 7

Which of these is not a legal numeric type in Python ? (a) int (b) float (c) decimal.

Answer

decimal is not a legal numeric type in Python.

Question 8

Which argument of print( ) would you set for:

(i) changing the default separator (space) ?
(ii) printing the following line in current line ?

Answer

(i) sep
(ii) end

Question 9

What are operators ? What is their function ? Give examples of some unary and binary operators.

Answer

Operators are tokens that trigger some computation/action when applied to variables and other objects in an expression. Unary plus (+), Unary minus (-), Bitwise complement (~), Logical negation (not) are a few examples of unary operators. Examples of binary operators are Addition (+), Subtraction (-), Multiplication (*), Division (/).

Question 10

What is an expression and a statement ?

Answer

An expression is any legal combination of symbols that represents a value. For example, 2.9, a + 5, (3 + 5) / 4.
A statement is a programming instruction that does something i.e. some action takes place. For example:
print("Hello")
a = 15
b = a - 10

Question 11

What all components can a Python program contain ?

Answer

A Python program can contain various components like expressions, statements, comments, functions, blocks and indentation.

Question 12

What do you understand by block/code block/suite in Python ?

Answer

A block/code block/suite is a group of statements that are part of another statement. For example:

if b > 5:
    print("Value of 'b' is less than 5.")
    print("Thank you.")

Question 13

What is the role of indentation in Python ?

Answer

Python uses indentation to create blocks of code. Statements at same indentation level are part of same block/suite.

Question 14

What are variables ? How are they important for a program ?

Answer

Variables are named labels whose values can be used and processed during program run. Variables are important for a program because they enable a program to process different sets of data.

Question 15

What do you understand by undefined variable in Python ?

Answer

In Python, a variable is not created until some value is assigned to it. A variable is created when a value is assigned to it for the first time. If we try to use a variable before assigning a value to it then it will result in an undefined variable. For example:

print(x)   #This statement will cause an error for undefined variable x
x = 20
print(x)

The first line of the above code snippet will cause an undefined variable error as we are trying to use x before assigning a value to it.

Question 16

What is Dynamic Typing feature of Python ?

Answer

A variable pointing to a value of a certain type can be made to point to a value/object of different type.This is called Dynamic Typing. For example:

x = 10
print(x)
x = "Hello World"
print(x)

Question 17

What would the following code do : X = Y = 7 ?

Answer

It will assign a value of 7 to the variables X and Y.

Question 18

What is the error in following code : X, Y = 7 ?

Answer

The error in the above code is that we have mentioned two variables X, Y as Lvalues but only give a single numeric literal 7 as the Rvalue. We need to specify one more value like this to correct the error:

X, Y = 7, 8

Question 19

Following variable definition is creating problem X = 0281, find reasons.

Answer

Python doesn't allow decimal numbers to have leading zeros. That is the reason why this line is creating problem.

Question 20

"Comments are useful and easy way to enhance readability and understandability of a program." Elaborate with examples.

Answer

Comments can be used to explain the purpose of the program, document the logic of a piece of code, describe the behaviour of a program, etc. This enhances the readability and understandability of a program. For example:

# This program shows a program's components

# Definition of function SeeYou() follows
def SeeYou():
    print("Time to say Good Bye!!")

# Main program-code follows now
a = 15
b = a - 10
print (a + 3)
if b > 5:         # colon means it's a block
    print("Value of 'a' was more than 15 initially.")
else:
    print("Value of 'a' was 15 or less initially.")

SeeYou()          # calling above defined function SeeYou()

Type B: Application Based Questions

Question 1

From the following, find out which assignment statement will produce an error. State reason(s) too.

(a) x = 55
(b) y = 037
(c) z = 0o98
(d) 56thnumber = 3300
(e) length = 450.17
(f) !Taylor = 'Instant'
(g) this variable = 87.E02
(h) float = .17E - 03
(i) FLOAT = 0.17E - 03

Answer

  1. y = 037 (option b) will give an error as decimal integer literal cannot start with a 0.
  2. z = 0o98 (option c) will give an error as 0o98 is an octal integer literal due to the 0o prefix and 8 & 9 are invalid digits in an octal number.
  3. 56thnumber = 3300 (option d) will give an error as 56thnumber is an invalid identifier because it starts with a digit.
  4. !Taylor = 'Instant' (option f) will give an error as !Taylor is an invalid identifier because it contains the special character !.
  5. this variable = 87.E02 (option g) will give an error due to the space present between this and variable. Identifiers cannot contain any space.
  6. float = .17E - 03 (option h) will give an error due to the spaces present in exponent part (E - 03). A very important point to note here is that float is NOT a KEYWORD in Python. The statement float = .17E-03 will execute successfully without any errors in Python.
  7. FLOAT = 0.17E - 03 (option i) will give an error due to the spaces present in exponent part (E - 03).

Question 2

How will Python evaluate the following expression ?

(i) 20 + 30 * 40

Answer

    20 + 30 * 40
⇒ 20 + 1200
⇒ 1220

(ii) 20 - 30 + 40

Answer

    20 - 30 + 40
⇒ -10 + 40
⇒ 30

(iii) (20 + 30) * 40

Answer

    (20 + 30) * 40
⇒ 50 * 40
⇒ 2000

(iv) 15.0 / 4 + (8 + 3.0)

Answer

    15.0 / 4 + (8 + 3.0)
⇒ 15.0 / 4 + 11.0
⇒ 3.75 + 11.0
⇒ 14.75

Question 3

Find out the error(s) in following code fragments:

(i)

temperature = 90
print temperature

Answer

The call to print function is missing parenthesis. The correct way to call print function is this:
print(temperature)

(ii)

a = 30
b=a+b
print (a And b)

Answer

There are two errors in this code fragment:

  1. In the statement b=a+b variable b is undefined.
  2. In the statement print (a And b), And should be written as and.

(iii)

a, b, c = 2, 8, 9
print (a, b, c)
c, b, a = a, b, c
print (a ; b ; c)

Answer

In the statement print (a ; b ; c) use of semicolon will give error. In place of semicolon, we must use comma like this print (a, b, c)

(iv)

X = 24
4 = X

Answer

The statement 4 = X is incorrect as 4 cannot be a Lvalue. It is a Rvalue.

(v)

print("X ="X)

Answer

There are two errors in this code fragment:

  1. Variable X is undefined
  2. "X =" and X should be separated by a comma like this print("X =", X)

(vi)

else = 21 - 5

Answer

else is a keyword in Python so it can't be used as a variable name.

Question 4

What will be the output produced by following code fragment (s) ?

(i)

X = 10          
X = X + 10         
X = X - 5       
print (X)       
X, Y = X - 2, 22
print (X, Y)    

Output

15
13 22

Explanation

  1. X = 10 ⇒ assigns an initial value of 10 to X.
  2. X = X + 10 ⇒ X = 10 + 10 = 20. So value of X is now 20.
  3. X = X - 5 ⇒ X = 20 - 5 = 15. X is now 15.
  4. print (X) ⇒ print the value of X which is 15.
  5. X, Y = X - 2, 22 ⇒ X, Y = 13, 22.
  6. print (X, Y) ⇒ prints the value of X which is 13 and Y which is 22.

(ii)

first = 2
second = 3
third = first * second
print (first, second, third) 
first = first + second + third
third = second * first
print (first, second, third)

Output

2 3 6
11 3 33

Explanation

  1. first = 2 ⇒ assigns an initial value of 2 to first.
  2. second = 3 ⇒ assigns an initial value of 3 to second.
  3. third = first * second ⇒ third = 2 * 3 = 6. So variable third is initialized with a value of 6.
  4. print (first, second, third) ⇒ prints the value of first, second, third as 2, 3 and 6 respectively.
  5. first = first + second + third ⇒ first = 2 + 3 + 6 = 11
  6. third = second * first ⇒ third = 3 * 11 = 33
  7. print (first, second, third) ⇒ prints the value of first, second, third as 11, 3 and 33 respectively.

(iii)

side = int(input('side') )  #side given as 7
area = side * side
print (side, area)

Output

side7
7 49

Explanation

  1. side = int(input('side') ) ⇒ This statements asks the user to enter the side. We enter 7 as the value of side.
  2. area = side * side ⇒ area = 7 * 7 = 49.
  3. print (side, area) ⇒ prints the value of side and area as 7 and 49 respectively.

Question 5

What is the problem with the following code fragments ?

(i)

a = 3
    print(a)
b = 4
    print(b)
s = a + b
    print(s)

Answer

The problem with the above code is inconsistent indentation. The statements print(a)print(b)print(s) are indented but they are not inside a suite. In Python, we cannot indent a statement unless it is inside a suite and we can indent only as much is required.

(ii)

name = "Prejith"
age = 26
print ("Your name & age are ", name + age)

Answer

In the print statement we are trying to add name which is a string to age which is an integer. This is an invalid operation in Python.

(iii)

a = 3
s = a + 10
a = "New"
q = a / 10

Answer

The statement a = "New" converts a to string type from numeric type due to dynamic typing. The statement q = a / 10 is trying to divide a string with a number which is an invalid operation in Python.

Question 6

Predict the output:

(a)

x = 40
y = x + 1       
x = 20, y + x    
print (x, y)

Output

(20, 81) 41

Explanation

  1. x = 40 ⇒ assigns an initial value of 40 to x.
  2. y = x + 1 ⇒ y = 40 + 1 = 41. So y becomes 41.
  3. x = 20, y + x ⇒ x = 20, 41 + 40 ⇒ x = 20, 81. This makes x a Tuple of 2 elements (20, 81).
  4. print (x, y) ⇒ prints the tuple x and the integer variable y as (20, 81) and 41 respectively.

(b)

x, y = 20, 60
y, x, y = x, y - 10, x + 10
print (x, y)

Output

50 30

Explanation

  1. x, y = 20, 60 ⇒ assigns an initial value of 20 to x and 60 to y.
  2. y, x, y = x, y - 10, x + 10
    ⇒ y, x, y = 20, 60 - 10, 20 + 10
    ⇒ y, x, y = 20, 50, 30
    First RHS value 20 is assigned to first LHS variable y. After that second RHS value 50 is assigned to second LHS variable x. Finally third RHS value 30 is assigned to third LHS variable which is again y. After this assignment, x becomes 50 and y becomes 30.
  3. print (x, y) ⇒ prints the value of x and y as 50 and 30 respectively.

(c)

a, b = 12, 13  
c, b = a*2, a/2
print (a, b, c)

Output

12 6.0 24

Explanation

  1. a, b = 12, 13 ⇒ assigns an initial value of 12 to a and 13 to b.
  2. c, b = a*2, a/2 ⇒ c, b = 12*2, 12/2 ⇒ c, b = 24, 6.0. So c has a value of 24 and b has a value of 6.0.
  3. print (a, b, c) ⇒ prints the value of a, b, c as 12, 6.0 and 24 respectively.

(d)

a, b = 12, 13
print (print(a + b))

Output

25
None

Explanation

  1. a, b = 12, 13 ⇒ assigns an initial value of 12 to a and 13 to b.
  2. print (print(a + b)) ⇒ First print(a + b) function is called which prints 25. After that, the outer print statement prints the value returned by print(a + b) function call. As print function does not return any value so outer print function prints None.

Question 7

Predict the output

a, b, c = 10, 20, 30
p, q, r = c - 5, a + 3, b - 4
print ('a, b, c :', a, b, c, end = '')
print ('p, q, r :', p, q, r)

Output

a, b, c : 10 20 30p, q, r : 25 13 16

Explanation

  1. a, b, c = 10, 20, 30 ⇒ assigns initial value of 10 to a, 20 to b and 30 to c.
  2. p, q, r = c - 5, a + 3, b - 4
    ⇒ p, q, r = 30 - 5, 10 + 3, 20 - 4
    ⇒ p, q, r = 25, 13, 16.
    So p is 25, q is 13 and r is 16.
  3. print ('a, b, c :', a, b, c, end = '') ⇒ This statement prints a, b, c : 10 20 30. As we have given end = '' so output of next print statement will start in the same line.
  4. print ('p, q, r :', p, q, r) ⇒ This statement prints p, q, r : 25 13 16

Question 8

Find the errors in following code fragment

(a)

y = x + 5
print (x, Y)

Answer

There are two errors in this code fragment:

  1. x is undefined in the statement y = x + 5
  2. Y is undefined in the statement print (x, Y). As Python is case-sensitive hence y and Y will be treated as two different variables.

(b)

print (x = y = 5)

Answer

Python doesn't allow assignment of variables while they are getting printed.

(c)

a = input("value")
b = a/2
print (a, b)

Answer

The input( ) function always returns a value of String type so variable a is a string. This statement b = a/2 is trying to divide a string with an integer which is invalid operation in Python.

Question 9

Find the errors in following code fragment : (The input entered is XI)

c = int (input ( "Enter your class") )
print ("Your class is", c)

Answer

The input value XI is not int type compatible.

Question 10

Consider the following code :

name = input ("What is your name?")
print ('Hi', name, ',')
print ("How are you doing?")

was intended to print output as

Hi <name>, How are you doing ?

But it is printing the output as :

Hi <name>,
How are you doing?

What could be the problem ? Can you suggest the solution for the same ?

Answer

The print() function appends a newline character at the end of the line unless we give our own end argument. Due to this behaviour of print() function, the statement print ('Hi', name, ',1) is printing a newline at the end. Hence "How are you doing?" is getting printed on the next line.
To fix this we can add the end argument to the first print() function like this:

print ('Hi', name, ',1, end = '')

Question 11

Find the errors in following code fragment :

c = input( "Enter your class" )
print ("Last year you were in class") c - 1

Answer

There are two errors in this code fragment:

  1. c - 1 is outside the parenthesis of print function. It should be specified as one of the arguments of print function.
  2. c is a string as input function returns a string. With c - 1, we are trying to subtract a integer from a string which is an invalid operation in Python.

The corrected program is like this:

c = int(input( "Enter your class" )) 
print ("Last year you were in class", c - 1) 

Question 12

What will be returned by Python as result of following statements?

(a) >>> type(0)

Answer

<class 'int'>

(b) >>> type(int(0))

Answer

<class 'int'>

(c) >>>.type(int('0')

Answer

SyntaxError: invalid syntax

(d) >>> type('0')

Answer

<class 'str'>

(e) >>> type(1.0)

Answer

<class 'float'>

(f) >>> type(int(1.0))

Answer

<class 'int'>

(g) >>>type(float(0))

Answer

<class 'float'>

(h) >>> type(float(1.0))

Answer

<class 'float'>

(i) >>> type( 3/2)

Answer

<class 'float'>

Question 13

What will be the output produced by following code ?

(a) >>> str(print())+"One"

Output

'NoneOne'

Explanation

print() function doesn't return any value so its return value is None. Hence, str(print()) becomes str(None)str(None) converts None into string 'None' and addition operator joins 'None' and 'One' to give the final output as 'NoneOne'.

(b) >>> str(print("hello"))+"One"

Output

hello 'NoneOne'

Explanation

First, print("hello") function is executed which prints the first line of the output as hello. The return value of print() function is None i.e. nothing. str() function converts it into string and addition operator joins 'None' and 'One' to give the second line of the output as 'NoneOne'.

(c) >>> print(print("Hola"))

Output

Hola None

Explanation

First, print("Hola") function is executed which prints the first line of the output as Hola. The return value of print() function is None i.e. nothing. This is passed as argument to the outer print function which converts it into string and prints the second line of output as None.

(d) >>> print (print ("Hola", end = ""))

Output

HolaNone

Explanation

First, print ("Hola", end = "") function is executed which prints Hola. As end argument is specified as "" so newline is not printed after Hola. The next output starts from the same line. The return value of print() function is None i.e. nothing. This is passed as argument to the outer print function which converts it into string and prints None in the same line after Hola.

Question 14

Carefully look at the following code and its execution on Python shell. Why is the last assignment giving error ?

>>> a = 0o12
>>> print(a)
10
>>> b = 0o13
>>> c = 0o78
    File "<python-input-41-27fbe2fd265f>", line 1
    c = 0o78
         ^
SyntaxError : invalid syntax         

Answer

Due to the prefix 0o, the number is treated as an octal number by Python but digit 8 is invalid in Octal number system hence we are getting this error.

Question 15

Predict the output

a, b, c = 2, 3, 4
a, b, c = a*a, a*b, a*c
print(a, b, c)

Output

4 6 8

Explanation

  1. a, b, c = 2, 3, 4 ⇒ assigns initial value of 2 to a, 3 to b and 4 to c.
  2. a, b, c = a*a, a*b, a*c
    ⇒ a, b, c = 2*2, 2*3, 2*4
    ⇒ a, b, c = 4, 6, 8
  3. print(a, b, c) ⇒ prints values of a, b, c as 4, 6 and 8 respectively.

Question 16

The id( ) can be used to get the memory address of a variable. Consider the adjacent code and tell if the id( ) functions will return the same value or not(as the value to be printed via print() ) ? Why ?
[There are four print() function statements that are printing id of variable num in the code shown on the right.

num = 13
print( id(num) )
num = num + 3
print( id(num) )
num = num - 3
print( id(num) )
num = "Hello"
print( id(num) )

Answer

num = 13
print( id(num) ) # print 1
num = num + 3
print( id(num) ) # print 2 
num = num - 3
print( id(num) ) # print 3
num = "Hello"
print( id(num) ) # print 4

For the print statements commented as print 1 and print 3 above, the id() function will return the same value. For print 2 and print 4, the value returned by id() function will be different.

The reason is that for both print 1 and print 3 statements the value of num is the same which is 13. So id(num) gives the address of the memory location which contains 13 in the front-loaded dataspace.

Question 17

Consider below given two sets of codes, which are nearly identical, along with their execution in Python shell. Notice that first code-fragment after taking input gives error, while second code-fragment does not produce error. Can you tell why ?

(a)

>>> print(num = float(input("value1:")) )  
value1:67

TypeError: 'num' is an invalid keyword argument for this function

(b)

>>> print(float(input("valuel:")) )
value1:67

67.0

Answer

In part a, the value entered by the user is converted to a float type and passed to the print function by assigning it to a variable named num. It means that we are passing an argument named num to the print function. But print function doesn't accept any argument named num. Hence, we get this error telling us that num is an invalid argument for print function.

In part b, we are converting the value entered by the user to a float type and directly passing it to the print function. Hence, it works correctly and the value gets printed.

Question 18

Predict the output of the following code :

days = int (input ("Input days : ")) * 3600 * 24
hours = int(input("Input hours: ")) * 3600 
minutes = int(input("Input minutes: ")) * 60 
seconds = int(input("Input seconds: ")) 
time = days + hours + minutes + seconds 
print("Total number of seconds", time)

If the input given is in this order : 1, 2, 3, 4

Output

Input days : 1
Input hours: 2
Input minutes: 3
Input seconds: 4
Total number of seconds 93784

Question 19

What will the following code result into ?

n1, n2 = 5, 7
n3 = n1 + n2
n4 = n4 + 2
print(n1, n2, n3, n4)

Answer

The code will result into an error as in the statement n4 = n4 + 2, variable n4 is undefined.

Question 20

Correct the following program so that it displays 33 when 30 is input.

val = input("Enter a value")
nval = val + 30
print(nval)

Answer

Below is the corrected program:

val = int(input("Enter a value"))    #used int() to convert input value into integer 
nval = val + 3    #changed 30 to 3
print(nval)

Type C : Programming Practice/Knowledge based Questions

Question 1

Write a program that displays a joke. But display the punchline only when the user presses enter key.
(Hint. You may use input( ))

Solution
print("Why is 6 afraid of 7?")
input("Press Enter")
print("Because 7 8(ate) 9 :-)")
Output
Why is 6 afraid of 7?
Press Enter
Because 7 8(ate) 9 :-)

Question 2

Write a program to read today's date (only del part) from user. Then display how many days are left in the current month.

Solution
day = int(input("Enter day part of today's date: "))
totalDays = int(input("Enter total number of days in this month: "))
daysLeft = totalDays - day
print(daysLeft, "days are left in current month")
Output
Enter day part of today's date: 16
Enter total number of days in this month: 31
15 days are left in current month

Question 3

Write a program that generates the following output :
5
10
9
Assign value 5 to a variable using assignment operator (=) Multiply it with 2 to generate 10 and subtract 1 to generate 9.

Solution
a = 5
print(a)
a = a * 2
print(a)
a = a - 1
print(a)
Output
5
10
9

Question 4

Modify above program so as to print output as 5@10@9.

Solution
a = 5
print(a, end='@')
a = a * 2
print(a, end='@')
a = a - 1
print(a)
Output
5@10@9

Question 5

Write the program with maximum three lines of code and that assigns first 5 multiples of a number to 5 variables and then print them.

Solution
a = int(input("Enter a number: "))
b, c, d, e = a * 2, a * 3, a * 4, a * 5
print(a, b, c, d, e)
Output
Enter a number: 2
2 4 6 8 10

Question 6

Write a Python program that accepts radius of a circle and prints its area.

Solution
r = float(input("Enter radius of circle: "))
a = 3.14159 * r * r
print("Area of circle =", a)
Output
Enter radius of circle: 7.5
Area of circle = 176.7144375

Question 7

Write Python program that accepts marks in 5 subjects and outputs average marks.

Solution
m1 = int(input("Enter first subject marks: "))
m2 = int(input("Enter second subject marks: "))
m3 = int(input("Enter third subject marks: "))
m4 = int(input("Enter fourth subject marks: "))
m5 = int(input("Enter fifth subject marks: "))
avg = (m1 + m2+ m3+ m4 + m5) / 5;
print("Average Marks =", avg)
Output
Enter first subject marks: 65
Enter second subject marks: 78
Enter third subject marks: 79
Enter fourth subject marks: 80
Enter fifth subject marks: 85
Average Marks = 77.4

Question 8

Write a short program that asks for your height in centimetres and then converts your height to feet and inches. (1 foot = 12 inches, 1 inch = 2.54 cm).

Solution
ht = int(input("Enter your height in centimeters: "))
htInInch = ht / 2.54;
feet = htInInch // 12;
inch = htInInch % 12;
print("Your height is", feet, "feet and", inch, "inches")
Output
Enter your height in centimeters: 162
Your height is 5.0 feet and 3.7795275590551185 inches

Question 9

Write a program to read a number n and print n2, n3 and n4.

Solution
n = int(input("Enter n: "))
n2, n3, n4 = n ** 2, n ** 3, n ** 4
print("n =", n)
print("n^2 =", n2)
print("n^3 =", n3)
print("n^4 =", n4)
Output
Enter n: 2
n = 2
n^2 = 4
n^3 = 8
n^4 = 16

Question 10

Write a program to find area of a triangle.

Solution
h = float(input("Enter height of the triangle: "))
b = float(input("Enter base of the triangle: "))
area = 0.5 * b * h
print("Area of triangle = ", area)
Output
Enter height of the triangle: 2.5
Enter base of the triangle: 5
Area of triangle =  6.25

Question 11

Write a program to compute simple interest and compound interest.

Solution
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = int(input("Enter time: "))
si = (p * r * t) / 100
ci = p * ((1 + (r / 100 ))** t) - p
print("Simple interest = ", si)
print("Compound interest = ", ci)
Output
Enter principal: 15217.75
Enter rate: 9.2
Enter time: 3
Simple interest =  4200.098999999999
Compound interest =  4598.357987312007

Question 12

Write a program to input a number and print its first five multiples.

Solution
n = int(input("Enter number: "))
print("First five multiples of", n, "are")
print(n, n * 2, n * 3, n * 4, n * 5)
Output
Enter number: 5
First five multiples of 5 are
5 10 15 20 25

Question 13

Write a program to read details like name, class, age of a student and then print the details firstly in same line and then in separate lines. Make sure to have two blank lines in these two different types of prints.

Solution
n = input("Enter name of student: ")
c = int(input("Enter class of student: "))
a = int(input("Enter age of student: "))
print("Name:", n, "Class:", c, "Age:", a)
print()
print()
print("Name:", n)
print("Class:", c)
print("Age:", a)
Output
Enter name of student: Kavya
Enter class of student: 11
Enter age of student: 17
Name: Kavya Class: 11 Age: 17


Name: Kavya
Class: 11
Age: 17

Question 14

Write a program to input a single digit(n) and print a 3 digit number created as <n(n + 1)(n + 2)> e.g., if you input 7, then it should print 789. Assume that the input digit is in range 1-7.

Solution
d = int(input("Enter a digit in range 1-7: "))
n = d * 10 + d + 1
n = n * 10 + d + 2
print("3 digit number =", n)
Output
Enter a digit in range 1-7: 7
3 digit number = 789

Question 15

Write a program to read three numbers in three variables and swap first two variables with the sums of first and second, second and third numbers respectively.

Solution
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print("The three number are", a, b, c)
a, b = a + b, b + c
print("Numbers after swapping are", a, b, c)
Output
Enter first number: 10
Enter second number: 15
Enter third number: 20
The three number are 10 15 20
Numbers after swapping are 25 35 20

Second largest number in java using ternary operator

 //Largest second number using ternary operator public class Main { public static void main(String[] args) { int a=5,b=6,c=7; int ...