Python
Python interview questions and answers
What are the key features of Python?
Python is a object-oriented,open source programming language
It runs on different platforms like Windows, Linux,Macintosh etc.
It is easy to read as it has a clean syntax
It can be integrated with different languages such as Java,C,C++,C#.
function
A function is used to modularize application.Instead of defining application in a single module,application code is defined in different functions.
This helps to keep the application easier to maintain.After you have defined a function you can call it by using its name.
What is a function.How do you define a function?
You can define a function using the def keyword:
def FunctionName(): statements
to call the function you use:
FunctionName()
you can also define and pass parameters to the function:
def FunctionName(param1): statement block
Write to a file in python?
Python provides several functions for working with files.One of the most important functions is open.To open a file for reading:
f = open("file name")
or
f = open("file name",mode)
So to open a file for reading mode should be “r”:
f = open("fileName.txt","r")
if you want to append to an existing file:
f = open("fileName.txt","a+") f.write("Append Data" )
Pass in python?
Sometimes when defining a class you don’t want to implement some of the methods.As you can not write any method without any statement so you can use pass
statement:
class ClassName(object): def method1(self): pass def method2(self): pass
Exception handling in Python?
You use the try and except keywords.If the code in try block throws any exception then it is handled by the matching except block.
try: statement block except exception1: print("exception 1") except exception2: print("exception 2") except exception3: print("exception 3")
What is PEP 8?
It is a set of coding conventions for the Python code and defines things such as method names,variable names,exception names etc.
Explain the ternary operator in Python?
It specifies a boolean expression and returns one of the two values based on the value of the boolean expression
Following is a ternary operator which returns the value y.
x,y=1,2
num = x if x < y else y
What is the key difference between a list and the tuple?
Bothe list and tuple are containers of items but list is mutable while tuple is immutable
How does Python handle the memory management?
Memory management in Python is handled using Python memory manager.The Python memory manager consists of different components for different aspects of memory maangement such as:
- sharing
- segmentation
- preallocation
- caching
The user has no control over Python heap as it is performed by the the interpreter.
What is the “self” keyword in Python?
Self is a variable used in a class method which refers to the current instance of the class.
In the following example we are setting a variable called num in SimpleClass as 2.
class SimpleClass(object): num = 1 def set_num(self): self.num=2
What is NumPy?
- NumPy is a package for scientific computing with Python.It has features such as:
N-dimensional array - linear algebra, Fourier transform, and random number capabilities
Explain help() and dir() functions in Python?
- help() function provides information related to modules, keywords, attributes, etc.
- dir() returnd a list of attributes of the object.
Listening to Raspberry pi push button using Python
In this example we will see how to connect push button to raspberry pi.The push button will act as an input interface to raspberry pi.
To implement the circuit fort the application we will need the following:
- breadboard
- jumper wires (2 male to female)
- push button
- raspberry pi (b+ in this example)
set up the circuit as:
attach the push button on the breadboard such that two terminals are together and 2 are separated.You need to use different unconnected rows in the breadboard.
connect the jumper wires
- GPIO Grd(PIN 3) to one terminal of push button
- GPIO 16 to other terminal of push button
Following is the layout of the raspberry pi GPIO (3 B+).
Following is the Python code:
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(16, GPIO.IN) if GPIO.input(16) == False: # you can also use 1/0 instead of true/false print('I am pressing the button') time.sleep(0.2)
There is one important point to note here,the call to setup() method:
GPIO.setup(16, GPIO.IN)
What this does is set the GPIO pin which you want to use.Here we are using the GPIO pin 16 ,but you can use another GPIO.
and we are reading the input using the GPIO.input() method.This method return boolean values ,TRUE/FALSE or 1/0.
Inputs are Boolean values: 1 or 0, GPIO.HIGH or GPIO.LOW, True or False.
You can save the above script in a file called pushButon.py and execute it as:
python pushButon.py
If you run the above code and press the button then the following text will be printed:
I am pressing the button
Best Python IDEs for Developers
IDE stands for integrated development environment is an application which provides several features that help developers in various tasks.It commonly consists of following:
- Source code editor
- compiler or interpreter
- debugger
- code completion
- syntax highlighting
Python has several IDEs which are supported on Windows.Here we will look into some of these IDEs:
Following are supported in all the Operating Systems including Windows:
PyCharm
PyCharm is created by JetBrains.It is used for mainly Python, Javascript, Typescript, AngularJS, Node.js among others.It also supports some web development frameworks such as Django.It can be used for running and debugging Python applications.It has good community support.There is an option to buy yearly license.
Eclipse using PyDev
Eclipse supports Python using Python plugin for Eclipse called PyDev.It is open source and licensed under Eclipse’s public license.Supports Django.
Emacs
Emacs is a family of text editors.It is supported on Windows. Mac OS, Linux.It is free and registered under GNU(General Public License).
Wing IDE
Wing IDE is Close-Sourced .Supports Windows, Linux and MacOS support.It has support for Django.
Komodo IDE
Komodo IDE Close-Sourced , Windows, MacOS and Linux support.You need to buy license to use it.There is currently 21 days trial available.
Sublime Text 3
Sublime is supported on all the major OS.There is a plugin for Python that can be added in Sublime called SublimePythonIDE.
Spyder
Spyder is free to use under MIT license,windows, Linux, MacOS, MacOS.Useful for data science applications.
self parameter in Python
Class in Python is declared using the class keyword.To declare a simple class called Example you use the following statement
class Example: pass
we used pass since we are not declaring the class body.
We can modify the above class to add a simple method called PrintHello.What this method will do is print a simple message. __init_ is the class constructor.
class Example: def __init__(self): print("Example object is created") def PrintHello(self): self.name="1" print("hello world")
If you observe the above class definition you can see that __init__ method as well as the PrintHello() method are passed a parameter called self.The keyword self represents an object or instance of the class.The current object is represented by the keyword self.
self parameter is used in a method in a class.You can not use self parameter outside the class.
In the PrintHello() method we are adding a new attribute called name to self.This is one way of adding attributes to an object.We can access the attribute name from the calling method as:
ob=Example() ob.PrintHello() print(ob.name) #this will print the value "1"