Python Coding Interview Questions And Answers

Preparing for Python coding interviews? If your answer is yes, then you are right place. 141 Python Coding Interview Questions and Answers will help you crack your following Python code interview.

Here Codingcompiler shares a very good list of 141 Python coding interview questions for freshers and experienced. These Python coding questions are prepared by expert Python developers. If you are a fresher or experienced in Python coding, definitely, these interview questions on Python will help you to refresh your coding knowledge to cross the line in your next Python job interview. All the best for your future and happy python coding.

Table of Contents

Python Coding Interview Questions For Freshers

  1. Write a Python Code to Check if a Number is Odd or Even.
  2. Write a Python code to find the maximum of two numbers.
  3. Write a Python code to check prime numbers.
  4. Write a Python factorial program without using if-else, for, and ternary operators.
  5. Write a Python code to calculate the square root of a given number.
  6. Write a Python code to calculate the area of a triangle.
  7. Write a Python code to check the armstrong number.
  8. Write a Python code to check prime numbers.
  9. Write a Python code to display a multiplication table using for loop.
  10. Write a Python code to swap two variables.

Python Coding Interview Questions For Experienced

  1. How do you debug a Python program?
  2. What is Keyword in Python?
  3. How to convert a list into a string?
  4. How to convert a list into a tuple?
  5. How to convert a list into a set?
  6. How to count the occurrences of a particular element in the list?
  7. What is NumPy array?
  8. How can you create Empty NumPy Array In Python?
  9. What is a negative index in Python?
  10. How do you Concatenate Strings in Python?

Python Basic Coding Interview Questions

1) Write the output for the below Hello, Python commands.

print('Hello, Python!') print("Hello, Python!") print('''Hello, Python!''') print('"Hello, Python"') print("'Hello, Python'")

Output

Hello, Python!
Hello, Python!
Hello, Python!
“Hello, Python!”
‘Hello, Python!’

Explanation: In Python programming, a string can be enclosed inside single quotes, double quotes, or triple quotes.

2) What is the output of the Python add two numbers program?

Python Add Two Numbers Program

#Python Add Two Numbers Program number1 = 5 number2 = 4 # Add two numbers sum = number1 + number2 # Display the sum of the two numbers print('The sum of the two numbers is:' sum)

Output of the program:

File “”, line 7
print(‘The sum of the two numbers is:’ sum)
^
SyntaxError: invalid syntax

The above Python add two numbers program throws SyntaxError because, the comma(,) is missing in print statement. The below print statement will give you the sum of the two numbers.

print('The sum of the two numbers is:', sum)

3) What is the output of the below sum of the two numbers Python program?

num1 = input('Enter first number: ') num2 = input('Enter second number: ') sum = num1 + num2 print('The sum of the numbers is', sum)

The output of the sum of the two numbers program

Enter first number: 15
Enter second number: 10
The sum of the numbers is 1510

Python input() function always converts the user input into a string. Whether you enter an int or float value it will consider it as a string. We need to convert it into number using int() or float() functions. See the below example.

Read the input numbers from users

num1 = input(‘Enter the first number: ‘)
num2 = input(‘Enter the second number: ‘)

Converting and adding two numbers using int() & float() functions

sum = int(num1) + int(num2)
sum2 = float(num1) + float(num2)

Displaying the sum of two numbers

print(‘The sum of and is ’.format(num1, num2, sum))
print(‘The sum of and is ’.format(num1, num2, sum2))

The output of the sum of the two numbers program

Enter the first number: 15
Enter the second number: 10
The sum of 15 and 10 is 25
The sum of 15 and 10 is 25.0

4) Write a Python program to illustrate arithmetic operations (+,-,*,/)?

Here is the Python arithmetic operators program:

# Read the input numbers from users num1 = input('Enter the first number: ') num2 = input('Enter the second number: ') # Converting and adding two numbers using int() & float() functions sum = int(num1) + int(num2) # Subtracting the two numbers sub = int(num1) - int(num2) # Multiplying two numbers mul = float(num1) * float(num2) #Dividing two numbers div = float(num1) / float(num2) # Displaying the results of arithmetic operations print('The sum of and is '.format(num1, num2, sum)) print('The subtration of and is '.format(num1, num2, sub)) print('The multiplication of and is '.format(num1, num2, mul)) print('The division of and is '.format(num1, num2, div))

The output of the Python arithmetic operators program

Enter the first number: 25
Enter the second number: 10
The sum of 25 and 10 is 35
The subtraction of 25 and 10 is 15
The multiplication of 25 and 10 is 250.0
The division of 25 and 10 is 2.5

5) Python Program to Check if a Number is Odd or Even.

#Python program to check if a number is odd or even #To get the input from user num1 = input("Enter a number: ") #Checking whether the entered number is odd or even if (int(num1) % 2) == 0: print(" is Even number".format(num1)) else: print(" is Odd number".format(num1))

The output of the Python odd or even program

Enter a number: 4
4 is Even number

Enter a number: 5
5 is Odd number

6) Write a Python program to find the maximum of two numbers?

Here is the Python program to find the maximum of two numbers:

#To read the input value from the user num1 = input('Enter the first number: ') num2 = input('Enter the second number: ') #Finding the maximum value using Python max() funtion maximum = max(int(num1), int(num2)) #Displaying the maximum number print("The maximum number is: ",maximum)

The output of the Python program to find the maximum number

Enter the first number: 23
Enter the second number: 45
The maximum number is: 45

7) Write a Python program to check prime numbers.

Here is the Python program to check whether a number is prime or not:

# Function to check prime number def PrimeChecking(num): # Condition to check given number is more than 1 if num > 1: # For look to iterate over the given number for i in range(2, int(num/2) + 1): # Condition to check if the given number is divisible if (num % i) == 0: #If divisible by any number it's not a prime number print("The number ",num, "is not a prime number") break # Else print it as a prime number else: print("The number ",num, "is a prime number") # If the given number is 1 else: print("The number ",num, "is not a prime number") # Input function to take the number from user num = int(input("Enter a number to check prime or not: ")) # To print the result, whether a given number is prime or not PrimeChecking(num)

#Output1 of the above Python program to check the prime number

Enter a number to check prime or not: 10
The number 10 is not a prime number

#Output2 of the above Python program to check the prime number

Enter a number to check prime or not: 37
The number 37 is a prime number

8) Write a Python factorial program without using if-else, for, and ternary operators.

Yes, we can write a Python program to find the factorial of a number using in-built Python functions.

math.factorial() function returns the factorial of a given number. Let’s have a look at the Python factorial program using a math function:

# Python program to find factorial of a given number #importing the math function import math #Defining the factorial() function to find factorial def factorial(num): return(math.factorial(num)) # Input function to get the number from user num = int(input('Please enter a number to find the factorial: ')) #Printing the factorial of the given number print("The factorial of the given number", num, "is", factorial(num))

Output1 of the Python factorial program

Please enter a number to find the factorial: 5
The factorial of the given number 5 is 120

The output2 of the Python factorial program

Pleas enter a number to find the factorial: 10
The factorial of the given number 10 is 3628800

9) Write a Python program to calculate the square root of a given number.

Here is the Python Program to calculate the square root:

# Input function to get the input from the user n = float(input('Enter a number: ')) #Formula to calculate the square root of the number n_sqrt = n ** 0.5 #Printing the calculated square root of the given number print('The square root of is '.format(n ,n_sqrt))

Output1 of the Python program to find the square root

Enter a number: 2
The square root of 2.0 is 1.4142135623730951

Output2 of the Python program to find the square root

Enter a number: 4
The square root of 4.0 is 2.0

10) Write a Python program to calculate the area of a triangle.

To calculate the area of a triangle we need the values of side one, side two, side three, and the semi-perimeter. Let’s have a look at the Python area of the triangle program:

# Python Program to find the area of a triangle # Get the 3 sides of a triangle from the user s1 = float(input('Enter first side value: ')) s2 = float(input('Enter second side value:')) s3 = float(input('Enter third-side value:')) #Calculating the semi-perimeter of a triangle sp = (s1 + s2 + s3) / 2 #Calculating the area of a triangle area = (sp*(sp-s1)*(sp-2)*(sp-s3)) ** 0.5 #Printing the area of the triangle print('The area of the triangle is: ', area)

The output of the Python area of the triangle program

Enter first side value: 3
Enter the second side value:4
Enter third-side value:5
The area of the triangle is: 8.48528137423857

11) Write a Python program to check Armstrong’s number.

The armstrong number can be defined as n-digit numbers equal to the sum of the nth powers of their digits are called armstrong numbers.

Armstrong Number Example:

153 is a armstrong number.

n=3 (numbr of digits)

nth powers of the digits – (111), (555), (333)

The number should equal the nth power of their digits, i.e

Other Armstrong Numbers: 153, 370, 371, 407, 1634, 8208, 9474

# python program to check armstrong number #Taking the input from user to check armstrong number num=int(input("Enter the number to check armstrong number: ")) #Assigning the num value to arms arms = num #Finding the length of the number length = len(str(num)) sum1 = 0 #Iterating the values to check armstrong number while num != 0: rem = num % 10 sum1 = sum1+(rem**length) num = num//10 #Printing the result whether the given number is armstrong number or not if arms == sum1: print("The given number", arms, "is armstrong number") else: print("The given number", arms, "is not an armstrong number")

Output1 of the Python armstrong number program

Enter the number to check armstrong number: 153
The given number 153 is armstrong number

Output2 of the Python armstrong number program

Enter the number to check armstrong number: 123
The given number 123 is not an armstrong number

12) Write a Python program to check leap year.

Do you know what is the leap year, it occurs once every 4 years. It contains additional days which makes a year 366 days.

#Python program to check whether the given year is leap year or not # Function implementation to check leap year def LeapYear(Year): #Condition to check if the given year is leap year or not if((Year % 400 == 0) or (Year % 100 != 0) and (Year % 4 == 0)): print("The given Year is a leap year"); # Else it is not a leap year else: print ("The given Year is not a leap year") # Taking an input year from user Year = int(input("Enter the year to check whether a leap year or not: ")) # Printing the leap year result LeapYear(Year)

Output1 of the Python leap year program

Enter the year to check whether a leap year or not: 2020
The given Year is a leap year

Output2 of the Python leap year program

Enter the year to check whether a leap year or not: 2021
The given year is not a leap year

13) Write a Python program to check prime numbers.

A prime number is a positive integer p>1 that has no positive integer divisors other than 1 and p itself.

Example Prime Numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, ….

#Python program to check prime number #Get the input to check whether a number is Prime or not prime_num = int(input("Enter a number to check whether it is prime or not: ")) if prime_num > 1: for i in range(2, int(prime_num/2)+1): if (prime_num % i) == 0: print(prime_num, "is not a prime number") break else: print(prime_num, "is a prime number") else: print(prime_num, "is not a prime number")

Output1 of Python program to check prime number

Enter a number to check whether it is prime or not: 7
7 is a prime number

Output2 of Python program to check prime number

Enter a number to check whether it is prime or not: 10
10 is not a prime number

14) Write a Python program to display a multiplication table using for loop.

Here is the Python program to display the multiplication table of any number using for loop.

#Python program to display multiplication table #Get the number from the user for multipication table tab_number = int(input ("Enter the number of your choice to print the multiplication table: ")) #For loop to iterate the multiplication 10 times and print the table print ("The Multiplication Table of: ", tab_number) for count in range(1, 11): print (tab_number, 'x', count, '=', tab_number * count)

The output of Python multiplication table

Enter the number of your choice to print the multiplication table: 10
The Multiplication Table of: 10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

15) Write a Python program to swap two variables.

Python program to swap two variables.

# Take inputs from the user to swap the two variables num1 = input('Enter the first variable: ') num2 = input('Enter the second variable: ') #Printing the numbers before swap print('The value of num1 before swapping: <>'.format(num1)) print('The value of num2 before swapping: <>'.format(num2)) #Use temporary variable and swap the values temp = num1 num1 = num2 num2 = temp #Printing the numbers after swap print('The value of num1 after swapping: <>'.format(num1)) print('The value of num2 after swapping: <>'.format(num2))

The output of the Python program to swap two numbers:

Enter the first variable: 5
Enter the second variable: 10

The value of num1 before swapping: 5
The value of num2 before swapping: 10

The value of num1 after swapping: 10
The value of num2 after swapping: 5

16) Write a Python program to check if a given number is a Fibonacci number or not.

Here is the Python program to check the Fibonacci number:

#Python progam to check fibonacci number # First two fibonacci terms fib_nums = [0, 1] number = int(input('Enter the number you want to check for fibonacci number: ')) # Iterate fibonacci terms until the user number is reached while fib_nums[-1] is a fibonacci number.') else: print(f'No. is NOT a fibonacci number.')

Output1 of Python program to check Fibonacci number

Enter the number you want to check for fibonacci number: 8
Yes. 8 is a fibonacci number.

Output2 of Python program to check Fibonacci number

Enter the number you want to check for fibonacci number: 10
No. 10 is NOT a fibonacci number.

17) Write a Python program to find the area of a circle.

The formula to find the area of the circle is: Area = pi * r2, where r is the radius of the circle.

Here is the Python program to find the area of the circle.

# Python program to find area of a circle def circ_Area(rad): PI = 3.142 return PI * (rad*rad); rad = float(input('Enter the radius of the circle: ')) print("Area of the circle is %.6f" % circ_Area(rad));

The output of the Python program is to find the area of a circle.

Enter the radius of the circle: 4
The area of the circle is 50.272000

18) Write a Python program to display the calendar.

Python program to display the calendar.

#Python program to display calendar import calendar # Get the month and year from the users year = int(input("Enter the year: ")) month = int(input("Enter the month: ")) # Displaying the calendar for the given year and month print(calendar.month(year,month))

The output of the Python program to display the calendar.

Enter the year: 2022
Enter the month: 10
October 2022
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

19) Write a Python program to find factorial of the given number.

The factorial formual:

5! = 5x4x3x2x1 = 120

# Python program to find factorial of a given number import math def check_Fact(num): return(math.factorial(num)) num = int(input("Enter the number to find factorial:")) fact = check_Fact(num) print("Factorial of the number", num, "is", fact)

The output of the Python factorial program

Enter the number to find factorial:5
Factorial of the number 5 is 120

20) Write a Python program to print all prime numbers in an interval.

Here is the Python program to display all the prime numbers within a range.

# Python program to print all prime number in an interval def disp_Prime(num1, num2): prime_List = [] for i in range(num1, num2): if i == 0 or i == 1: continue else: for j in range(2, int(i/2)+1): if i % j == 0: break else: prime_List.append(i) return prime_List # Driver program starting_Num = int(input('Enter the starting range: ')) ending_Num = int(input('Enter the ending range: ')) lst = disp_Prime(starting_Num, ending_Num) if len(lst) == 0: print("There are no prime numbers in this range") else: print("The prime numbers in the given range are: ", lst)

The output of Python prime numbers display program

Enter the starting range: 5
Enter the ending range: 25
The prime numbers in this range are: [5, 7, 11, 13, 17, 19, 23]

Python Strings Interview Questions & Answers

21) Write a Python Program to Find Vowels From a String.

Python Program to Find Vowels From a String

This Python coding example returns the vowels “a e i o u” present in a string. This Python program is useful when finding vowels, Let’s try this and see how it works.

#Python Program to Find Vowels From a String #defining a function def get_vowels(String): return [each for each in String if each in "aeiou"] get_string1 = "hello" # ['e', 'o'] get_string2 = "python is fun" # ['o', 'i', 'u'] get_string3 = "coding compiler" # ['o', 'i', 'o', 'i', 'e'] get_string4 = "12345xyz" # [] #Let's print vowels from the given strigns #Vowels from first string print("The Vowels Are: ",get_vowels(get_string1)) #Vowels from second string print("The Vowels Are: ",get_vowels(get_string2)) #Vowels from third string print("The Vowels Are: ",get_vowels(get_string3)) #Vowels from fourth string print("The Vowels Are: ",get_vowels(get_string4))

The output of the above Python code:

The Vowels Are: [‘e’, ‘o’]
The Vowels Are: [‘o’, ‘i’, ‘u’]
The Vowels Are: [‘o’, ‘i’, ‘o’, ‘i’, ‘e’]
The Vowels Are: []

22) Write a Python Program to Convert Comma Separated List to a String.

Python Program to Convert Comma Separated List to a String

In this Python coding example we use the join() method to convert comma separated list to a string. Let’s try this Python program and see how it works.

# Python program to converting a comma separated list to a string #comma seperated list favorite_prog = ["Python", "SQL", "GO"] #The join() method takes all items from the favorite_prog list and joins them into one string. print("What is your favorite programming language:", ", ".join(favorite_prog))

The output of the above Python code:

What is your favorite programming language: Python, SQL, GO

23) Write a Python Program to Capitalize the First Letter of a String.

Python program to convert every first letter of the characters in a string to an uppercase.

This Python coding example capitalizes every first letter of the characters in a string. This Python program is useful when converting the first letter of a string to a capital letter, Let’s try this and see how it works.

#Python Program to Capialize the First Letter of a String #defining a capitalize function def capitalize(String): return String.title() get_capital1 = "hello" # [Hello] get_capital2 = "python programming" # [Python Programming] get_capital3 = "python is easy to learn" # [Python Is Easy To Learn] #Let's print capitalized string from the given strigns #Capitalized string from first string print("The Capitalized String Is: ",capitalize(get_capital1)) #Capitalized string from second string print("The Capitalized String Is: ",capitalize(get_capital2)) #Capitalized string from third string print("The Capitalized String Is: ",capitalize(get_capital3))

The output of the above Python code:

The Capitalized String Is: Hello
The Capitalized String Is: Python Programming
The Capitalized String Is: Python Is Easy To Learn

Python Implicit/Explicit Type Conversion Interview Questions

24) Write a Python Program to Implicit Type Conversion.

Python Program to Demonstrate Implicit Type Conversion.

This Python coding example explains implicit type conversion in Python. This Python program is useful when working with different data types and conversions. Let’s try this and see how it works.

#Implicit type casting example get_num1 = 199 #int get_num2 = 1.25 #float get_num3 = get_num1 + get_num2 #int+float=? print("Datatype of get_num1:",type(get_num1)) print("Datatype of get_num2:",type(get_num2)) print("The value of get_num3 is:",get_num3) print("Datatype of get_num3:",type(get_num3)) #Implicit conversion - Python always converts smaller data types to larger data types to avoid the loss of data.

The output of the above Python code:

Datatype of get_num1:
Datatype of get_num2:

The value of get_num3 is: 200.25
Datatype of get_num3:

25) What’s the Output of this Python program?

Let’s find out what’s the output of the below Python program.

#Let's find out what's the output of the below Python program. #Implicit type casting example num1 = 123 num2 = "456" print("Data type of num_int:",type(num1)) print("Data type of num_str:",type(num2)) print("num1 data type is:",type(num1 + num2))

The output of the above Python code:

Data type of num_int:
Data type of num_str:
Traceback (most recent call last):
File “”, line 11, in
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Python is not able to convert string type to integer type implicitly. So we can see TypeError in output.

26) Write a Python Program to Explicit Type Conversion.

Python Program to Demonstrate Explicit Type Conversion.

Python coding example explains explicit type conversion in Python. This Python program is useful when working with different data types and conversions. Let’s try this Python code and see how it works.

#Python Program to Demonstrate Explicit Type Conversion #Explicit type casting example num1 = 123 num2 = "456" print("Datatype of num1:",type(num1)) print("Datatype of num2 before Type Casting:",type(num2)) #Convertion of num2 from string(higher) to integer(lower) type using int() function to perform the addition between num1 and num2. num2 = int(num2) print("Datatype of num2 after Type Casting:",type(num2)) num3 = num1 + num2 print("Sum of num1 and num2:",num3) print("Data type of the num3:",type(num3))

The output of the above Python code:

Datatype of num1:
Datatype of num2 before Type Casting:

Datatype of num2 after Type Casting:

Sum of num1 and num2: 579
Data type of the num3:

Python Namespace Coding Interview Questions

27) What’s the Output of this Python Namespace program?

Python Namespace Program.

#Python Namespace Program Example def outer_function(): num = 20 def inner_function(): num = 30 print('num =', num) inner_function() print('num =', num) num = 10 outer_function() print('num =', num)

The output of the above Python code:

Three different variables “num” are defined in separate namespaces and accessed accordingly.

num = 30
num = 20
num = 10

28) What’s the Output of this Python program?

Python Namespace Program.

#Python Namespace Program Example def outer_function(): global num num = 20 def inner_function(): global num num = 30 print('num =', num) inner_function() print('num =', num) num = 10 outer_function() print('num =', num)

The output of the above Python code:

All references and assignments are to the global ‘num’ due to the use of the keyword ‘global’.

num = 30
num = 30
num = 30

29) What does this do, and why should one include the if statement?

Explain what the below Python program does.

if __name__ == "__main__": print("Hello, World!")

Answer#

It’s boilerplate code that protects users from accidentally invoking the script when they didn’t intend to. Here are some common problems when the guard is omitted from a script:

If you import the guardless script in another script (e.g. import my_script_without_a_name_eq_main_guard), then the latter script will trigger the former to run at import time and use the second script’s command line arguments. This is almost always a mistake.

If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.

Example Python Code:

Create the following two files:

# a.py import b # b.py print("__name__ equals " + __name__) if __name__ == '__main__': print("if-statement was executed") Now run each file individually. Running python a.py: $ python a.py __name__ equals b When a.py is executed, it imports the module b. This causes all the code inside b to run. Python sets globals()['__name__'] in the b module to the module's name, b. #Running python b.py: $ python b.py __name__ equals __main__

if-statement was executed, when only the file b.py is executed, Python sets globals()[‘name‘] in this file to “main“. Therefore, the if statement evaluates to True this time.

30) What does __all__ mean in Python?

Answer#

It’s a list of public objects of that module, as interpreted by import *. It overrides the default of hiding everything that begins with an underscore.

Example Python Code:

Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from import * is used on the module.

For example, the following code in a foo.py explicitly exports the symbols bar and baz:

__all__ = ['bar', 'baz'] waz = 5 bar = 10 def baz(): return 'baz' # These symbols can then be imported like so: from foo import * print(bar) print(baz) # The following will trigger an exception, as "waz" is not exported by the module print(waz)

If the __all__ above is commented out, this code will then execute to completion, as the default behavior of import * is to import all symbols that do not begin with an underscore, from the given namespace.

NOTE: __all__ affects the from import * behavior only. Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from import .

31) How to create a namespace package in Python?

In Python, a namespace package allows you to spread Python code among several projects. This is useful when you want to release related libraries as separate downloads. For example, with the directories Package-1 and Package-2 in PYTHONPATH,

Package-1/namespace/__init__.py Package-1/namespace/module1/__init__.py Package-2/namespace/__init__.py Package-2/namespace/module2/__init__.py the end-user can import namespace.module1 and import namespace.module2.

What’s the best way to define a namespace package so more than one Python product can define modules in that namespace?

Answer#

On Python 3.3 you don’t have to do anything, just don’t put any __init__.py in your namespace package directories and it will just work. On pre-3.3, choose the pkgutil.extend_path() solution over the pkg_resources.declare_namespace() one, because it’s future-proof and already compatible with implicit namespace packages.

Python 3.3 introduces implicit namespace packages.

This means there are now three types of objects that can be created by an import foo:

A module represented by a foo.py file
A regular package, represented by a directory foo containing an __init__.py file
A namespace package, represented by one or more directories foo without any __init__.py files

32) How to create a Python namespace (argparse.parse_args value)?

To interactively test my python script, I would like to create a Namespace object, similar to what would be returned by argparse.parse_args(). The obvious way,

>>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.parse_args() Namespace() >>> parser.parse_args("-a") usage: [-h] : error: unrecognized arguments: - a

Process Python exited abnormally with code 2 may result in Python repl exiting (as above) on a silly error.

So, what is the easiest way to create a Python namespace with a given set of attributes?

E.g., I can create a dict on the fly (dict([(“a”,1),(“b”,”c”)])) but I cannot use it as a Namespace:

AttributeError: ‘dict’ object has no attribute ‘a’

Answer#

#You can create a simple class: class Namespace: def __init__(self, **kwargs): self.__dict__.update(kwargs) #and it'll work the exact same way as the argparse Namespace class when it comes to attributes: >>> args = Namespace(a=1, b='c') >>> args.a 1 >>> args.b 'c' #Alternatively, just import the class; it is available from the argparse module: from argparse import Namespace args = Namespace(a=1, b='c') As of Python 3.3, there is also types.SimpleNamespace, which essentially does the same thing: >>> from types import SimpleNamespace >>> args = SimpleNamespace(a=1, b='c') >>> args.a 1 >>> args.b 'c'

The two types are distinct; SimpleNamespace is primarily used for the sys.implementation attribute and the return value of time.get_clock_info().

33) What does __import__('pkg_resources').declare_namespace(__name__) do?

In some init.py files of modules I saw such single line:

import(‘pkg_resources’).declare_namespace(name)

What does it do and why people use it? Suppose it’s related to dynamic importing and creating namespace at runtime.

Answer#

Here are two things:

1) __import__ is a Python function that will import a package using a string as the name of the package. It returns a new object that represents the imported package. So foo = __import__(‘bar’) will import a package named bar and store a reference to its objects in a local object variable foo.

2 From setup utils pkg_resources’ documentation, declare_namespace() “Declare[s] that the dotted package name is a “namespace package” whose contained packages and modules may be spread across multiple distributions.”

So __import__(‘pkg_resources’).declare_namespace(__name__) will import the ‘pkg_resources’ package into a temporary and call the declare_namespace function stored in that temporary (the __import__ function is likely used rather than the import statement so that there is no extra symbol left over named pkg_resources). If this code were in my_namespace/__init__.py, then __name__ is my_namespace and this module will be included in the my_namespace namespace package.

34) What exactly does “import *” import?

In Python, what exactly does import * import? Does it import __init__.py found in the containing folder?

For example, is it necessary to declare from project.model import __init__, or is from project.model import * sufficient?

Answer#

The “advantage” of from xyz import * as opposed to other forms of import is that it imports everything (well, almost… [see (a) below] everything) from the designated module under the current module. This allows using the various objects (variables, classes, methods…) from the imported module without prefixing them with the module’s name.

#For example >>> from math import * >>>pi 3.141592653589793 >>>sin(pi/2) >>>1.0

35) Why is “import *” bad in Python?

It is recommended to not to use import * in Python.

Can you please share the reason for that?

Answer#

Because it puts a lot of stuff into your namespace (might shadow some other object from the previous import and you won’t know about it).

Because you don’t know exactly what is imported and can’t easily find from which module a certain thing was imported (readability).

Because you can’t use cool tools like pyflakes to statically detect errors in your code.

36) What are Python namespaces and explain how to use namespaces & how this feature makes programming better?

Answer#

Namespace is a way to implement scope.

In Java (or C) the compiler determines where a variable is visible through static scope analysis.

In C, scope is either the body of a function or it’s global or it’s external. The compiler reasons this out for you and resolves each variable name based on scope rules. External names are resolved by the linker after all the modules are compiled.

In Java, scope is the body of a method function, or all the methods of a class. Some class names have a module-level scope, also. Again, the compiler figures this out at compile time and resolves each name based on the scope rules.

In Python, each package, module, class, function and method function owns a “namespace” in which variable names are resolved. Plus there’s a global namespace that’s used if the name isn’t in the local namespace.

Each variable name is checked in the local namespace (the body of the function, the module, etc.), and then checked in the global namespace.

Variables are generally created only in a local namespace. The global and nonlocal statements can create variables in other than the local namespace.

When a function, method function, module or package is evaluated (that is, starts execution) a namespace is created. Think of it as an “evaluation context”. When a function or method function, etc., finishes execution, the namespace is dropped. The variables are dropped. The objects may be dropped, also.

37) Is it a good idea to use the class as a namespace in Python?

Answer#

Yes, indeed. You can use Python classes strictly for namespacing as that is one of the special things they can do and do differently than modules. It’s a lot easier to define a class as a namespace inline in a file than to generate more files.

You should not do it without commenting on your code saying what it’s for. Python classes come in a lot of different forms and purposes and this makes it difficult to understand code you have not seen before.

A Python class used as a namespace is no less a Python class than one that meets the perception of what a class is in other languages. Python does not require a class to be instantiated to be useful. It does not require ivars and does not require methods. It is fairly flexible.

Classes can contain other classes too.

Lots of people have their ideas about what is or isn’t Pythonic. But if they were all worried about something like consistency, they’d push to have things like len() dir(), and help() be a method of objects rather than a global function.

38) Is it possible to add an object to the global namespace, for example, by using globals() or dir()?

def insert_into_global_namespace(var_name, value): globals()[var_name] = value insert_into_global_namespace('my_obj', 'an object') print(f'my_obj = ') #But this only works in the current module.

Answer#

#It is as simple as globals()['var'] = "an object" and/or def insert_into_namespace(name, value, name_space=globals()): name_space[name] = value insert_into_namespace("var", "an object") # Remark that globals is a built-in keyword, that is, 'globals' in __builtins__.__dict__ evaluates to True.

39) What’s the python __all__ module level variable for?

Answer#

It has two purposes:

Anybody who reads the source will know what the exposed public API is. It doesn’t prevent them from poking around in private declarations but does provide a good warning not to.

When using from mod import *, only names listed in __all__ will be imported. This is not as important, in my opinion, because importing everything is a really bad idea.

40) Is it possible to call static method from within class without qualifying the name in Python?

class MyClass: @staticmethod def foo(): print "hi" @staticmethod def bar(): MyClass.foo()

Is there a way to make this work without naming MyClass in the call? i.e. so I can just say foo() on the last line?

Answer#

There is no way to use foo and get what you want. There is no implicit class scope, so foo is either a local or a global, neither of which you want.

You might find classmethods more useful:

class MyClass: @classmethod def foo(cls): print "hi" @classmethod def bar(cls): cls.foo() #This way, at least you don't have to repeat the name of the class.

Object-Oriented Python Coding Interview Questions

41) What is the output of the below (__class__.__name__) Object Oriented Python code?

class Programming: def name(self, name): return name p = Programming() print(p.__class__.__name__)

#Output

42) What’s the output of the below (type().__name__) Python code?

class Programming: def name(self, name): return name p = Programming() print(type(p).__name__)

#Output

43) What does super() do in Python? The difference between super().__init__() and explicit superclass __init__()?

#What's the difference between: class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() and: class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self)

I’ve seen super being used quite a lot in classes with only single inheritance. I can see why you’d use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.

#Output

super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven’t already.

Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(ChildB, self).__init__() which IMO is quite a bit nicer.

What’s the difference?

SomeBaseClass.__init__(self)
means to call SomeBaseClass’s __init__. while

super().__init__()
means to call a bound __init__ from the parent class that follows SomeBaseClass’s child class (the one that defines this method) in the instance’s Method Resolution Order (MRO).

If the instance is a subclass of this child class, there may be a different parent that comes next in the MRO.

Explained simply
When you write a class, you want other classes to be able to use it. super() makes it easier for other classes to use the class you’re writing.

Good architecture allows you to postpone decision-making as long as possible.

super() can enable that sort of architecture.

When another class subclasses the class you wrote, it could also be inherited from other classes. And those classes could have an __init__ that comes after this __init__ based on the ordering of the classes for method resolution.

Without super you would likely hard-code the parent of the class you’re writing (like the example does). This would mean that you would not call the next __init__ in the MRO, and you would thus not get to reuse the code in it.

If you’re writing your own code for personal use, you may not care about this distinction. But if you want others to use your code, using super is one thing that allows greater flexibility for users of the code.

Python 2 versus 3
This works in Python 2 and 3:

super(Child, self).__init__()
This only works in Python 3:

super().__init__()

It works with no arguments by moving up in the stack frame and getting the first argument to the method (usually self for an instance method or cls for a class method – but could be other names) and finding the class (e.g. Child) in the free variables (it is looked up with the name class as a free closure variable in the method).

44) How to create static class variables or methods in Python?

Answer#

Variables declared inside the class definition, but not inside a method are class or static variables:

>>> class MyClass: . i = 3 . >>> MyClass.i 3 #This creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have >>> m = MyClass() >>> m.i = 4 >>> MyClass.i, m.i >>> (3, 4)

This is different from C++ and Java, but not so different from C#, where a static member can’t be accessed using a reference to an instance.

45) Why do Python classes inherit object?

Why does the following class declaration inherit from object?

Answer#

#Python 3 class MyClass(object): = New-style class class MyClass: = New-style class (implicitly inherits from object) #Python 2 class MyClass(object): = New-style class class MyClass: = OLD-STYLE CLASS

Explanation:

When defining base classes in Python 3.x, you’re allowed to drop the object from the definition. However, this can open the door for a seriously hard-to-track problem…

Python introduced new-style classes back in Python 2.2, and by now old-style classes are really quite old.

46) What is the purpose of the ‘ self ‘ parameter in Python? Why is it needed?

#Consider this example: class MyClass: def func(self, name): self.name = name

Answer#

The reason you need to use self. is because Python does not use a special syntax to refer to instance attributes.

Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.

That makes methods entirely the same as functions and leaves the actual name to use up to you (although the self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it’s just another object.

Python could have done something else to distinguish normal names from attributes — special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different — but it didn’t.

Python’s all for making things explicit, making it obvious what’s what, and although it doesn’t do it entirely everywhere, it does do it for instance attributes.

That’s why assigning to an instance attribute needs to know what instance to assign to, and that’s why it needs self..

#Example: Let's say you have a class ClassA which contains a method methodA defined as: def methodA(self, arg1, arg2): # do something #and ObjectA is an instance of this class. #Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as: ClassA.methodA(ObjectA, arg1, arg2) #The self variable refers to the object itself.

47) What is the difference between old-style and new-style classes in Python?

Answer#

Up to Python 2.1, old-style classes were the only flavor available to the user.

The concept of the (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.class designates the class of x, but type(x) is always .

This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called an instance.

New-style classes were introduced in Python 2.2 to unify the concepts of class and type. A new-style class is simply a user-defined type, no more, no less.

If x is an instance of a new-style class, then type(x) is typically the same as x.class (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.class).

The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model.

It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of “descriptors”, which enable computed properties.

For compatibility reasons, classes are still old-style by default.

New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the “top-level type” object if no other parent is needed.

The behavior of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns.

Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are “fixes” that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritances.

Python 3 only has new-style classes.

No matter if you subclass from the object or not, classes are new-style in Python 3.

Declaration-wise:

New-style classes inherit from an object, or from another new-style class.

class AnotherNewStyleClass(NewStyleClass):
pass
Old-style classes don’t.

Python 3 Note:

Python 3 doesn’t support old-style classes, so either form noted above results in a new-style class.

48) How to call a parent class’s method from a child class in Python?

Answer#

#Use the super() function: class Foo(Bar): def baz(self, **kwargs): return super().baz(**kwargs) #For Python < 3, you must explicitly opt in to using new-style classes and use: class Foo(Bar): def baz(self, arg): return super(Foo, self).baz(arg)

Example: super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.

The search order is the same as that used by getattr() except that the type itself is skipped.

class A(object): # deriving from 'object' declares A as a 'new-style-class' def foo(self): print "foo" class B(A): def foo(self): super(B, self).foo() # calls 'A.foo()' myB = B() myB.foo()

49) How to print instances of a class using print() in Python?

When I try to print an instance of a class, I get an output like this:

>>> class Test(): . def __init__(self): . self.a = 'foo' . >>> print(Test())

How can I define the printing behavior (or the string representation) of a class and its instances?

For example, referring to the above code, how can I modify the Test class so that printing an instance shows the value?

Answer#

>>> class Test: . def __repr__(self): . return "Test()" . def __str__(self): . return "member of Test" . >>> t = Test() >>> t Test() >>> print(t) member of Test

The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

50) What is the difference between __init__ and __call__?

I want to know the difference between __init__ and __call__ methods.

#For example: class test: def __init__(self): self.a = 10 def __call__(self): b = 20

Answer#

So, the __init__ method is used when the class is called to initialize the instance, while the __call__ method is called when the instance is called.

Example:

The __init__ is used to initialize newly created object, and receives arguments used to do that:

class Foo: def __init__(self, a, b, c): # . x = Foo(1, 2, 3) # __init__ #The __call__ implements function call operator. class Foo: def __call__(self, a, b, c): # . x = Foo() x(1, 2, 3) # __call__

Python OOP Coding Interview Questions

51) What are meta classes in Python?

Answer#

A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.

While in Python you can use arbitrary callables for metaclasses (like Jerub shows), the better approach is to make it an actual class itself. type is the usual metaclass in Python. type is itself a class, and it is its own type. You won’t be able to recreate something like type purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass type.

A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the ‘class’ statement) by calling the metaclass.

Combined with the normal __init__ and __new__ methods, metaclasses, therefore, allow you to do ‘extra things’ when creating a class, like registering the new class with some registry or replacing the class with something else entirely.

When the class statement is executed, Python first executes the body of the class statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be.

The metaclass is determined by looking at the base classes of the class-to-be (metaclasses are inherited), at the metaclass attribute of the class-to-be (if any) or the __metaclass__ global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.

However, metaclasses actually define the type of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass.

These metaclass-methods are like class methods in that they can be called on the class without an instance, but they are also not like class methods in that they cannot be called on an instance of the class. type.__subclasses__() is an example of a method on the type metaclass.

You can also define the normal ‘magic’ methods, like __add__, __iter__, and __getattr__, to implement or change how the class behaves.

The __metaclass__ attribute

In Python 2, you can add a __metaclass__ attribute when you write a class (see next section for the Python 3 syntax):

class Foo(object):
__metaclass__ = something…
[…]

If you do so, Python will use the metaclass to create the class Foo.

Metaclasses in Python 3

The syntax to set the metaclass has been changed in Python 3:

class Foo(object, metaclass=something):

i.e. the metaclass attribute is no longer used, in favor of a keyword argument in the list of base classes.

The behavior of metaclasses however stays largely the same.

One thing added to metaclasses in Python 3 is that you can also pass attributes as keyword-arguments into a metaclass, like so:

class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2):

52) What is the difference between @staticmethod and @classmethod in Python?

Answer#

A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python — you can just use a module function instead of a staticmethod.

A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument.

This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved.

Observe for instance how dict.fromkeys(), a classmethod, returns an instance of the subclass when called on a subclass:

>>> class DictSubclass(dict): . def __repr__(self): . return "DictSubclass" . >>> dict.fromkeys("abc") >>> DictSubclass.fromkeys("abc") DictSubclass >>>

53) What is the meaning of single and double underscore before an object name in Python?

Answer#

Single Underscore – In a class, names with a leading underscore indicate to other programmers that the attribute or method is intended to be used inside that class.

However, privacy is not enforced in any way. Using leading underscores for functions in a module indicates it should not be imported from somewhere else.

From the PEP-8 style guide:

_single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose name starts with an underscore.

Double Underscore (Name Mangling)

From the Python docs:

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

And a warning from the same page:

Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class.

Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.

Example:

>>> class MyClass(): . def __init__(self): . self.__superprivate = "Hello" . self._semiprivate = ", world!" . >>> mc = MyClass() >>> print mc.__superprivate Traceback (most recent call last): File "", line 1, in AttributeError: myClass instance has no attribute '__superprivate' >>> print mc._semiprivate , world! >>> print mc.__dict__

54) What are the differences between type() and isinstance() in Python?

Answer#

isinstance caters for inheritance (an instance of a derived class is an instance of a base class, too), while checking for equality of type does not (it demands identity of types and rejects instances of subtypes, AKA subclasses).

Normally, in Python, you want your code to support inheritance, of course (since inheritance is so handy, it would be bad to stop code using yours from using it!), so isinstance is less bad than checking identity of types because it seamlessly supports inheritance.

#Using type: import types if type(a) is types.DictType: do_something() if type(b) in types.StringTypes: do_something_else() #Using isinstance: if isinstance(a, dict): do_something() if isinstance(b, str) or isinstance(b, unicode): do_something_else()

55) What is a mixin and why is it useful in Python?

Answer#

A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:

1)You want to provide a lot of optional features for a class.
2) You want to use one particular feature in a lot of different classes.

For an example of number one, consider werkzeug’s request and response system. I can make a plain old request object by saying:

from werkzeug import BaseRequest class Request(BaseRequest): pass

If I want to add accept header support, I would make that

from werkzeug import BaseRequest, AcceptMixin class Request(AcceptMixin, BaseRequest): pass

If I wanted to make a request object that supports accept headers, etags, authentication, and user agent support, I could do this:

from werkzeug import BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthenticationMixin class Request(AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthenticationMixin, BaseRequest): pass

The difference is subtle, but in the above examples, the mixin classes weren’t made to stand on their own. In more traditional multiple inheritance, the AuthenticationMixin (for example) would probably be something more like Authenticator. That is, the class would probably be designed to stand on its own.

56) What is the purpose of __slots__ in Python?

Answer#

The special attribute __slots__ allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:

1) faster attribute access.
2) space savings in memory.

The space savings is from

1) Storing value references in slots instead of __dict__.
2) Denying __dict__ and __weakref__ creation if parent classes deny them and you declare __slots__.

Quick Caveats

A small caveat, you should only declare a particular slot one time in an inheritance tree.

class Base: __slots__ = 'foo', 'bar' class Right(Base): __slots__ = 'baz', class Wrong(Base): __slots__ = 'foo', 'bar', 'baz' # redundant foo and bar

Python doesn’t object when you get this wrong (it probably should), problems might not otherwise manifest, but your objects will take up more space than they otherwise should. Python 3.8:

>>> from sys import getsizeof >>> getsizeof(Right()), getsizeof(Wrong()) (56, 72) #This is because the Base's slot descriptor has a slot separate from the Wrong's. This shouldn't usually come up, but it could: >>> w = Wrong() >>> w.foo = 'foo' >>> Base.foo.__get__(w) Traceback (most recent call last): File "", line 1, in AttributeError: foo >>> Wrong.foo.__get__(w) 'foo'

The biggest caveat is for multiple inheritance – multiple “parent classes with nonempty slots” cannot be combined.

To accommodate this restriction, follow best practices: Factor out all but one or all parents’ abstraction which their concrete class respectively and your new concrete class collectively will inherit from – giving the abstraction(s) empty slots (just like abstract base classes in the standard library).

57) What does ‘super’ do in Python? What is the difference between super().__init__() and explicit superclass __init__()?

Answer#

The benefits of super() in single-inheritance are minimal — mostly, you don’t have to hard-code the name of the base class into every method that uses its parent methods.

However, it’s almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child and a mixin, their code would not work properly.

What’s the difference?

SomeBaseClass.__init__(self) means to call SomeBaseClass's __init__. while super().__init__()

means to call a bound init from the parent class that follows SomeBaseClass’s child class (the one that defines this method) in the instance’s Method Resolution Order (MRO).

If the instance is a subclass of this child class, there may be a different parent that comes next in the MRO.

When you write a class, you want other classes to be able to use it. super() makes it easier for other classes to use the class you’re writing.

As Bob Martin says, the good architecture allows you to postpone decision-making as long as possible.

super() can enable that sort of architecture.

When another class subclasses the class you wrote, it could also be inheriting from other classes. And those classes could have an __init__ that comes after this __init__ based on the ordering of the classes for method resolution.

Without super you would likely hard-code the parent of the class you’re writing (like the example does). This would mean that you would not call the next __init__ in the MRO, and you would thus not get to reuse the code in it.

If you’re writing your own code for personal use, you may not care about this distinction. But if you want others to use your code, using super is one thing that allows greater flexibility for users of the code.

Python 2 versus 3

#This works in Python 2 and 3: super(Child, self).__init__() #This only works in Python 3: super().__init__()

It works with no arguments by moving up in the stack frame and getting the first argument to the method (usually self for an instance method or cls for a class method – but could be other names) and finding the class (e.g. Child) in the free variables (it is looked up with the name __class__ as a free closure variable in the method).

58) Explain the ‘__enter__’ and ‘__exit__’ methods in Python?

Answer#

Using these magic methods (__enter__, __exit__) allows you to implement objects which can be used easily with the with statement.

The idea is that it makes it easy to build code which needs some ‘cleandown’ code executed (think of it as a try-finally block).

A useful example could be a database connection object (which then automagically closes the connection once the corresponding ‘with’-statement goes out of scope):

class DatabaseConnection(object): def __enter__(self): # make a database connection and return it . return self.dbconn def __exit__(self, exc_type, exc_val, exc_tb): # make sure the dbconnection gets closed self.dbconn.close() .

As explained above, use this object with the with statement (you may need to do from future import with_statement at the top of the file if you’re on Python 2.5).

with DatabaseConnection() as mydbconn:
# do stuff
PEP343 — The ‘with’ statement’ has a nice writeup as well.

59) How do I implement interfaces in Python?

Answer#

Interfaces are not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you must have interfaces in Java, you don’t have to have them in Python.

That said, there are still several uses for interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. They are useful, if you want to make base classes that cannot be instantiated, but provide a specific interface or part of an implementation.

Another usage is if you somehow want to specify that an object implements a specific interface, and you can use ABC’s for that too by subclassing from them. Another way is zope.interface, a module that is a part of the Zope Component Architecture, a really awesomely cool component framework.

Here you don’t subclass from the interfaces, but instead mark classes (or even instances) as implementing an interface. This can also be used to look up components from a component registry. Supercool!

60) How to invoke the super constructor in Python?

class A: def __init__(self): print("world") class B(A): def __init__(self): print("hello") B() # output: hello

In all other languages I’ve worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect super(self) but this doesn’t work.

Answer#

there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:

Python-3.x

class A(object): def __init__(self): print("world") class B(A): def __init__(self): print("hello") super().__init__()

Python-2.x

In python 2.x, you have to call the slightly more verbose version super(, self), which is equivalent to super() as per the docs.

class A(object): def __init__(self): print "world" class B(A): def __init__(self): print "hello" super(B, self).__init__()

Python Functions Coding Interview Questions

61) How to get a function name as a string in Python?

def foo(): pass >>> name_of(foo) "foo"

Answer#

my_function.__name__

Using __name__ is the preferred method as it applies uniformly. Unlike func_name, it works on built-in functions as well:

>>> import time >>> time.time.func_name Traceback (most recent call last): File "", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'func_name' >>> time.time.__name__ 'time'

Also, the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a __name__ attribute too, so you only have to remember one special name.

62) What is the naming convention in Python for variables and functions?

Answer#

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.

The Google Python Style Guide has the following convention:

module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name.

A similar naming scheme should be applied to a CLASS_CONSTANT_NAME

63) How are Python lambdas useful?

Answer#

lambda x: x*2 + 2x – 5

Those things are actually quite useful. Python supports a style of programming called functional programming where you can pass functions to other functions to do stuff. Example:

mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])

sets mult3 to [3, 6, 9], those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than

def filterfunc(x): return x % 3 == 0 mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])

Of course, in this particular case, you could do the same thing as a list comprehension:

mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]

(or even as range(3,10,3)), but there are many other, more sophisticated use cases where you can’t use a list comprehension and a lambda function may be the shortest way to write something out.

Returning a function from another function

def transform(n): … return lambda x: x + n … f = transform(3) f(4) 7

This is often used to create function wrappers, such as Python’s decorators.

Combining elements of an iterable sequence with reduce()

reduce(lambda a, b: ‘<>, <>’.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9])
‘1, 2, 3, 4, 5, 6, 7, 8, 9’

Sorting by an alternate key

sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x))
[5, 4, 6, 3, 7, 2, 8, 1, 9]

I use lambda functions on a regular basis. It took me a while to get used to them, but eventually, I came to understand that they’re a very valuable part of the language.

lambda is just a fancy way of saying function. Other than its name, there is nothing obscure, intimidating, or cryptic about it. When you read the following line, replace lambda with function in your mind:

f = lambda x: x + 1
f(3)
4

It just defines a function of x. Some other languages, like R, say it explicitly:

Do you see? It’s one of the most natural things to do in programming.

64) How do I call a function from another .py file?

file.py contains a function named function. How do I import it?

from file.py import function(a,b)

The above gives an error:

ImportError: No module named ‘file.py’; file is not a package

Answer#

First, import function from file.py:

from the file import function

Later, call the function using:

Note that if you’re trying to import functions from a.py to a file called b.py, you will need to make sure that a.py and b.py are in the same directory.

65) How to determine function name from within that function (without using traceback) in Python?

In Python, without using the traceback module, is there a way to determine a function’s name from within that function?

Say I have a module foo with a function bar. When executing foo.bar(), is there a way for bar to know bar’s name? Or better yet, foo.bar’s name?

#foo.py def bar(): print "my name is", __myname__ # 

Answer#

import inspect def foo(): print(inspect.stack()[0][3]) print(inspect.stack()[1][3]) # will give the caller of foos name, if something called foo foo() #output: foo

66) Why do some functions have underscores “__” before and after the function name in Python?

Answer#

Descriptive: Naming Styles in Python

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

_single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose name starts with an underscore.

single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

__double_leading_and_trailing_underscore__: “magic” objects or attributes that live in user-controlled namespaces. E.g. init, import or file. Never invent such names; only use them as documented.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: “Never invent such names; only use them as documented”.

67) How to run a function from the command line in Python?

I have this code:

def hello():
return ‘Hi :)’

How would I run this directly from the command line?

Answer#

With the -c (command) argument (assuming your file is named foo.py):

$ python -c ‘import foo; print foo.hello()’

Alternatively, if you don’t care about namespace pollution:

$ python -c ‘from foo import *; print hello()’

And the middle ground:

$ python -c ‘from foo import hello; print hello()’

68) How to pass a dictionary to a function as keyword parameters in Python?

I’d like to call a function in python using a dictionary with matching key-value pairs for the parameters.

Here is some code:

d = dict(param='test') def f(param): print(param) f(d) #This prints but I'd like it to just print test. #I'd like it to work similarly for more parameters: d = dict(p1=1, p2=2) def f2(p1, p2): print(p1, p2) f2(d) #Is this possible?

Answer#

Just include the ** operator to unpack the dictionary. This solves the issue of passing a dictionary to a function as a keyword parameter.

So here is an example:

d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(**d)

69) Is there a math nCr function in Python?

Answer# Python code for nCr (n Choose r) function:

The following program calculates nCr in an efficient manner (compared to calculating factorials etc.)

import operator as op from functools import reduce def ncr(n, r): r = min(r, n-r) numer = reduce(op.mul, range(n, n-r, -1), 1) denom = reduce(op.mul, range(1, r+1), 1) return numer // denom # or / in Python 2 #As of Python 3.8, binomial coefficients are available in the standard library as math.comb: >>> from math import comb >>> comb(10,3) 120

70) How to send an email with Python? Python code for sending an email?

Answer#: Python program for sending an email.

We recommend using the standard packages email and smtplib together to send emails.

Please look at the following example (reproduced from the Python documentation).

Notice that if you follow this approach, the “simple” task is indeed simple, and the more complex tasks (like attaching binary objects or sending plain/HTML multipart messages) are accomplished very rapidly.

# Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. with open(textfile, 'rb') as fp: # Create a text/plain message msg = MIMEText(fp.read()) # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'The contents of %s' % textfile msg['From'] = me msg['To'] = you # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') s.sendmail(me, [you], msg.as_string()) s.quit()

For sending emails to multiple destinations, you can follow the below Python example:

# Import smtplib for the actual sending function import smtplib # Here are the email package modules we'll need from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Our family reunion' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = me msg['To'] = ', '.join(family) msg.preamble = 'Our family reunion' # Assume we know that the image files are all in PNG format for file in pngfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. with open(file, 'rb') as fp: img = MIMEImage(fp.read()) msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP('localhost') s.sendmail(me, family, msg.as_string()) s.quit()

As you can see, the header To in the MIMEText object must be a string consisting of email addresses separated by commas. On the other hand, the second argument to the sendmail function must be a list of strings (each string is an email address).

So, if you have three email addresses: [email protected], [email protected], and [email protected], you can do as follows (obvious sections omitted):

the “,”.join(to) part makes a single string out of the list, separated by commas.