1) What is Python?
Ans: Python is a high-level and object-oriented programming language with unified semantics designed primarily for developing apps and web. It is the core language in the field of Rapid Application Development (RAD) as it offers options such as dynamic binding and dynamic typing.
2) What are the benefits of Python?
Ans: The benefits of Python are as follows:
- Speed and Productivity: Utilizing the productivity and speed of Python will enhance the process control capabilities and possesses strong integration.
- Extensive Support for Libraries: Python provides a large standard library that includes areas such as operating system interfaces, web service tools, internet protocols, and string protocols. Most of the programming tasks are already been scripted in the standard library which reduces effort and time.
- User-friendly Data Structures: Python has an in-built dictionary of data structures that are used to build fast user-friendly data structures.
- Existence of Third Party Modules: The presence of third party modules in the Python Package Index (PyPI) will make Python capable to interact with other platforms and languages.
- Easy Learning: Python provides excellent readability and simple syntaxes to make it easy for beginners to learn.
3) What are the key features of Python?
Ans: The following are the significant features of Python, and they are:
- Interpreted Language: Python is an interpreted language that is used to execute the code line by line at a time. This makes debugging easy.
- Highly Portable: As Python can run on different platforms such as Unix, Macintosh, Linux, Windows, and so on. So, we can say that it is a highly portable language.
- Extensible: It ensures that the Python code can be compiled on various other languages such as C, C++ and so on.
- GUI programming Support: It implies that the Python provides support to develop graphical user interfaces
4) What type of language is Python? Programming or Scripting?
Ans: Python is suitable for scripting, but in general it is considered as a general-purpose programming language.
5) What are the applications of Python?
Ans: The applications of Python are as follows:
- GUI based desktop applications
- Image processing applications
- Business and Enterprise applications
- Prototyping
- Web and web framework applications
6) What is the difference between list and tuple in Python?
Ans: The difference between tuple and list are as follows:
List | Tuple |
The list is mutable (can be changed) | A tuple is immutable (remains constant) |
These lists performance is slower | Tuple performance is faster when compared to lists |
Syntax: list_1 = [20, ‘Mindmajix’, 30] | Syntax: tup_1 = (20, ‘Mindmajix’, 30) |
7) What are the global and local variables in Python?
Ans: Global Variables in Python: The variables that are declared outside the function are called global variables. These variables can be accessed or invoked by any function in the program.
Example:
1
2
3
4
| def v() : print g g = "welcome to mindmajix" v() |
Output:
1
| Welcome to mindmajix |
Local Variables in Python: The variables that are declared inside a function are called local variables. These type of variables can be accessed only inside the function.
8) Define PYTHON PATH?
Ans: PYTHONPATH is an environmental variable that is used when we import a module. Suppose at any time we import a module, PYTHONPATH is used to check the presence of the modules that are imported in different directories. Loading of the module will be determined by interpreters.
9) What are the two major loop statements?
Ans: for and while
10) What do you understand by the term PEP 8?
Ans: PEP 8 is the Python latest coding convention and it is abbreviated as Python Enhancement Proposal. It is all about how to format your Python code for maximum readability.
11) How memory management is done in Python?
Ans:
- In Python memory management is done using private heap space. The private heap is the storage area for all the data structures and objects. The interpreter has access to the private heap and the programmer cannot access this private heap.
- The storage allocation for the data structures and objects in Python is done by the memory manager. The access for some tools is provided by core API for programmers to code.
- The built-in garbage collector in Python is used to recycle all the unused memory so that it can be available for heap storage area.
12) Java vs Python
Ans: The major difference between Java and Python are as follows:
Function | Java | Python |
Coding | In Java, we need to write a long code to print something. | In Python coding is simple and smaller when compared to Java |
Syntax | In Java we need to put a semicolon at the end of the statement and also code must be placed in curly braces. | Whereas, in Python indentation is mandatory as it improves the readability of the code. |
Dynamic | In Java, we need to declare the type for each variable | In this case, codes are dynamically typed and this is also known as duck typing |
Easy to use | Java is not easy to use because of its larger coding | In Python, it is very easy to code and perform very easily. |
Databases | Java Database Connectivity (JDBC) is more popular and used most commonly. | In Python database access layers are weaker when compared to Java. |
Explore in detail differences @ Python vs Java
13) Define modules in Python?
Ans: Module is defined as a file that includes a set of various functions and Python statements that we want to add in our application.
Example of creating` a module:
In order to create a module first, we need to save the code that we want in a file with .py extension.
Save the module with module.py
1
2
| def wishes(name): Print( "Hi, " + name) |
14) What are the built-in types available in Python?
Ans: The built-in types in Python are as follows:
- Integer
- Complex numbers
- Floating-point numbers
- Strings
- Built-in functions
15) What are Python Decorators?
Ans: Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of class or function.
Example for Python Decorator is:
1
2
3
| @gfg_decorator def hi_decorator(): print( "Gfg" ) |
16) How do we find bugs and statistical problems in Python?
Ans: We can detect bugs in python source code using a static analysis tool named PyChecker. Moreover, there is another tool called PyLint that checks whether the Python modules meet their coding standards or not.
17) What is the difference between .py and .pyc files?
Ans: .py files are Python source files. .pyc files are the compiled bytecode files that are generated by the Python compiler
18) How do you invoke the Python interpreter for interactive use?
Ans: By using python or pythonx.y we can invoke Python interpreter. where x.y is the version of the Python interpreter.
19) Define String in Python?
Ans: String in Python is formed using a sequence of characters. Value once assigned to a string cannot be modified because they are immutable objects. String literals in Python can be declared using double quotes or single quotes.
Exam
1
2
| print( "Hi" ) print( 'Hi' ) |
20) What do you understand by the term namespace in Python?
Ans: A namespace in Python can be defined as a system that is designed to provide a unique name for every object in python. Types of namespaces that are present in Python are:
- Local namespace
- Global namespace
- Built-in namespace
Scope of an object in Python:
Scope refers to the availability and accessibility of an object in the coding region.
21) How do you create a Python function?
Ans: Functions are defined using the def statement.
An example might be def foo(bar):
22) Define iterators in Python?
Ans: In Python, an iterator can be defined as an object that can be iterated or traversed upon. In another way, it is mainly used to iterate a group of containers, elements, the same as a list.
23) How does a function return values?
Ans: Functions return values using the return statement.
24) Define slicing in Python?
Ans: Slicing is a procedure used to select a particular range of items from sequence types such as Strings, lists, and so on.
25) How can Python be an interpreted language?
Ans: As in Python the code which we write is not machine-level code before runtime so, this is the reason why Python is called as an interpreted language.
26) What happens when a function doesn’t have a return statement? Is this valid?
Ans: Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code is executed (i.e., the indenting) not by any explicit keyword.
27) Define package in Python?
Ans: In Python packages are defined as the collection of different modules.
28) How can we make a Python script executable on Unix?
Ans: In order to make a Python script executable on Unix, we need to perform two things. They are:
Script file mode must be executable and
The first line should always begin with #.
29) Which command is used to delete files in Python?
Ans: OS.unlink(filename) or OS.remove(filename) are the commands used to delete files in Python Programming.
Example:
1
2
| import OS OS.remove( "abc.txt" ) |
30) Define pickling and unpickling in Python?
Ans:
Pickling in Python: The process in which the pickle module accepts various Python objects and converts into a string representation and dumps the file accordingly using dump function is called pickling.
Unpickling in Python: The process of retrieving actual Python objects from the stored string representation is called unpickling.
31) Explain the difference between local and global namespaces?
Ans: Local namespaces are created within a function when that function is called. Global namespaces are created when the program starts.
32) What is a boolean in Python?
Ans: Boolean is one of the built-in data types in Python, it mainly contains two values, and they are true and false.
Python bool() is the method used to convert a value to a boolean value.
1
| Syntax for bool() method: bool([a]) |
33) What is Python String format and Python String replace?
Ans:
Python String Format: The String format() method in Python is mainly used to format the given string into an accurate output or result.
Syntax for String format() method:
1
| template.format(p0, p1, ..., k0=v0, k1=v1, ...) |
Python String Replace: This method is mainly used to return a copy of the string in which all the occurrence of the substring is replaced by another substring.
Syntax for String replace() method:
1
| str.replace(old, new [, count]) |
34Q. Name some of the built-in modules in Python?
Ans: The built-in modules in Python are:
- sys module
- OS module
- random module
- collection module
- JSON
- Math module
35Q. What are the functions in Python?
Ans: In Python, functions are defined as a block of code that is executable only when it is called. The def keyword is used to define a function in Python.
Example:
1
2
3
| def Func(): print( "Hello, Welcome toMindmajix" ) Func(); #calling the function |
Output: Hello, Welcome to Mindmajix
36) What are Dict and List comprehensions in Python?
Ans: These are mostly used as syntax constructions to ease the creation of list and dictionaries based on existing iterable.
37Q. Define the term lambda?
Ans: Lambda is the small anonymous function in Python that is often used as an inline function.
38Q. When would you use triple quotes as a delimiter?
Ans: Triple quotes ‘’”” or ‘“ are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained therein.
39Q. Define self in Python?
Ans: In Python self is defined as an object or an instance of a class. This self is explicitly considered as the first parameter in Python. Moreover, we can also access all the methods and attributes of the classes in Python programming using self keyword.
In the case of the init method, self refers to the newer creation of the object. Whereas in the case of other methods self refers to the object whose method was called.
40Q. What is _init_?
Ans: The _init_ is a special type of method in Python that is called automatically when the memory is allocated for a new object. The main role of _init_ is to initialize the values of instance members for objects.
Example:
1
2
3
4
5
6
7
8
9
10
11
| class Student: def _init_ (self, name, age, marks): self.name = name self.age = age self.marks = 950 S1 = Student( "ABC" , 22, 950) # S1 is the instance of class Student. # _init allocates memory for S1. print(S1.name) print(S1.age) print(S1.marks) |
Output:
1
2
3
| ABC 22 950 |
41Q. Define generators in Python?
Ans: The way of implementing an effective representation of iterators is known as generators. It is only the normal function that yields expression in the function.
42Q. Define docstring in Python?
Ans: The docstring in Python is also called a documentation string, it provides a way to document the Python classes, functions, and modules.
43Q. How do we convert the string to lowercase?
Ans: lower() function is used to convert string to lowercase.
Example:
1
2
| str = 'XYZ' print(str.lower()) |
Output:
1
| xyz |
44Q. How to remove values from a Python array?
Ans: The elements can be removed from a Python array using remove() or pop() function. The difference between pop() and remove() will be explained in the below example.
Example:
1
2
3
4
5
| x = arr.array( 'd' , [ 1.0, 2.2, 3.4, 4.8, 5.2, 6.6, 7.3]) print(x.pop()) print(x.pop(3)) x.remove(1.0) print(a) |
Output:
1
2
3
| 7.3 4.8 array(‘d’, [2.2, 3.4, 5.2, 6.6]) |
45Q. What is Try Block?
A block which is preceded by the try keyword is known as a try block
Syntax:
1
2
3
| try { //statements that may cause an exception } |
46Q. Why do we use the split method in Python?
Ans: split() method in Python is mainly used to separate a given string.
Example:
1
2
| x = "Mindmajix Online Training" print(a.split()) |
Output:
1
| [‘Mindmajix’, ‘Online’, ‘Training’] |
47Q. How can we access a module written in Python from C?
Ans: We can access the module written in Python from C by using the following method.
1
| Module == PyImport_ImportModule( "<modulename>" ); |
48Q. How do you copy an object in Python?
Ans: To copy objects in Python we can use methods called copy.copy() or copy.deepcopy().
49Q. How do we reverse a list in Python?
Ans: By using list.reverse(): we can reverse the objects of the list in Python.
50Q. How can we debug a Python program?
Ans: By using the following command we can debug the Python program
1
| $ python -m pdb python-script.py |
51Q. Write a program to count the number of capital letters in a file?
Ans:
1
2
3
4
5
6
| with open(SOME_LARGE_FILE) as countletter: count = 0 text = countletter.read() for character in text: if character.isupper(): count += 1 |
52Q. Write a program to display the Fibonacci sequence in Python?
Ans:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| # Displaying Fibonacci sequence n = 10 # first two terms n0 = 0 n1 = 1 #Count x = 0 # check if the number of terms is valid if n <= 0: print( "Enter positive integer" ) elif n == 1: print( "Numbers in Fibonacci sequence upto" ,n, ":" ) print(n0) else : print( "Numbers in Fibonacci sequence upto" ,n, ":" ) while x < n: print(n0,end= ', ' ) nth = n0 + n1 n0 = n1 n1 = nth x += 1 |
Output:
1
| 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, |
53Q. Write a program in Python to produce Star triangle?
Ans: The code to produce star triangle is as follows:
1
2
3
4
| def pyfun(r): for a in range(r): print( ' ' *(r-x-1)+ '*' *(2*x+1)) pyfun(9) |
Output:
1
2
3
4
5
6
7
8
9
| * *** ***** ******* ********* *********** ************* *************** ***************** |
54Q. Write a program to check whether the given number is prime or not?
Ans: The code to check prime number is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| # program to check the number is prime or not n1 = 409 # num1 = int(input("Enter any one number: ")) # prime number is greater than 1 if n1 > 1: # check the following factors for x is in range of(2,num1): if (n1 % x) == 0: print(n1, "is not a prime number" ) print(x, "times" ,n1 //x,"is",num) break else : print(n1, "is a prime number" ) # if input number is smaller than # or equal to the value 1, then it is not prime number else : print(n1, "is not a prime number" ) |
Output:
1
| 409 is a prime number |
55Q. Write Python code to check the given sequence is a palindrome or not?
Ans:
1
2
3
4
5
6
7
8
9
10
11
| # Python code to check a given sequence # is palindrome or not my_string1 = 'MOM' My_string1 = my_string1.casefold() # reverse the given string rev_string1 = reversed(my_string1) # check whether the string is equal to the reverse of it or not if list(my_string1) == list(rev_string1): print( "It is a palindrome" ) else : print( "It is not a palindrome" ) |
Output:
1
| it is a palindrome |
56Q. Write Python code to sort a numerical dataset?
Ans: The code to sort a numerical dataset is as follows:
1
2
3
4
| list = [ "13" , "16" , "1" , "5" , "8" ] list = [int(x) for x in the list] list.sort() print(list) |
Output:
1
| 1, 5, 8, 13, 16 |
57Q. What is the output of the following code?
1
2
| x = [ 'ab' , 'cd' ] print(list(map(list, x))) |
Ans: The output of the following code is
1
| [ [‘a’, ‘b’], [‘c’, ‘d’] |
58Q.
59Q. Differentiate between SciPy and NumPy?
Ans: The difference between SciPy and NumPy is as follows:
NumPy | SciPy |
Numerical Python is called NumPy | Scientific Python is called SciPy |
It is used for performing general and efficient computations on numerical data which is saved in arrays. For example indexing, reshaping, sorting, and so on | This is an entire collection of tools in Python mainly used to perform operations like differentiation, integration and many more. |
There are some of the linear algebraic functions present in this module but they are not fully fledged. | For performing algebraic computations this module contain some of the fully fledged operations |
60Q. How do Python arrays and lists differ from each other?
Ans: The difference between Python array and Python list are as follows:
Arrays | Lists |
Array is defined as a linear structure that is used to store only homogeneous data. | List are used to store arbitrary and heterogenous data |
Since array stores only similar type of data so it occupies less amount of memory when compared to list. | List stores different types of data so it requires huge amount of memory |
Length of the array is fixed at the time of designing and no more elements can be added in the middle. | Length of the list is no fixed, and adding items in the middle is possible in lists. |
61Q. Can we make multi-line comments in Python?
Ans: In python there is no specific syntax to display multi-line comments like other languages. In order to display mitli-line comments in Python, programmers use triple-quoted (docstrings) strings. If the docstring is not used as the first statement in the present method, it will not be considered by Python parser.
62Q. What is the difference between range and xrange?
Ans: These both the methods are mainly used in Python to iterate the for loop for a fixed number of times. They differ only when we talk regarding Python versions.
The difference between range and xrange are as follows:
Range() method | Xrange() method |
The xrange() method is not supported in Python3 so that the range() method is used for iteration in for loops. | The xrange() method is used only in the Python version 2 for the iteration in for loops. |
List is returned by this range() method | It only returns the generator object because it doesn’t produce a static list during run time. |
It occupies a huge amount of memory as it stores the complete list of iterating numbers in memory. | It occupies less memory because it only stores one number at the time in memory. |
63Q. Explain how can we build or set up the database in Django?
Ans: we can make use of edit mysite/setting.py command, it is a simple Python module consists of levels for presenting or displaying Django settings.
By default Django uses SQLite; this also makes easy for Django users in case of any other type of installations. For example, if your database choice is different then you need to follow certain keys in the DATABASE like default items to match database connection settings.
- Engines: By these engines you change the database by using commands such as ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.sqlite3’, ‘django.db.backends.oracle’, ‘django.db.backends.mysql’, and so on.
- Name: This represents the name of your own database. If you are familiar with using SQLite as your database, in such case database is available as a file on your particular system. Moreover, the name should be as a fully absolute or exact path along with the file name of the particular file.
- Suppose if we are not using SQlite as your database then additional settings such password, user, the host must be added.
Django mainly uses SQLite as its default database to store entire information in a single file of the filesystem. If you want to use different database servers rather than SQLite, then make use of database administration tools to create a new database for the Django project. Another way is by using your own database in that place, and remaining is to explain Django about how to use it. This is the place in which Python’s project settings.py file comes into the picture.
We need to add the below code to the setting.py file:
1
2
3
4
5
6
| DATABASE = { ‘Default’ : { ‘ENGINE’ : ‘django.db.backends.sqlite3’, ‘NAME’ : os.path.join(BASE_DIR, ‘db.sqlite3’), } } |
64Q. List out the inheritance styles in Django?
Ans: There are three possible inheritance styles in Django, and they are:
- Proxy models: This style is mainly used for those who want to modify the Python level behaviour of the model, without modifying the model’s fields.
- Abstract Base Classes: This inheritance style is used only when we want to make parent class hold the data which they don’t want to repeat it again in the child class.
- Multi-table Inheritance: This inheritance style is used only when we want to subclass an existing model and there must a database table designed for each model on its own.
65Q. How to save an image locally using Python in which we already know the URL address?
Ans: The following code is used to save the image locally from the URL address which we know.
1
2
| import urllib.request urllib.request.urlretrieve( "URL" , "local-filename.jpg" ) |
66Q. How can we access sessions in flask?
Ans: A session will basically allow us to remember information from one request to another. In a flask, a signed cookie is used to make the user look at the session contents and modify them. Moreover, the user can change the session only when the secret key named Flask.secret_key is present.
67Q. Is flask an MVC model? If yes, justify your answer by showing an example of your application with the help of MVC pattern?
Ans: Basically, flask is a minimalistic framework that behaves the same as MVC framework. So MVC will be perfectly suitable for the flask and we will consider the MVC pattern in the below example.
1
2
3
4
5
6
7
| from flask import Flask In this code your, app = Flask(_name_) @app.route(“/”) Def hey(): return “Welcome to Appmajix” app.run(debug = True) |
The following code can be fragmented into
Configuration part will be,
1
2
| In this code your, app = Flask(_name_) |
View part will be,
1
2
3
| @app.route(“/”) Def hey(): return “Welcome to Appmajix” |
While your main part will be,
1
| app.run(debug = True) |
68Q. What are the database connections in Python Flask, explain?
Ans: Database powered applications are supported by flask. The relational database systems need to create a schema that requires piping the schema.sql file into a SQLite3 command. So, in this case you need to install SQLite3 command on your system to initiate and create the database in the flask.
We can request a database using flask in three ways, and they are:
- before_request(): Using this we can request database before only without passing arguments.
- after_request(): This method is called after requesting the database and also send the response to client.
- teardown_request(): This method is called in the cases where the responses are not guaranteed and the exception is raised. They have no access to modify the request.
69Q. Explain the procedure to minimize or lower the outages of Memcached server in your Python development?
Ans: The following are the steps used to minimize the outages of the Memcached server in your Python development, and they are.
- When a single instance fails, this will impact on larger load of the database server. The client makes the request when the data is reloaded. In order to avoid this, the code that you have written must be used to lower cache stampedes then it will used to leave a minimal impact.
- The other way is to bring out the instance of the memcached on a new machine by using the IP address of the lost machine.
- Another important option is to lower the server outages is code. This code provides you the liberty to modify the memcached server list with minimal work
- Another way is by setting timeout value that will be one of the options for memcac12345
Class Student:
def __init__(self, name):
self.name = name
S1=Student(
"XYZ"
)
print(S1.name)
70Q. What is Dogpile effect?
Ans: This is defined as an occurrence of event when the cache expires and also when the websites are hit with more number of requests by the client at a time. This dogpile effect can be averted by the use of a semaphore lock. If in the particular system the value expires then, first of all, the particular process receives the lock and begin generating new value.
71Q. What are the OOPS concepts available in Python?
Ans: Python is also object-oriented programming language like other programming languages. It also contains different OOPS concepts, and they are
- Object
- Class
- Method
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
72Q. Define object in Python?
Ans: An object in Python is defined as an instance that has both state and behaviour. Everything in Python is made of objects.
73Q. What is a class in Python?
Ans: Class is defined as a logical entity that is a huge collection of objects and it also contains both methods and attributes.
74Q. How to create a class in Python?
Ans: In Python programming, the class is created using a class keyword. The syntax for creating a class is as follows:
1
2
| class ClassName: #code (statement-suite) |
Example of creating a class in Python.
Output:
1
| XYZ |
75Q. What is the syntax for creating an instance of a class in Python?
Ans: The syntax for creating an instance of a class is as follows:
1
| <object-name> = <class-name>(<arguments>) |
76Q. Define what is “Method” in Python programming?
Ans: The Method is defined as the function associated with a particular object. The method which we define should not be unique as a class instance. Any type of objects can have methods.
77Q. Does multiple inheritances is supported in Python?
Ans: Multiple inheritance is supported in python. It is a process that provides flexibility to inherit multiple base classes in a child class.
Example of multiple inheritance in Python is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
| class Calculus: def Sum(self,a,b): return a+b; class Calculus1: def Mul(self,a,b): return a*b; class Derived(Calculus,Calculus1): def Div(self,a,b): return a/b; d = Derived() print(d.Sum(10,30)) print(d.Mul(10,30)) print(d.Div(10,30)) |
Output:
1
2
3
| 40 300 0.3333 |
78Q. What is data abstraction in Python?
Ans: In simple words, abstraction can be defined as hiding of unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal process and showing only the functionality. In Python abstraction can be achieved using encapsulation.
79Q. Define encapsulation in Python?
Ans: Encapsulation is one of the most important aspects of object-oriented programming. Binding or wrapping of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to restrict access to methods and variables.
80Q. What is polymorphism in Python?
Ans: By using polymorphism in Python we will understand how to perform a single task in different ways. For example, designing a shape is the task and various possible ways in shapes are a triangle, rectangle, circle, and so on.
81Q. Does Python make use of access specifiers?
Ans: Python does not make use of access specifiers and also it does not provide a way to access an instance variable. Python introduced a concept of prefixing the name of the method, function, or variable by using a double or single underscore to act like the behaviour of private and protected access specifiers.
82Q. How can we create an empty class in Python?
Ans: Empty class in Python is defined as a class that does not contain any code defined within the block. It can be created using pass keyword and object to this class can be created outside the class itself.
Example:
1
2
3
4
5
| class x: pass obj=x() obj.id= "123" print( "Id = " ,obj.id) |
Output:
1
| 123 |
83Q. Define Constructor in Python?
Ans: Constructor is a special type of method with a block of code to initialize the state of instance members of the class. A constructor is called only when the instance of the object is created. It is also used to verify that they are sufficient resources for objects to perform a specific task.
There are two types of constructors in Python, and they are:
- Parameterized constructor
- Non-parameterized constructor
84Q. How can we create a constructor in Python programming?
Ans: The _init_ method in Python stimulates the constructor of the class. Creating a constructor in Python can be explained clearly in the below example.
1
2
3
4
5
6
7
8
9
10
11
12
| class Student: def __init__(self,name,id): self.id = id; self.name = name; def display (self): print( "ID: %d nName: %s" %(self.id,self.name)) stu1 =Student( "nirvi" ,105) stu2 = Student( "tanvi" ,106) #accessing display() method to print employee 1 information stu1.display(); #accessing display() method to print employee 2 information stu2.display(); |
Output:
1
2
3
4
| ID: 1 Name: nirvi ID: 106 Name: Tanvi |
85Q. Define Inheritance in Python?
Ans: When an object of child class has the ability to acquire the properties of a parent class then it is called inheritance. It is mainly used to acquire runtime polymorphism and also it provides code reusability.
Sample Python Programs
1. In-place swapping of two numbers
1
2
3
4
| p, q = 20, 40 print(p, q) p, q = q, p print(p, q) |
Output:
1
2
| 20 40 40 20 |
2. Reversing a String in Python
1
2
| x = "MindmajixTraining" print( "Reverse is" , x[: : -1] |
Output:
1
| Reverse is gniniarTxijamdniM |
3. Create a single string from all the elements in the list
1
2
| x = [ "Mindmajix" , "Online" , "Training" ] print( " " .join(x)) |
Output:
1
| Mindmajix Online Training |
4. Use of Enums in Python
1
2
3
4
5
6
| class Training: Mindmajix, Online, Mindmajix = range(3) print(MyName.Mindmajix) print(MyName.Online) print(MyName.Mindmajix) |
Output:
1
2
3
| 2 1 2 |
5. Return multiple values from functions
1
2
3
4
| def a(): return 4, 5, 6, 7 p, q, r, s = a() print(p, q, r, s) |
Output:
1
| 4, 5, 6, 7 |
6. Print String N times
1
2
3
| n = 3 x = "Mindmajix" ; print(a * n) |
Output:
1
| MindmajixMindmajixMindmajix |
7. Check the memory usage of an object
1
2
3
| import sys x = 10 print(sys.getsizeof(x)) |
Output:
1
|
8. Find the most frequent value in a list
1
2
| test = [1, 2, 3, 9, 2, 7, 3, 5, 9, 9, 9] print(max(set(test), key = test.count)) |
Output:
1
| 9 |
9. Checking whether the two words are anagrams or not
1
2
3
4
5
| from collections import Counter def is_anagram(str1, str2): return Counter(str1) == Counter(str2) print(is_anagram( 'majix' , 'magic' )) print(is_anagram( 'majix' , 'xijam' )) |
Output:
False True
10. Print the file path of imported modules
1
2
3
4
| import os; import socket; print(os) print(socket) |
Output:
1
2
| <module 'os' from '/usr/lib/python3.5/os.py' > <module 'socket' from '/usr/lib/python3.5/socket.py' > |
No comments:
Post a Comment