Skip to main content

Python top 25 Logical programming interview question & Answer | important python language question and answer ?

😀 Python top 25 Logical programming interview question & Answer. It is very useful for Fresher and  Experience. If you learn this make sure you can get good marks in your exam and interview.

1.Write a program to find Area of Triangle..?

Ans-

a = float(input('Enter first side: '))  

b = float(input('Enter second side: '))  

c = float(input('Enter third side: '))  

   s = (a + b + c) / 2  

  # calculate the area  

area = (s*(s-a)*(s-b)*(s-c)) ** 0.5  

print('The area of the triangle is %0.2f' %area)   

=>Output-

Enter the first side: 5

Enter the second side: 7

Enter the third side: 8

The area of the triangle is 17.32



2.Write a program to check A Leap Year or Not..?

Ans-

year = int(input("Enter a year: "))  

if (year % 4) == 0:  

   if (year % 100) == 0:  

       if (year % 400) == 0:  

           print("{0} is a leap year".format(year))  

       else:  

           print("{0} is not a leap year".format(year))  

   else:  

       print("{0} is a leap year".format(year))  

else:  

   print("{0} is not a leap year".format(year))  


=>Outpou-

Enter a year: 2020

2020 is a leap year


OR


Enter a year: 2021

2021 is not a leap year

3.Write a program to find Factorial of a  number..?

Ans-

num = int(input("Enter a number: "))  

factorial = 1  

if num < 0:  

   print("Sorry, factorial does not exist for negative numbers")  

elif num == 0:  

   print("The factorial of 0 is 1")  

else:  

   for i in range(1,num + 1):  

       factorial = factorial*i  

   print("The factorial of",num,"is",factorial)  


Output-

Enter a number: 20

The factorial of 20 is 2432902008176640000


OR


Enter a number: 10

The factorial of 10 is 3628800

4.Write a program to check Armstrong or not..?

Ans-

num = int(input("Enter a number: "))  

sum = 0  

temp = num  

  

while temp > 0:  

   digit = temp % 10  

   sum += digit ** 3  

   temp //= 10  

  

if num == sum:  

   print(num,"is an Armstrong number")  

else:  

   print(num,"is not an Armstrong number")  


Output-

 

Enter a number: 121

121 is not an Armstrong number


OR


Enter a number: 153

153 is an Armstrong number

5.Write a program to find the sum of Natural Number..?

Ans-

num = int(input("Enter a number: "))  

  

if num < 0:  

   print("Enter a positive number")  

else:  

   sum = 0  

   

   while(num > 0):  

       sum += num  

       num -= 1  

   print("The sum is",sum) 


Output-

Enter a number: 4

The sum is 10


OR


Enter a number: 15

The sum is 120

6.Write a program to find the ASCII value of any character..?

Ans-

a = input("Enter a character: ")  

  

print("The ASCII value of '" + a + "' is",ord(a))  


Output-

Enter a character: b

The ASCII value of 'b' is 98


OR

Enter a character: f

The ASCII value of 'f' is 102

7.Write a program to find Display Calendar..?

Ans-

import calendar


yy = int(input("Enter year: "))  

mm = int(input("Enter month: "))

# display the calendar  

print(calendar.month(yy,mm))  

Output-

Enter year: 2020

Enter month: 10

    October 2020

Mo Tu We Th Fr Sa Su

          1  2  3  4

 5  6  7  8  9 10 11

12 13 14 15 16 17 18

19 20 21 22 23 24 25

26 27 28 29 30 31

8.Write a program to remove Punctuation from a String..?

Ans-

#All Punctuation was taken as an example here.

punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''

 my_str = input("Enter a string: ")  

# remove punctuation from the string

no_punct = ""  

for char in my_str:  

   if char not in punctuation:  

       no_punct = no_punct + char  

print(no_punct)  

Output-

Enter a string: how are you friends, where are you from..?

how are your friends where  are you from

OR

Enter a string: What's your name, where are going? why are you coming!!.

What's your name where are going why are you coming

9.Write a program to sort the elements of an array in ascending order..?

Ans-

arr = [9, 2, 8, 7, 1, 13, 3];     

temp = 0;    

  #Displaying elements of original array    

print("Elements of original array: ");    

for i in range(0, len(arr)):    

    print(arr[i], end=" ");    

#Sort the array in ascending order    

for i in range(0, len(arr)):    

    for j in range(i+1, len(arr)):    

        if(arr[i] > arr[j]):    

            temp = arr[i];    

            arr[i] = arr[j];    

            arr[j] = temp;    

     print();    

print("Elements of array sorted in ascending order: ");    

for i in range(0, len(arr)):    

    print(arr[i], end=" ");    

Output-

Elements of original array: 

9 2 8 7 1 13 3 

Elements of array sorted in ascending order: 

1 2 3 7 8 9 13 

10.Write a program Half pyramid pattern with numbers

Note-Note: In this pattern, The count of numbers on each row is equal to the current row number. In each row, every next number is incremented by 1

Ans-

rows = 5

for row in range(1, rows+1):

    for column in range(1, row + 1):

        print(column, end=' ')

    print("")

Output-

1 2 

1 2 3 

1 2 3 4 

1 2 3 4 5 

11.write a Program to convert temperature in celsius to Fahrenheit

Ans-

# You can change the value for a different result

celsius = 40.7

# calculate fahrenheit

fahrenheit = (celsius * 1.8) + 32

print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

Output-

40.7 degree Celsius is equal to 105.3 degrees Fahrenheit

12.Write a Python program to find the smallest and largest word in a given string...?

Ans-

def smallest_largest_words(str1):

    word = "";

    all_words = [];

    str1 = str1 + " ";

    for i in range(0, len(str1)):

        if(str1[i] != ' '):

            word = word + str1[i];  

        else:

            all_words.append(word);  

            word = "";  

      small = large = all_words[0];  

  #Find the smallest and largest word in the str1  

 for k in range(0, len(all_words)):

        if(len(small) > len(all_words[k])):

            small = all_words[k];

        if(len(large) < len(all_words[k])):

            large = all_words[k];

    return small,large;

str1 = "Write a Python program to sort an array using Quick sort Algorithm.";  

print("Original Strings:\n",str1)

small, large = smallest_largest_words(str1)  

print("Smallest word: " + small);  

print("Largest word: " + large); 

Output-

Original Strings:

Write a Python program to sort an array using Quicksort Algorithm.

Smallest word: a

Largest word: Algorithm.

13.Write a Python program to count Uppercase, Lowercase, special character, and numeric values in a given string..?

Ans-

def count_chars(str):

     upper_ctr, lower_ctr, number_ctr, special_ctr = 0, 0, 0, 0

     for i in range(len(str)):

          if str[i] >= 'A' and str[i] <= 'Z': upper_ctr += 1

          elif str[i] >= 'a' and str[i] <= 'z': lower_ctr += 1

          elif str[i] >= '0' and str[i] <= '9': number_ctr += 1

          else: special_ctr += 1

     return upper_ctr, lower_ctr, number_ctr, special_ctr

    # You can take an example for didrrerent form.       

str = "javaforjob1.blogspot.Com"

print("Original Substrings:",str)

u, l, n, s = count_chars(str)

print('\nUpper case characters: ',u)

print('Lower case characters: ',l)

print('Number case: ',n)

print('Special case characters: ',s)

Output-

Original Substrings: javaforjob1.blogspot.Com

Upper case characters:  1

Lower case characters:  20

Number case:  1

Special case characters:  2

14.Write a Python program to reverse words in a string..?

Ans-

def reverse_string_words(text):

    for line in text.split('\n'):

        return(' '.join(line.split()[::-1]))

    print(reverse_string_words("Welcome to our javaforjob1.blogspot.com in my tutorial"))

print(reverse_string_words("Prince Shahjahan"))

Output-

tutorial my in javaforjob1.blogspot.com our to Welcome

Shahjahan Prince

15.Write a Python program to remove spaces from a given string..?

Ans-

def remove_spaces(str1):

  str1 = str1.replace(' ','')

  return str1

    print(remove_spaces("ja va for job 1"))

print(remove_spaces("a b c d e f"))

Output-

javaforjob1

abcdef

16.Write an example of program Python in Multiple Inheritance..?

Ans-

# Parent class 1

class TeamMember(object):                   

   def __init__(self, name, uid): 

      self.name = name 

      self.uid = uid 

  # Parent class 2

class Worker(object):                 

   def __init__(self, pay, jobtitle): 

      self.pay = pay 

      self.jobtitle = jobtitle 

  # Deriving a child class from the two parent classes

class TeamLeader(TeamMember, Worker):         

   def __init__(self, name, uid, pay, jobtitle, Fresher): 

      self.Fresher = Fresher 

      TeamMember.__init__(self, name, uid) 

      Worker.__init__(self, pay, jobtitle)

      print("Name: {}, Pay: {}, Fresher: {}".format(self.name, self.pay, self.Fresher))

TL = TeamLeader('SHAHJAHAN', 10001, 35000, 'Scrum Master', 1)

Output-

Name: SHAHJAHAN, Pay: 35000, Fresher: 1

17.Write a program in python using polymorphism with the Class method..?

Ans-

class India(): 

    def capital(self): 

        print("New Delhi is the capital of India.") 

  def language(self): 

        print("Hindi is the most widely spoken language of India.") 

   def type(self): 

        print("India is a developing country.") 

  class USA(): 

    def capital(self): 

        print("Washington, D.C. is the capital of USA.") 

  def language(self): 

        print("English is the primary language of the USA.") 

   def type(self): 

        print("USA is a developed country.") 

 obj_ind = India() 

obj_usa = USA() 

for country in (obj_ind, obj_usa): 

    country.capital() 

    country.language() 

    country.type() 

Output-

New Delhi is the capital of India.

Hindi is the most widely spoken language of India.

India is a developing country.

Washington, D.C. is the capital of the USA.

English is the primary language of the USA.

The USA is a developed country.

18.25) Write a Python Program to Count the Number of Digits in a Number..?

Ans-

n=int(input("Enter number:"))

count=0

while(n>0):

count=count+1

n=n//10

print("The number of digits in the number is:",count)

Output:

Enter number:14325

19.Write a Python Program to Find the Second Largest Number in a List..?

Ans-a=[]

n=int(input("Enter number of elements:"))

for i in range(1,n+1):

b=int(input("Enter element:"))

a.append(b)

a.sort()

print("Second largest element is:",a[n-2])

Output:

Enter the number of elements:4

Enter element:23

Enter element:56

Enter element:39

Enter element:11

The second largest element is: 39

20.Write a Python Program to Check Common Letters in Two Input Strings..?

Ans-s1=raw_input("Enter first string:")

s2=raw_input("Enter second string:")

a=list(set(s1)&set(s2))

print("The common letters are:")

for i in a:

print(i)

Output:

Enter first string: Hello

Enter second string: How are you

The common letters are:

H

e

o

21.Write a Python Program to Swap the First and Last Value of a List..?

Ans-a=[]

n= int(input("Enter the number of elements in list:"))

for x in range(0,n):

element=int(input("Enter element" + str(x+1) + ":"))

a.append(element)

temp=a[0]

a[0]=a[n-1]

a[n-1]=temp

print("New list is:")

print(a)

Output:

Enter the number of elements in list:4

Enter element1:23

Enter element2:45

Enter element3:67

Enter element4:89

The new list is:

[89, 45, 67, 23]

The number of digits in the number is: 5

22.Write a Python Program to Print Table of a Given Number..?

Ans-

n=int(input("Enter the number to print the tables for:"))

for i in range(1,11):

print(n,"x",i,"=",n*i)

Output:

Enter the number to print the tables for:7

7 x 1 = 7

7 x 2 = 14

7 x 3 = 21

7 x 4 = 28

7 x 5 = 35

7 x 6 = 42

7 x 7 = 49

7 x 8 = 56

7 x 9 = 63

7 x 10 = 70

23.Write a program to find the sum of the digits of a number in Python..?

Ans-

n=int(input("Enter a number:"))

tot=0

while(n>0):

dig=n%10

tot=tot+dig

n=n//10

print("The total sum of digits is:",tot)

Output:

Enter a number:1928

The total sum of digits is: 20

24.Write a NumPy program to convert a given array into a list and then convert it into a list again..?

Ans-

import numpy as np

a = [[1, 2], [3, 4]]

x = np.array(a)

a2 = x.tolist()

print(a == a2)

Output-

True

25.Write a Pandas program to get the items of a given series not present in another given series...?

Ans-import pandas as pd

sr1 = pd.Series([1, 2, 3, 4, 5])

sr2 = pd.Series([2, 4, 6, 8, 10])

print("Original Series:")

print("sr1:")

print(sr1)

print("sr2:")

print(sr2)

print("\nItems of sr1 not present in sr2:")

result = sr1[~sr1.isin(sr2)]

print(result)

print("Done!")

Output-

Original Series:

sr1:

0    1

1    2

2    3

3    4

4    5

type: int64

sr2:

0     2

1     4

2     6

3     8

4    10

type: int64

Items of sr1 not present in sr2:

0    1

2    3

4    5

type: int64  

Done!              

Thank You?

Comments

Post a Comment

Popular posts from this blog

How to Send OTP in Mobile Number | login with OTP mobile Number | How to send OTP in mobile no with Spring Boot APP

   ðŸ˜‚               Login with Mobile Number OTP ---------------------------------------------------------------------------- If you want to develop a project to log in with OTP mobile Number in Spring Boot Applications then this post for you. In this post, I am going to use some other service to send the OTP in mobile number. we have to use it in this project spring boot. we are going to use Twilio to send SMS. we are going to use a web socket to send the data from the browser to the SMS gateway. Oracle Database for store the user details. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.3.3.RELEASE</version> </dependency> <dependency> <groupId>com.twilio.sdk</grou

Spring Boot With MySQL Database connection with Examples | MySQl Database Configuration with Spring Boot Projects

 ðŸ˜ƒ MySQL Database Configuration with Spring Boot Projects  In this article, we are going to introduce How to connect MySQL Database with the Spring Boot project. pom.xml   <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</gro

How can we create Auto generated field or ID for mongodb using spring boot

😂 How can we create an Auto-generated field or ID for MongoDB using spring boot? First Create One Application Like Mongodb_sequence-id-generator Pom.XML <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>de.flapdoodle.embed</groupId> <artifactId>de.flapdoodle.embed.mongo</artifactId> </dependency> User.java package com.app; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "users_db") public class User { @Transient public static final String SEQUENCE_NAME = &