SlideShare une entreprise Scribd logo
1  sur  7
Télécharger pour lire hors ligne
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 :
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]=[]
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).
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?
 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
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.
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

Contenu connexe

Tendances

Tendances (20)

Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Python
PythonPython
Python
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Python Basics.pdf
Python Basics.pdfPython Basics.pdf
Python Basics.pdf
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 

Similaire à Python Interview Questions And Answers

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 

Similaire à Python Interview Questions And Answers (20)

These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Top Most Python Interview Questions.pdf
Top Most Python Interview Questions.pdfTop Most Python Interview Questions.pdf
Top Most Python Interview Questions.pdf
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
set.pptx
set.pptxset.pptx
set.pptx
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptxKripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
 
python interview prep question , 52 questions
python interview prep question , 52 questionspython interview prep question , 52 questions
python interview prep question , 52 questions
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
Python advance
Python advancePython advance
Python advance
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdf
 
Advance python
Advance pythonAdvance python
Advance python
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 

Plus de H2Kinfosys

HealthCare Project Test Case writing guidelines
HealthCare Project Test Case writing guidelinesHealthCare Project Test Case writing guidelines
HealthCare Project Test Case writing guidelines
H2Kinfosys
 
Letters test cases
Letters test casesLetters test cases
Letters test cases
H2Kinfosys
 
Health Care Project Testing Process
Health Care Project Testing ProcessHealth Care Project Testing Process
Health Care Project Testing Process
H2Kinfosys
 
Test Plan Template
Test Plan TemplateTest Plan Template
Test Plan Template
H2Kinfosys
 
Online Shopping Cart Business Requirement Dcoument
Online Shopping Cart Business Requirement DcoumentOnline Shopping Cart Business Requirement Dcoument
Online Shopping Cart Business Requirement Dcoument
H2Kinfosys
 

Plus de H2Kinfosys (18)

JIRA Introduction | JIRA Tutorial | Atlassian JIRA Training | H2kinfosys
JIRA Introduction | JIRA Tutorial | Atlassian JIRA Training | H2kinfosysJIRA Introduction | JIRA Tutorial | Atlassian JIRA Training | H2kinfosys
JIRA Introduction | JIRA Tutorial | Atlassian JIRA Training | H2kinfosys
 
Mobile Apps Telecommunication Doc
Mobile Apps Telecommunication DocMobile Apps Telecommunication Doc
Mobile Apps Telecommunication Doc
 
Mobile Apps Testing Tele communication Doc
Mobile Apps Testing Tele communication DocMobile Apps Testing Tele communication Doc
Mobile Apps Testing Tele communication Doc
 
Health Care Project Overview from H2kInfosys LLC
Health Care Project Overview from H2kInfosys LLCHealth Care Project Overview from H2kInfosys LLC
Health Care Project Overview from H2kInfosys LLC
 
Testcase cyclos excel document
Testcase cyclos excel documentTestcase cyclos excel document
Testcase cyclos excel document
 
Test plan cyclos
Test plan cyclosTest plan cyclos
Test plan cyclos
 
HealthCare Project Test Case writing guidelines
HealthCare Project Test Case writing guidelinesHealthCare Project Test Case writing guidelines
HealthCare Project Test Case writing guidelines
 
Letters test cases
Letters test casesLetters test cases
Letters test cases
 
Health Care Project Testing Process
Health Care Project Testing ProcessHealth Care Project Testing Process
Health Care Project Testing Process
 
Test Plan Template
Test Plan TemplateTest Plan Template
Test Plan Template
 
Test Plan Template
Test Plan TemplateTest Plan Template
Test Plan Template
 
ETL Testing Interview Questions and Answers
ETL Testing Interview Questions and AnswersETL Testing Interview Questions and Answers
ETL Testing Interview Questions and Answers
 
CRM Project - H2Kinfosys
CRM Project - H2KinfosysCRM Project - H2Kinfosys
CRM Project - H2Kinfosys
 
Online Banking Business Requirement Document
Online Banking Business Requirement DocumentOnline Banking Business Requirement Document
Online Banking Business Requirement Document
 
Online Shopping Cart Business Requirement Dcoument
Online Shopping Cart Business Requirement DcoumentOnline Shopping Cart Business Requirement Dcoument
Online Shopping Cart Business Requirement Dcoument
 
QA Interview Questions With Answers
QA Interview Questions With AnswersQA Interview Questions With Answers
QA Interview Questions With Answers
 
Basic Interview Questions
Basic Interview QuestionsBasic Interview Questions
Basic Interview Questions
 
SDLC software testing
SDLC software testingSDLC software testing
SDLC software testing
 

Dernier

Dernier (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Python Interview Questions And Answers

  • 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