SlideShare a Scribd company logo
2
Most read
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

More Related Content

PPTX
Class, object and inheritance in python
PDF
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
PDF
Python Programming Tutorial | Edureka
PPTX
Python Interview questions 2020
PPTX
Object oriented programming in python
DOCX
Python interview questions and answers
PDF
Top 20 Python Interview Questions And Answers 2023.pdf
PDF
Python Class | Python Programming | Python Tutorial | Edureka
Class, object and inheritance in python
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Programming Tutorial | Edureka
Python Interview questions 2020
Object oriented programming in python
Python interview questions and answers
Top 20 Python Interview Questions And Answers 2023.pdf
Python Class | Python Programming | Python Tutorial | Edureka

What's hot (20)

PPTX
Python dictionary
PDF
Python Programming Language | Python Classes | Python Tutorial | Python Train...
PDF
Python Interview Questions And Answers 2019 | Edureka
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
PPTX
Python presentation by Monu Sharma
PPTX
Linear Search Presentation
PPTX
Introduction to-python
PPT
PPT
Python ppt
PPTX
Computer Science-Data Structures :Abstract DataType (ADT)
PPT
Elementary data organisation
PPTX
Python ppt
PDF
What is Python JSON | Edureka
PDF
Class and Objects in Java
PDF
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
PPTX
Strings in Python
PDF
Introduction To Python | Edureka
PDF
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
PPTX
Strings in Java
Python dictionary
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Interview Questions And Answers 2019 | Edureka
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python presentation by Monu Sharma
Linear Search Presentation
Introduction to-python
Python ppt
Computer Science-Data Structures :Abstract DataType (ADT)
Elementary data organisation
Python ppt
What is Python JSON | Edureka
Class and Objects in Java
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
Strings in Python
Introduction To Python | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Strings in Java
Ad

Similar to Python Interview Questions And Answers (20)

DOCX
These questions will be a bit advanced level 2
PDF
Python Interview Questions PDF By ScholarHat.pdf
PDF
Python cheat-sheet
PDF
Top Most Python Interview Questions.pdf
PDF
advanced python for those who have beginner level experience with python
PDF
Advanced Python after beginner python for intermediate learners
PPTX
Programming in Python
PDF
Python interview questions and answers
PPTX
set.pptx
DOCX
Python Interview Questions For Experienced
PPTX
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
PPT
asdf adf asdfsdafsdafsdfasdfsdpy llec.ppt
PPTX
Python Interview Questions | Python Interview Questions And Answers | Python ...
KEY
Programming with Python - Week 3
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
PPTX
Python For Data Science.pptx
PDF
python interview prep question , 52 questions
PPTX
Python1_Extracted_PDF_20250404_1054.pptx
PPTX
Improve Your Edge on Machine Learning - Day 1.pptx
PPTX
Python advance
These questions will be a bit advanced level 2
Python Interview Questions PDF By ScholarHat.pdf
Python cheat-sheet
Top Most Python Interview Questions.pdf
advanced python for those who have beginner level experience with python
Advanced Python after beginner python for intermediate learners
Programming in Python
Python interview questions and answers
set.pptx
Python Interview Questions For Experienced
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
asdf adf asdfsdafsdafsdfasdfsdpy llec.ppt
Python Interview Questions | Python Interview Questions And Answers | Python ...
Programming with Python - Week 3
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Python For Data Science.pptx
python interview prep question , 52 questions
Python1_Extracted_PDF_20250404_1054.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
Python advance
Ad

More from H2Kinfosys (18)

PPTX
JIRA Introduction | JIRA Tutorial | Atlassian JIRA Training | H2kinfosys
DOCX
Mobile Apps Telecommunication Doc
DOCX
Mobile Apps Testing Tele communication Doc
PPT
Health Care Project Overview from H2kInfosys LLC
ODS
Testcase cyclos excel document
PDF
Test plan cyclos
PPT
HealthCare Project Test Case writing guidelines
PDF
Letters test cases
DOCX
Health Care Project Testing Process
PDF
Test Plan Template
DOC
Test Plan Template
PPTX
ETL Testing Interview Questions and Answers
PPTX
CRM Project - H2Kinfosys
DOC
Online Banking Business Requirement Document
PDF
Online Shopping Cart Business Requirement Dcoument
PDF
QA Interview Questions With Answers
PDF
Basic Interview Questions
DOCX
SDLC software testing
JIRA Introduction | JIRA Tutorial | Atlassian JIRA Training | H2kinfosys
Mobile Apps Telecommunication Doc
Mobile Apps Testing Tele communication Doc
Health Care Project Overview from H2kInfosys LLC
Testcase cyclos excel document
Test plan cyclos
HealthCare Project Test Case writing guidelines
Letters test cases
Health Care Project Testing Process
Test Plan Template
Test Plan Template
ETL Testing Interview Questions and Answers
CRM Project - H2Kinfosys
Online Banking Business Requirement Document
Online Shopping Cart Business Requirement Dcoument
QA Interview Questions With Answers
Basic Interview Questions
SDLC software testing

Recently uploaded (20)

PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PPTX
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
KodekX | Application Modernization Development
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Reimagining Insurance: Connected Data for Confident Decisions.pdf
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
GamePlan Trading System Review: Professional Trader's Honest Take
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
Understanding_Digital_Forensics_Presentation.pptx
Transforming Manufacturing operations through Intelligent Integrations
KodekX | Application Modernization Development
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Chapter 3 Spatial Domain Image Processing.pdf
Automating ArcGIS Content Discovery with FME: A Real World Use Case
CIFDAQ's Teaching Thursday: Moving Averages Made Simple

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