A for loop is probably the most common type of loop in Python. A for loop will select items from any iterable. In Python an iterable is any container (list, tuple, set, dictionary), as well as many other important objects such as generator function, generator expressions, the results of builtin functions such as filter, map, range and many other items.
1. Job Oriented || Instructor Led ||
Face2Face True Live I.T Training for
Everyone
Python Interview questions and Answers
1. How do you make a loop in Python 3?
There are 3 main ways to make a loop (or a loop like) construct:
While
A while loop is the simplest type of loop, where the body of the loop is repeated until a
condition becomes False
1. even =True
2. while even:
3. num=input('Provide an even integer > ')
4. even =(int(num)%2==0)
For loop
A for loop is probably the most common type of loop in Python. A for loop will select items
from any iterable. In Python an iterable is any container (list, tuple, set, dictionary), as well
as many other important objects such as generator function, generator expressions, the
results of builtin functions such as filter, map, range and many other items.
An example of a for loop :
2. 1. the_list=[1,2,3,4,5,6,7,8,9]
2. for item inthe_list:
3. print(item, item**2)
Comprehensions
Comprehensions are a loop like construct for use in building lists, sets and dictionaries
A list comprehension example :
1. # Build the list [0,2,4,6,8,10]
2. my_list=[x for x inrange(11)if x%2==0]
2. What is the difference between pop() and remove() in a list in
Python?
pop() takes an index as its argument and will remove the element at that index. If no
argument is specified, pop() will remove the last element. pop()also returns the element it
removed.
remove() takes an element as its argument and removes it if it’s in the list, otherwise an
exception will be thrown.
1. mylist=['zero','one','two','three']
2.
3. print(mylist.pop())# removes last element
4. print(mylist.pop(1))# removes a specific element
5. mylist.remove('zero')# removes an element by name
6. print(mylist)
7. mylist.remove('foo')# ...and throws an exception if not in list
3. Python (programming language). How do you check if a given key
already exists in a dictionary?
use the ‘in’ operator for a simple membership test, but in some cases, a call to the get
method might be better.
Using get to retrieve a value if it exists, and a default value if it doesn’t
for example:
val=my_dict.get(key,None)
Using ‘in’ to decide which operation is needed :
If you are testing for an existing key, and wondering whether to insert or append - there is
another thing you can do: if you have code like this :
1. if key inmy_dict:
2. my_dict[key].append(value)
3. else:
4. my_dict[key]=[]
3. 4. What does * and ** means in Python? Is it to do with pointers and
addresses?
There are a number of uses of * and ** :
* is the multiplication operator (or in the case of strings a repetition operator).
Classes in other libraries may use ‘*’ for other reasons, but nearly always it is
multiplication in some form.
** is an exponent operator such that in normal numbers x ** y is the mathematical
method for computing xyxy
5. What's the purpose of __main__ in python? How it is used and when?
For every module that is loaded/imported into a Python program, Python assigns a special
attribute called __name__.
The rules for how __name__ is set are not that complex :
If the module is the first module being executed, then __name__ is set to ‘__main__’
If the module is imported in some way, then __name__ is set to the name of the
module.
6. Why are lambdas useful in Python? What is an example that shows
such usefulness if any?
An example of the use case for lambdas is doing sorts, or map, or filter or reduce.
For example to remove odd numbers from a list:
1. evens_only=list(filter(lambda x:x %2==0, numbers))
So here the filter takes a function which needs to return true for every value to be contained
in the new iterable.
To sort a list of tuples, using only the 2nd item in the tuple as the sort item:
1. sorted=sorted(un_sorted_list_of_tuples, key=lambda x: x[1])
Without the key the sorted function will sort based on the entire tuple (which will compare
both the 1st and 2nd items). The sort method on lists works similarly if you want to sort in
place.
Using reduce to multiply a list of values together
2. product =reduce(lambdax,y: x*y,list_of_numbers,1)
Here reduce expects a function (such as a lambda) that takes two values and will return
one).
4. Another use case is for map to apply a transformation to every entry in a sequence - for
instance:
1. fromitertoolsimport count
2. for square inmap(lambda x:x*x, count()):
3. print(square):
4. if square >100:
5. break
This code uses map to generate a sequence of square numbers up to but not greater than
100.
Itertools.count is a great function that produces a sequence of numbers starting from 1 and
never ending ( similar to range but without an end).
7. How do you randomly select an item from a list in Python?
You can achieve this easily using choice method from random module
1. import random
2. l =[1,2,3,4,5]
3. selected =random.choice(l)
4. print(selected)
An alternative method would be selecting a random index
using random.randint. But random.choice is more convenient for this purpose.
8. What are Python modules?
A module is a collection is functions, classes and data which together provide related set of
functionality. For instance you could have a module which implements the http protocol,
and another module which create jpeg files. To make use of a module, and the functionality
in it - a python program simply has to import it.
You also find the Python has packages - A package is a set of modules - which are related - to
each other; An example would be the Django package. You have a set of modules which
define models, and another which supports web forms, another which supports views,
another which supports data validation and so on. They all relate to each to to provide the
Django package of functionality for writing web servers.
9. What are the differences between tuples and lists in Python?
The main difference:
lists can be changed once created - you can append, and delete elements from the
list, and change individual elements - they are mutable.
tuple, once created, cannot be changed - you cannot append or delete elements
from a tuple, or change individual elements - they are immutable.
10. Why would you want a data structure that can’t be changed once
created?
5. Tuples are smaller in terms of memory used than a list with the same number and
type of elements.
Tuples are ideally suited for data where the order of elements is well understood
by convention - for instance co-ordinates (x,y,z), colours (RGB or HSV). If you
need a tuple type structure but with named elements, not index numbers, then
you can use the NamedTuple type.
In general, a tuple can be stored in a set, or form the key for a dictionary - whereas
as a list cannot be. In python terms it is hashable. (Although you can make tuples
un-hashable by choosing the wrong data types).
11. What do 'write', 'read' and 'append' signify in Python's open()
function?
Write, read and append are what are termed the access mode. They indicate what the
intended operation on the file will be.
They have two important effects:
1. They relate directly to the permissions on a file - All O/S implement in some form
the idea of read write permission on a file. Attempting to open a file for writing or
appending that the program doesn’t have permission to write to, or opening a file
for reading that the program doesn’t have permission to read is by definition an
error, and in Python will raise an exception - specifically PermissionError.
2. They directly relate to how the file is opened, and where the file pointer is set to
(the O/S will maintain a file pointer which is where in the file the next read or
write will occur - it is normally a count from zero of the number of bytes in the
file.):
read : The file is opened with the file pointer set to zero - i.e. read from the start of
the file.
write : The file is opened, the file length is set to zero, and the file pointer is set to
zero - i.e. write from the start of the file ignoring all previous contents
append : The file is opened, the file pointer is set to the end of the file - i.e. write from
the end of the file, retaining all previous contents.
12. How do I write a program about summing the digits of a number
in Python?
The answers so far do this numerically, which is perfectly fine, but I think it’s more Pythonic
to consider the number as a string of digits, and iterate through it:
1. >>>num=123456789
2. >>>sum_of_digits=0
3. >>>for digit in str(num):
4. ...sum_of_digits+=int(digit)
5. ...
6. >>>sum_of_digits
7. 45
A more advanced solution would eschew the loop and use a generator expression. There’s
still a loop in there, but sum_of_digits is computed all in one go, so we don’t have to set it to
0 first:
1. >>>num=123456789
6. 2. >>>sum_of_digits= sum(int(digit)for digit in str(num))
3. >>>sum_of_digits
4. 45
13. What is “_init_” in Python?
__init__ (double underscore “init” followed by double underscore), when it’s used as the
name of a method for a class in Python, is an instance “initialization” function.
In Python most (almost all) of the “special” class methods and other attributes are wrapped
in “double underscore” characters. Theare, sometimes referred to as “dunder” methods (or
attributes).
14. Why do python classes always require a self parameter?
I will explain this with an example.
I have created here a class Human which I’m defining with Self.
Here I have created the object, Will.
1. classHuman():
2.
3. def __init__(self,name,gender):
4.
5. self.name = name
6. self.gender= gender
7.
8. defspeak_name(self):// the self-going to speak the name
9. print MY NameisWill%self.name
10.
11. will =Human("William","Male")
12.
13. print will.name
14. printwill.gender
15.
16. will.speak_name()
So, self-represents the object itself. The Object is will.
Then I have defined a method speak_name. ( A method is different from Function because it
is part of the class) It can be called from the object. Self is an object when you call self, it
refers to will.
This is how self-works.
Whenever you use self. something, actually you’re assigning new value or variable to the
object which can be accessed by the python program everywhere.
15. In Python, what is NumPy? How is it used?
Python NumPy is cross platform & BSD licensed. You often used it with packages like
Matplotlib & SciPy. This can be an alternative to MATLAB. Numpy is a portmanteau of the
words NUMerical and Python.
7. Features of Numpy-
NumPy stands on CPython, a non optimizing bytecode interpreter.
Multidimensional arrays.
Functions & operators for these arrays
Python alternatives to MATLAB.
ndarray- n-dimensional arrays.
Fourier transforms & shapes manipulation.
Linear algebra & random number generation.
Register & post msgs in Forums:http://h2kinfosys.com/forums/
Like us on FACE BOOK
http://www.facebook.com/H2KInfosysLLC
Videos : http://www.youtube.com/user/h2kinfosys