80 QUESTIONS The Ultimate PythonMastery
Curated by What is Python? List some popular applications of Python in the world of technology. Python is a widely-used general-purpose, high-level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code. System Scripting Web Development Game Development Software Development Complex Mathematics It is used for: Question 1 Curated by
System Scripting Web Development Game Development Software Development Complex Mathematics Complex Mathematics Complex Mathematics Complex Mathematics What are the benefits of using Python language as a tool in the present scenario? The following are the benefits of using Python language Question 2 Curated by Curated by Tutort Provides Dedicated Placement Team
Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc. Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc. Is Python a compiled language or an interpreted language? What does the ‘#’ Symbol in Python? What is the difference between a Mutable data type and an Immutable data type? Actually, Python is a partially compiled language and partially interpreted language. The compilation part is done first when we execute our code and this will generate byte code internally. This byte code gets converted by the Python virtual machine(p.v.m) according to the underlying platform(machine+operating system). ‘#’ is used to comment on everything that comes after on the line. Question Question Question 3 4 5 Curated by Curated by
The set is an unordered collection of data types that is iterable, mutable and has no duplicate elements. A dictionary in Python is an unordered collection of data values, used to store data values like a map. How are arguments passed by value or by reference in Python? What is the difference between a Set and Dictionary? Everything in Python is an object and all variables hold references to the objects. The reference values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if they are mutable. Question Question 6 7 Curated by Curated by
For example - For example - my_list = [i for i in range(1, 10)] a = lambda x, y : x*y print(a(7, 19)) What is List Comprehension? Give an Example. What is a lambda function? List comprehension is a syntax construction to ease the creation of a list based on an existing iterable. A lambda function is an anonymous function. This function can have any number of parameters but can have just one statement. Question Question 8 9 Curated by Curated by
What is the difference between / and // in Python? // represents floor division whereas / represents precise division. 5//2 = 2 5/2 = 2.5 Placed at Guaranteed Job Referrals Highest CTC 100% Hiring Partners 350+ 2.1CR One of the best institutes for getting started with DSA and System Design. It also assisted me in launching my technical career and in honing my problem-solving and coding abilities. I was placed in more than 6+ product based companies because of their constant support. Avishkar Dalvi Question 11 What is a pass in Python? Pass means performing no operation or in other words, it is a placeholder in the compound statement, where there should be a blank left and nothing has to be written there. Question 10 Curated by Curated by
The beauty of the final block is to execute the code after trying for an error. This block gets executed irrespective of whether an error occurred or not. Finally block is used to do the required cleanup activities of objects/variables. There are 3 main keywords i.e. try, except, and finally which are used to catch exceptions and handle the recovering mechanism accordingly. Try is the block of a code that is monitored for errors. Except the block gets executed when an error occurs. string = "Hello Pune" string.swapcase() ---> "hELLO pUNE" How is Exceptional handling done in Python? What is a swapcase function in Python? It is a string’s function that converts all uppercase characters into lowercase and vice versa. It is used to alter the existing case of the string. This method creates a copy of the string which contains all the characters in the swap case. Question 13 Question 12 Curated by Curated by
The “while” loop is the actual looping feature that is used in any other programming language. Programmers use a Python while loop where they just have the end conditions. The “for” Loop is generally used to iterate through the elements of various collection types such as List, Tuple, Set, and Dictionary. Developers use a “for” loop where they have both the conditions start and the end. Difference between for loop and while loop in Python Question 14 Can we Pass a function as an argument in Python? Yes, Several arguments can be passed to a function, including objects, variables (of the same or distinct data types), and functions. Functions can be passed as parameters to other functions because they are objects. Higher-order functions are functions that can take other functions as arguments. Question 15 Curated by Curated by
What are *args and *kwargs? Is Indentation Required in Python? To pass a variable number of arguments to a function in Python, use the special syntax *args and **kwargs in the function specification. It is used to pass a variable-length, keyword-free argument list. By using the *, the variable we associate with the * becomes iterable, allowing you to do operations on it such as iterating over it and using higher- order operations like map and filter. Yes, indentation is required in Python. A Python interpreter can be informed that a group of statements belongs to a specific block of code by using Python indentation. Indentations make the code easy to read for developers in all programming languages but in Python, it is very important to indent the code in a specific order. Question Question 16 17 Curated by Curated by
Global variables: Global variables are the ones that are defined and declared outside any function and are not specified to any function. Module-level scope: It refers to the global objects of the current module accessible in the program. Outermost scope: It refers to any built-in names that the program can call. The name referenced is located last among the objects in this scope. Local variable: Local variables are those that are initialized within a function and are unique to that function. It cannot be accessed outside of the function. What is Scope in Python? The location where we can find a variable and also access it if required is called the scope of a variable. Question 18 Curated by Curated by
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. Statically typed languages: In this type of language, the data type of a variable is known at the compile time which means the programmer has to specify the data type of a variable at the time of its declaration. Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method, or function declaration. All functions should have a docstring. Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function. What is docstring in Python? Question 19 What is a dynamically typed language? Typed languages are the languages in which we define the type of data type and it will be known by the machine at the compile-time or at runtime. Typed languages can be classified into two categories: Question 20 Curated by Curated by
The break statement is used to terminate the loop or statement in which it is present. After that, the control will pass to the statements that are present after the break statement, if available. Continue is also a loop control statement just like the break statement. The continue statement is opposite to that of the break statement, instead of terminating the loop, it forces the execution of the next iteration of the loop. Pass means performing no operation or in other words, it is a placeholder in the compound statement, where there should be a blank left and nothing has to be written there. Dynamically typed languages: These are the languages that do not require any pre-defined data type for any variable as it is interpreted at runtime by the machine itself. In these languages, interpreters assign the data type to a variable at runtime depending on its value. What is a break, continue, and pass in Python? Question 21 Curated by Curated by Curated by
Numeric: The numeric data type in Python represents the data that has a numeric value. A numeric value can be an integer, a floating number, a Boolean, or even a complex number. Sequence Type: The sequence Data Type in Python is the ordered collection of similar or different data types. There are several sequence types in Python: String List Tuple Dictionary Range Mapping Types: In Python, hashable data can be mapped to random objects using a mapping object. There is currently only one common mapping type, the dictionary, and mapping objects are mutable. Set: In Python, a Set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. What are Built-in data types in Python? The following are the standard or built-in data types in Python: Question 22 Curated by Curated by
range() – This returns a list of numbers created using the range() function. xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called lazy evaluation. How do you floor a number in Python? What is the difference between xrange and range functions? The Python math module includes a method that can be used to calculate the floor of a number. floor() method in Python returns the floor of x i.e., the largest integer not greater than x. ceil(x) in Python returns a ceiling value of x i.e., the smallest integer greater than or equal to x. range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python 3, there is no xrange, but the range function behaves like xrange in Python 2. Question Question 23 24 Curated by Curated by
What is Dictionary Comprehension? Give an Example Is Tuple Comprehension? If yes, how, and if not why? my_dict = {i:1+7 for i in range(1, 10)} Dictionary Comprehension is a syntax construction to ease the creation of a dictionary based on the existing iterable. Tuple comprehension is not possible in Python because it will end up in a generator, not a tuple comprehension. Question Question 25 26 (i for i in (1, 2, 3)) Curated by Curated by
Lists are Mutable data types. LISTS TUPLES Tuples are Immutable data types. Lists consume more memory Tuple consumes less memory as compared to the list The implication of iterations is comparatively Faster A Tuple data type is appropriate for accessing the elements The implication of iterations is Time-consuming The list is better for performing operations, such as insertion and deletion. Differentiate between List and Tuple? What is the difference between a shallow copy and a deep copy? Let’s analyze the differences between List and Tuple: Shallow copy is used when a new instance type gets created and it keeps values that are copied whereas deep copy stores values that are already copied. A shallow copy has faster program execution whereas a deep copy makes it slow. Question Question 27 28 Curated by Curated by
Which sorting technique is used by sort() and sorted() functions of python? What are Decorators? Python uses the Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data. Decorators in simple terms is the specific change that we make in Python syntax to alter functions easily. Question Question 29 30 Curated by Curated by our Success Story GunjanBhadani From To our Success Story GunjanBhadani From To
In Python, we can use the debugger pdb for debugging the code. To start debugging we have to enter the following lines on the top of a Python script. import pdb pdb.set_trace() After adding these lines, our code runs in debug mode. Now we can usecommands like breakpoint, step through, step into etc for debugging. By using this command we can debug a Python program: $ python -m pdb python-script.py How do you debug a Python program? Question 31 What are Iterators in Python? In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are collections of items, and they can be a list, tuples, or a dictionary. Python iterator implements __itr__ and the next() method to iterate the stored elements. We generally use loops to iterate over the collections (list, tuple) in Python. Question 32 Curated by Curated by
In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implement __itr__ and next() method and reduces other overheads as well. If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resumes from the same when required. What are Generators in Python? Question 33 Does Python support multiple Inheritance? Python does support multiple inheritances, unlike Java. Multiple inheritances mean that a class can be derived from more than one parent class. Question 34 Curated by Curated by
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism. Encapsulation means binding the code and the data together. A Python class is an example of encapsulation. What is Polymorphism and encapsulation in Python? Question 35 What is garbage collection in Python? A garbage collection in Python manages the memory automatically and heap allocation. In simpler terms, the process of automatic deletion of unwanted or unused objects to free the memory is called garbage collection in Python. Question 36 Curated by Curated by
How do you do data abstraction in Python? How is memory management done in Python? Data Abstraction is providing only the required details and hides the implementation from the world. It can be achieved in Python by using interfaces and abstract classes. Python uses its private heap space to manage the memory. Basically, all the objects and data structures are stored in the private heap space. Even the programmer can not access this private space as the interpreter takes care of this space. Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space. Question Question 37 38 Curated by Curated by
os.remove() os.unlink() Lst[ Initial : End : IndexJump ] How to delete a file using Python? What is slicing in Python? We can delete a file using Python by following approaches: Python Slicing is a string operation for extracting a part of the string, or some part of a list. With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. Question Question 39 40 Curated by Curated by
What is a namespace in Python? What is PIP? What is a zip function? A namespace is a naming system used to make sure that names are unique to avoid naming conflicts. PIP is an acronym for Python Installer Package which provides a seamless interface to install various Python modules. It is a command-line tool that can search for packages over the internet and install them without any user interaction. Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples. Question Question Question 41 42 43 Curated by Curated by
What are Pickling and Unpickling? How can we do Functional programming in Python? The Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling. Python has a module named pickle. This module has the implementation of a powerful algorithm for serialization and deserialization of Python object structure. In Functional Programming, we decompose a program into functions. These functions take input and after processing give an output. The function does not maintain any state. Python provides built-in functions that can be used for Functional programming. Question Question 44 45 Curated by Curated by
Map() reduce() filter() Some of these functions are: Event iterators and generators can be used for Functional programming in Python. What is __init__() in Python? Write a code to display the current time? Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables. Question Question 46 47 current_time= time.localtime() print (“Current time is”, current_time) Curated by Curated by
Public Access Modifier: The members of a class that are declared public are easily accessible from any part of the program. All data members and member functions of a class are public by default. Protected Access Modifier: The members of a class that are declared public are easily accessible from any part of the program. All data members and member functions of a class are public by default. Private Access Modifier: The members of a class that are declared private are accessible within the class only, the private access modifier is the most secure access modifier. Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class. What are Access Specifiers in Python? Python uses the ‘_’ symbol to determine the access control for a specific data member or a member function of a class. A Class in Python has three types of Python access modifiers: Question 48 Curated by Curated by
What are unit tests in Python? Python Global Interpreter Lock (GIL)? The Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling. Python has a module named pickle. This module has the implementation of a powerful algorithm for serialization and deserialization of Python object structure. Python Global Interpreter Lock (GIL) is a type of process lock that is used by Python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. The performance of the single-threaded process and the multi-threaded process will be the same in Python and this is because of GIL in Python. We can not achieve multithreading in Python because we have a global interpreter lock that restricts the threads and works as a single thread. Question Question 49 50 Curated by Curated by
Function Annotation is a feature that allows you to add metadata to function parameters and return values. This way you can specify the input type of the function parameters and the return type of the value the function returns. Function annotations are arbitrary Python expressions that are associated with various parts of functions. These expressions are evaluated at compile time and have no life in Python’s runtime environment. Python does not attach any meaning to these annotations. They take life when interpreted by third-party libraries, for example, mypy. What are Function Annotations in Python? Question 51 Curated by Curated by Courses Offered by Tutort Academy Data Analytics and
 Business Analytics Program Data Science and
 Artificial Intelligence Program Learn more Learn more
TheExceptionGroupcanbehandledusinganewexcept* syntax.The*symbolindicatesthatmultipleexceptions canbehandledbyeachexcept*clause. ExceptionGroupisacollection/groupofdifferentkindsof Exception.WithoutcreatingMultipleExceptionswecan grouptogetherdifferentExceptionswhichwecanlater fetchonebyonewhenevernecessary,theorderinwhich theExceptionsarestoredintheExceptionGroupdoesn’t matterwhilecallingthem. try: raiseExceptionGroup('ExampleExceptionGroup',( TypeError('ExampleTypeError'), ValueError('ExampleValueError'), KeyError('ExampleKeyError'), AttributeError('ExampleAttributeError') )) except*TypeError: ... except*ValueErrorase: ... except*(KeyError,AttributeError)ase: ... WhatareExceptionGroupsinPython? Question 52 Curatedby Curatedby
match term: case pattern-1: action-1 case pattern-2: action-2 case pattern-3: action-3 case _: action-default What is Python Switch Statement Python has implemented a switch case feature called “structural pattern matching”. You can implement this feature with the match and case keywords. Note that the underscore symbol is what you use to define a default case for the switch statement in Python. Note: Before Python 3.10 Python didn't support match Statements. Question 53 Curated by Curated by
>>> thelist=['a','b'] >>> for i,j in enumerate(thelist): ... print i,j ... 0 a 1 b High readability reduces cost of program maintenance open source support third party packages modularity code reverse. What is the improvement in the enumerate() function of Python? In Python, enumerate() function is an improvement over regular iteration. The enumerate() function returns an iterator that gives (0, item[0]). Question 54 uses and benefits of python Question 55 Curated by Curated by
Static- data types are checked before execution. dynamic- data type are checked during execution Tutort Benefits 24x7 Live 1:1 Video based doubt support 1:1 Mentorship from Industry experts Resume building & Mock Interview Preparations Special support for foreign students Dynamically typed language? Typing refers to type checking in programming language storing type language such as a Python 1 + 2 will result in type error since this language don't allow for “type coercion” (implicit conversion of data types) on the other hand a weekly type data weakly typed language such as JS will simply output 12 to a result Two stage of a Typing- checking Question 56 Curated by Curated by
Class address: def __init__(mine,street,number): Mine.street = street Mine.number = number Def myfunc(abc): print(“my address is “ abc,street) P1 = address(“Albert street”,20) p1.myfunc() What is self in code? self represents the instances of class . These handy keywords allow you to access the variables, attributes and methods of a defined class in Python. Self parameter doesn't have to be you named ‘self’ as you can call it by any other home however the self parameter must always be the first parameter of any class function regardless of a name choose chosen so instead of selfie you call you ‘mine’ or ‘ours’ or anything else Question 57 Curated by Curated by
What is comprehension in Python? It provide us with the short and a concise way to construct a new sequences [such as a list set dictionary etc] using sequences which have been already defined Python supports four types of a comprehension Question 58 A. List comprehension- it provide an elegant way to create a new list.The following is the basic structure of a list comprehension output list= [ output_execution for var in input_list if (var satisfy this condition)] Note - list comprehension may or may not contain and if condition list comprehension can contain multiple for nested list conference comprehension list comprehension set comprehension dictionary comprehension generator comprehension Curated by Curated by
#without using list comprehension Input_list = [1, 2, 3, 4, 4, 5, 6, 7,7] Output_list=[ ] #look for constructing output for var in input_list: If var % 2 ==0: Output_list.append(var) print(“Output list using for loop, output_list) # Constructing output list using for loop output list is equal to[] for war in range(1, 10): output_list.append(var ** 2): print(“Output list using for loops: “,output_list ) 1. example one suppose we want to create an output list which contains only the even number which are present in the input list let's see how to do this using for loops and list comprehension and decide which method suits better Output = output list using for loop : [2 4 4 6] output = output list using for loop : [1 4 9 16 25 36 49 64 81] 2. Suppose we want to create an output list which contains squares of all the numbers from 1 to 9 let's see how to do this using for loops and list comprehension Curated by Curated by
B. Dictionary comprehension Extending the idea of list comprehensions, we can also create a dictionary using dictionary comprehensions. The basic structure of a dictionary comprehension looks like below. Example #1: Suppose we want to create an output dictionary which contains only the odd numbers that are present in the input list as keys and their cubes as values. Let’s see how to do this using for loops and dictionary comprehension. output = output list using for comprehension: [1 4 9 16 25 36 49 64 81] #using list comprehension list_using_comprehension=[ var * 2 for var in range(1,10)] print(“Output list using for loops: “, list_using_comprehension ) output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)} Curated by Curated by
Example #2: Given two lists containing the names of states and their corresponding capitals, construct a dictionary which maps the states with their respective capitals. Let’s see how to do this using for loops and dictionary comprehension. Output: Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343} Output: Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7: 343} input_list = [1, 2, 3, 4, 5, 6, 7] output_dict = {} # Using loop for constructing output dictionary for var in input_list: if var % 2 != 0: output_dict[var] = var**3 print("Output Dictionary using for loop:", output_dict ) # Using Dictionary comprehensions # for constructing output dictionary input_list = [1,2,3,4,5,6,7] dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0} print("Output Dictionary using dictionary comprehensions:", dict_using_comp) Curated by Curated by
Output Output Dictionary using for loop: {'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur'} Output: Output Dictionary using dictionary comprehensions: {'Rajasthan': 'Jaipur', 'Maharashtra': 'Mumbai', 'Gujarat': 'Gandhinagar'} state = ['Gujarat', 'Maharashtra', 'Rajasthan'] capital = ['Gandhinagar', 'Mumbai', 'Jaipur'] output_dict = {} # Using loop for constructing output dictionary for (key, value) in zip(state, capital): output_dict[key] = value print("Output Dictionary using for loop:", output_dict) # Using Dictionary comprehensions # for constructing output dictionary state = ['Gujarat', 'Maharashtra', 'Rajasthan'] capital = ['Gandhinagar', 'Mumbai', 'Jaipur'] dict_using_comp = {key:value for (key, value) in zip(state, capital)} print("Output Dictionary using dictionary comprehensions:", dict_using_comp) Curated by Curated by
C. set comprehension: Set comprehensions are pretty similar to list comprehensions. The only difference between them is that set comprehensions use curly brackets { }. Let’s look at the following example to understand set comprehensions. Example #1 : Suppose we want to create an output set which contains only the even numbers that are present in the input list. Note that set will discard all the duplicate values. Let’s see how we can do this using for loops and set comprehension. Output: Output Set using for loop: {2, 4, 6} input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7] output_set = set() # Using loop for constructing output set for var in input_list: if var % 2 == 0: output_set.add(var) print("Output Set using for loop:", output_set) Curated by Curated by
D. generator comprehension Generator Comprehensions are very similar to list comprehensions. One difference between them is that generator comprehensions use circular brackets whereas list comprehensions use square brackets. The major difference between them is that generators don’t allocate memory for the whole list. Instead, they generate each value one by one which is why they are memory efficient. Let’s look at the following example to understand generator comprehension: Output: Output Set using set comprehensions: {2, 4, 6} # Using Set comprehensions # for constructing output set input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7] set_using_comp = {var for var in input_list if var % 2 == 0} print("Output Set using set comprehensions:",set_using_comp) Curated by Curated by
Output: Output values using generator comprehensions: 2 4 4 6 input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] output_gen = (var for var in input_list if var % 2 == 0) print("Output values using generator comprehensions:", end = ' ') for var in output_gen: print(var, end = ' ') Curated by Curated by Courses Offered by Tutort Data Science and
 Artificial Intelligence Program Data Analytics and
 Business Analytics Program Learn more Learn more Full Stack Specialisation
 In Software Development Learn more Data Structures and Algorithms
 with System Design Learn more
Output:- 6 def plus_one(number): return number + 1 add_one = plus_one add_one(5) What is a decorator? A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate. ● Assigning Functions to Variables To kick us off we create a function that will add one to a number whenever it is called. We'll then assign the function to a variable and use this variable to call the function. Question 59 Curated by Curated by
● Defining Functions Inside other Functions Next, we'll illustrate how you can define a function inside another function in Python. Stay with me, we'll soon find out how all this is relevant in creating and understanding decorators in Python. ● Passing Functions as Arguments to other Functions Functions can also be passed as parameters to other functions. Let's illustrate that below. Output:- 5 Output:- 5 def plus_one(number): def add_one(number): return number + 1 result = add_one(number) return result plus_one(4) def plus_one(number): return number + 1 def function_call(function): number_to_add = 5 return function(number_to_add) function_call(plus_one) Curated by Curated by
●FunctionsReturningotherFunctions Afunctioncanalsogenerateanotherfunction.We'llshow thatbelowusinganexample. ●NestedFunctionshaveaccesstotheEnclosing Function'sVariableScope Pythonallowsanestedfunctiontoaccesstheouterscope oftheenclosingfunction.Thisisacriticalconceptin decorators--thispatternisknownasaClosure. Output:-‘hi’ Output:-Somerandommessage defhello_function(): defsay_hi(): return"Hi" returnsay_hi hello=hello_function() hello() defprint_message(message): "EnclosingFunction" defmessage_sender(): "NestedFunction" print(message) message_sender() print_message("Somerandommessage") Curatedby Curatedby
● Creating Decorators With these prerequisites out of the way, let's go ahead and create a simple decorator that will convert a sentence to uppercase. We do this by defining a wrapper inside an enclosed function. As you can see it is very similar to the function inside another function that we created earlier. Our decorator function takes a function as an argument, and we shall, therefore, define a function and pass it to our decorator. We learned earlier that we could assign a function to a variable. We'll use that trick to call our decorator function. Output 'HELLO THERE' def uppercase_decorator(function): def wrapper(): func = function() make_uppercase = func.upper() return make_uppercase return wrapper def say_hi(): return 'hello there' decorate = uppercase_decorator(say_hi) decorate() Curated by Curated by
Output 'HELLO THERE' @uppercase_decorator def say_hi(): return 'hello there' say_hi() def split_string(function): def wrapper(): func = function() splitted_string = func.split() return splitted_string return wrapper @split_string @uppercase_decorator def say_hi(): return 'hello there' say_hi() ['HELLO', 'THERE'] We can use multiple decorators to a single function. However, the decorators will be applied in the order that we've called them. Below we'll define another decorator that splits the sentence into a list. We'll then apply the uppercase_decorator and split_string decorator to a single function. However, Python provides a much easier way for us to apply decorators. We simply use the @ symbol before the function we'd like to decorate. Let's show that in practice below. Curated by Curated by
From the above output, we notice that the application of decorators is from the bottom up. Had we interchanged the order, we'd have seen an error since lists don't have an upper attribute. The sentence has first been converted to uppercase and then split into a list. ● Accepting Arguments in Decorator Functions Sometimes we might need to define a decorator that accepts arguments. We achieve this by passing the arguments to the wrapper function. The arguments will then be passed to the function that is being decorated at call time. Output My arguments are: Nairobi, Accra Cities I love are Nairobi and Accra def decorator_with_arguments(function): def wrapper_accepting_arguments(arg1, arg2): print("My arguments are: {0}, {1}".format(arg1,arg2)) function(arg1, arg2) return wrapper_accepting_arguments @decorator_with_arguments def cities(city_one, city_two): print("Cities I love are {0} and {1}".format(city_one, city_two)) cities("Nairobi", "Accra") Curated by Curated by
●DefiningGeneralPurposeDecorators Todefineageneralpurposedecoratorthatcanbeappliedto anyfunctionweuseargsand**kwargs.argsand**kwargs collectallpositionalandkeywordargumentsandstorethem intheargsandkwargsvariables.argsandkwargsallowusto passasmanyargumentsaswewouldlikeduringfunction calls. Let'sseehowwe'dusethedecoratorusingpositional arguments. def a_decorator_passing_arbitrary_arguments(function _to_decorate): def a_wrapper_accepting_arbitrary_arguments(*args,** kwargs): print('Thepositionalargumentsare',args) print('Thekeywordargumentsare',kwargs) function_to_decorate(*args) returna_wrapper_accepting_arbitrary_arguments @a_decorator_passing_arbitrary_arguments deffunction_with_no_argument(): print("Noargumentshere.") function_with_no_argument() Thepositionalargumentsare() Thekeywordargumentsare{} Noargumentshere. Curatedby Curatedby
Keyword arguments are passed using keywords. An illustration of this is shown below. The positional arguments are () The keyword arguments are {'first_name': 'Derrick', 'last_name': 'Mwiti'} This has shown keyword arguments ● Passing Arguments to the Decorator Now let's see how we'd pass arguments to the decorator itself. In order to achieve this, we define a decorator maker that accepts arguments then defines a decorator inside it. We then define a wrapper function inside the decorator as we did earlier. @a_decorator_passing_arbitrary_arguments def function_with_arguments(a, b, c): print(a, b, c) function_with_arguments(1,2,3) The positional arguments are (1, 2, 3) The keyword arguments are {} 1 2 3 @a_decorator_passing_arbitrary_arguments def function_with_keyword_arguments(): print("This has shown keyword arguments") function_with_keyword_arguments(first_name="Der rick", last_name="Mwiti") Curated by Curated by
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2, decorator_arg3): def decorator(func): def wrapper(function_arg1, function_arg2, function_arg3) : "This is the wrapper function" print("The wrapper can access all the variablesn" "t- from the decorator maker: {0} {1} {2}n" "t- from the function call: {3} {4} {5}n" "and pass them to the decorated function" .format(decorator_arg1, decorator_arg2,decorator_arg3, function_arg1, function_arg2,function_arg3)) return func(function_arg1, function_arg2,function_arg3) return wrapper return decorator pandas = "Pandas" @decorator_maker_with_arguments(pandas, "Numpy","Scikit-learn") def decorated_function_with_arguments(function_arg1, function_arg2,function_arg3): print("This is the decorated function and it only knows about its arguments: {0}" " {1}" " {2}".format(function_arg1, function_arg2,function_arg3)) decorated_function_with_arguments(pandas, "Science", "Tools") Curated by Curated by
The wrapper can access all the variables - from the decorator maker: Pandas Numpy Scikit-learn - from the function call: Pandas Science Tools and pass them to the decorated function This is the decorated function, and it only knows about its arguments: Pandas Science Tools In order to solve this challenge Python provides a functools.wraps decorator. This decorator copies the lost metadata from the undecorated function to the decorated closure. Let's show how we'd do that. ● Debugging Decorators As we have noticed, decorators wrap functions. The original function name, its docstring, and parameter list are all hidden by the wrapper closure: For example, when we try to access the decorated_function_with_arguments metadata, we'll see the wrapper closure's metadata. This presents a challenge when debugging. decorated_function_with_arguments.__name__ 'wrapper' decorated_function_with_arguments.__doc__ 'This is the wrapper function' Curated by Curated by
When we check the say_hi metadata, we notice that it is now referring to the function's metadata and not the wrapper's metadata. say_hi.__name__ 'say_hi' say_hi.__doc__ 'This will say hi' It is advisable and good practice to always use functools.wraps when defining decorators. It will save you a lot of headache in debugging. import functools def uppercase_decorator(func): @functools.wraps(func) def wrapper(): return func().upper() return wrapper @uppercase_decorator def say_hi(): "This will say hi" return 'hello there' say_hi() 'HELLO THERE' Curated by Curated by
● Python Decorators Summary Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated. Using decorators in Python also ensures that your code is DRY(Don't Repeat Yourself). Decorators have several use cases such as: Authorization in Python frameworks such as Flask and Django Logging Measuring execution time Synchronization What are Python Modules? Question 60 Files containing Python codes are referred to as Python Modules. This code can either be classes, functions, or variables and saves the programmer time by providing the predefined functionalities when needed. It is a file with “.py” extension containing an executable code. Commonly used built modules are listed below: os sys data time math random JSON Curated by Curated by
Pandas: Powerful Python Data Analysis Toolkit Seaborn: This is a statistical data visualization library in Python. SciKit: This is a machine learning library in Python. SciPy: This is an open source system for science, mathematics and engineering implemented in Python. What is pep 8? What are Python packages? What are the popular Python libraries used in Data analysis? PEP in Python stands for Python Enhancement Proposal. It is a set of rules that specify how to write and design Python code for maximum readability. A Python package refers to the collection of different sub- packages and modules based on the similarities of the function. Some of the popular libraries of Python used for Data analysis are: Question Question Question 61 62 62 Curated by Curated by
What is docstring in Python? Python lets users include a description (or quick notes) for their methods using documentation strings or docstrings. Docstrings are different from regular comments in Python as, rather than being completely ignored by the Python Interpreter like in the case of comments, these are defined within triple quotes. Using docstring as a comment. This code add two numbers """ x=7 y=9 z=x+y print(z) Question What is the difference between append() and extend() methods? 65 Question 64 Both append() and extend() methods are methods used to add elements at the end of a list. append(element): Adds the given element at the end of the list that called this append() method extend(another-list): Adds the elements of another list at the end of the list that called this extend() method Curated by Curated by
What are the common built-in data types in Python? Question 67 Immutable data types: Number , String, Tuple Mutable data types: List, Dictionary, Set How is Multithreading achieved in Python? Question 66 Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time. Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core. Python supports the below-mentioned built-in data types: Curated by Curated by
What is the difference between split() and slicing in Python? How can you randomize the items of a list in place in Python? Question Question 68 69 Both split() function and slicing work on a String object. By using split() function, we can get the list of words from a String. E.g. 'a b c '.split() returns [‘a’, ‘b’, ‘c’] Slicing is a way of getting substring from a String. It returns another String. E.g. >>> 'a b c'[2:3] returns b This can be easily achieved by using the Shuffle() function from the random library as shown below: Output: [‘Loves’,’He’ ,’To ,’In’, ‘Python’,’Code’] from random import shuffle List = ['He', 'Loves', 'To', 'Code', 'In', 'Python'] shuffle(List) print(List) Curated by Curated by
To access an element from ordered sequences, we simply use the index of the element, which is the position number of that particular element. The index usually starts from 0, i.e., the first element has index 0, the second has 1, and so on. Python Indexing When we use the index to access elements from the end of a list, it’s called reverse indexing. In reverse indexing, the indexing of elements starts from the last element with the index number ‘−1’. The second last element has index ‘−2’, and so on. These indexes used in reverse indexing are called negative indexes. Guaranteed Job Referrals Highest CTC 100% Hiring Partners 350+ 2.1CR Why Tutort Academy? What are negative indexes and why are they used? Question 70 Curated by Curated by
Explain split(), sub(), subn() methods of “re” module in Python? Question 71 These methods belong to the Python RegEx or ‘re’ module and are used to modify strings. split(): This method is used to split a given string into a list. sub(): This method is used to find a substring where a regex pattern matches, and then it replaces the matched substring with a different string. subn(): This method is similar to the sub() method, but it returns the new string, along with the number of replacements. Curated by Curated by
What is a map function in Python? Question 72 The map() function in Python has two parameters, function and iterable. The map() function takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It returns an object list of results. def calculateSq(n): return n*n numbers = (2, 3, 4, 5) result = map( calculateSq, numbers) print(result) Curated by Curated by
Python has various file processing modes. For opening files, there are three modes: For opening a text file using the above modes, we will have to append ‘t’ with them as follows: read-only mode (r) write-only mode (w) read–write mode (rw) read-only mode (rt) write-only mode (wt) read–write mode (rwt) Explain all file processing modes supported in Python? Question 73 Curated by Curated by
Similarly, a binary file can be opened by appending ‘b’ with them as follows: To append the content in the files, we can use the append mode (a): For text files, the mode would be ‘at’ For binary files, it would be ‘ab’ To remove duplicate elements from the list we use the set() function. Consider the below example: read-only mode (rb) write-only mode (wb) read–write mode (rwb) demo_list=[5,4,4,6,8,12,12,1,5] unique_list = list(set(demo_list)) output:[1,5,6,8,12] How will you remove duplicate elements from a list? Question 74 Curated by Curated by
How will you read a random line in a file? How can files be deleted in Python? Question Question 75 76 We can read a random line in a file using the random module. For example: You need to import the OS Module and use os.remove() function for deleting a file in python. consider the code below: import os os.remove("file_name.txt") import random def read_random(fname): lines = open(fname).read().splitlines() return random.choice(lines) print(read_random (‘hello.txt’)) Curated by Curated by
How can you generate random numbers in Python? What is slicing in Python? Question Question 77 78 This is achieved with importing the random module,it is the module that is used to generate random numbers. Syntax: Slicing is a process used to select a range of elements from sequence data type like list, string and tuple. Slicing is beneficial and easy to extract out the elements. It requires a : (colon) which separates the start index and end index of the field. All the data sequence types List or tuple allows us to use slicing to get the needed elements. Although we can get elements by specifying an index, we get only a single element whereas using slicing we can get a group or appropriate range of needed elements. Syntax - List_name[start:stop] import random random.random # returns the floating point random number between the range of [0,1]. Curated by Curated by
Define Constructor in Python? Question 79 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 Curated by Curated by Courses Offered by Tutort Academy Data Analytics and
 Business Analytics Program Data Science and
 Artificial Intelligence Program Learn more Learn more
How can we create a constructor in Python programming? Question 80 The _init_ method in Python stimulates the constructor of the class. Creating a constructor in Python can be explained clearly in the below example. Output: ID: 1 Name: nirvi ID: 106 Name: Tanvi 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(); Curated by Curated by
Start Your with us Upskilling www.tutort.net Follow us on Watch us on Youtube Read more on Quora Explore our courses Data Science and
 Artificial Intelligence Program Data Analytics and
 Business Analytics Program

🐍⚡ “Python Panache: Code Like a Pro, Not a Programmer!”

  • 1.
  • 2.
    Curated by What isPython? List some popular applications of Python in the world of technology. Python is a widely-used general-purpose, high-level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code. System Scripting Web Development Game Development Software Development Complex Mathematics It is used for: Question 1 Curated by
  • 3.
    System Scripting Web Development GameDevelopment Software Development Complex Mathematics Complex Mathematics Complex Mathematics Complex Mathematics What are the benefits of using Python language as a tool in the present scenario? The following are the benefits of using Python language Question 2 Curated by Curated by Tutort Provides Dedicated Placement Team
  • 4.
    Mutable data typescan be edited i.e., they can change at runtime. Eg – List, Dictionary, etc. Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc. Is Python a compiled language or an interpreted language? What does the ‘#’ Symbol in Python? What is the difference between a Mutable data type and an Immutable data type? Actually, Python is a partially compiled language and partially interpreted language. The compilation part is done first when we execute our code and this will generate byte code internally. This byte code gets converted by the Python virtual machine(p.v.m) according to the underlying platform(machine+operating system). ‘#’ is used to comment on everything that comes after on the line. Question Question Question 3 4 5 Curated by Curated by
  • 5.
    The set isan unordered collection of data types that is iterable, mutable and has no duplicate elements. A dictionary in Python is an unordered collection of data values, used to store data values like a map. How are arguments passed by value or by reference in Python? What is the difference between a Set and Dictionary? Everything in Python is an object and all variables hold references to the objects. The reference values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if they are mutable. Question Question 6 7 Curated by Curated by
  • 6.
    For example - Forexample - my_list = [i for i in range(1, 10)] a = lambda x, y : x*y print(a(7, 19)) What is List Comprehension? Give an Example. What is a lambda function? List comprehension is a syntax construction to ease the creation of a list based on an existing iterable. A lambda function is an anonymous function. This function can have any number of parameters but can have just one statement. Question Question 8 9 Curated by Curated by
  • 7.
    What is thedifference between / and // in Python? // represents floor division whereas / represents precise division. 5//2 = 2 5/2 = 2.5 Placed at Guaranteed Job Referrals Highest CTC 100% Hiring Partners 350+ 2.1CR One of the best institutes for getting started with DSA and System Design. It also assisted me in launching my technical career and in honing my problem-solving and coding abilities. I was placed in more than 6+ product based companies because of their constant support. Avishkar Dalvi Question 11 What is a pass in Python? Pass means performing no operation or in other words, it is a placeholder in the compound statement, where there should be a blank left and nothing has to be written there. Question 10 Curated by Curated by
  • 8.
    The beauty ofthe final block is to execute the code after trying for an error. This block gets executed irrespective of whether an error occurred or not. Finally block is used to do the required cleanup activities of objects/variables. There are 3 main keywords i.e. try, except, and finally which are used to catch exceptions and handle the recovering mechanism accordingly. Try is the block of a code that is monitored for errors. Except the block gets executed when an error occurs. string = "Hello Pune" string.swapcase() ---> "hELLO pUNE" How is Exceptional handling done in Python? What is a swapcase function in Python? It is a string’s function that converts all uppercase characters into lowercase and vice versa. It is used to alter the existing case of the string. This method creates a copy of the string which contains all the characters in the swap case. Question 13 Question 12 Curated by Curated by
  • 9.
    The “while” loopis the actual looping feature that is used in any other programming language. Programmers use a Python while loop where they just have the end conditions. The “for” Loop is generally used to iterate through the elements of various collection types such as List, Tuple, Set, and Dictionary. Developers use a “for” loop where they have both the conditions start and the end. Difference between for loop and while loop in Python Question 14 Can we Pass a function as an argument in Python? Yes, Several arguments can be passed to a function, including objects, variables (of the same or distinct data types), and functions. Functions can be passed as parameters to other functions because they are objects. Higher-order functions are functions that can take other functions as arguments. Question 15 Curated by Curated by
  • 10.
    What are *argsand *kwargs? Is Indentation Required in Python? To pass a variable number of arguments to a function in Python, use the special syntax *args and **kwargs in the function specification. It is used to pass a variable-length, keyword-free argument list. By using the *, the variable we associate with the * becomes iterable, allowing you to do operations on it such as iterating over it and using higher- order operations like map and filter. Yes, indentation is required in Python. A Python interpreter can be informed that a group of statements belongs to a specific block of code by using Python indentation. Indentations make the code easy to read for developers in all programming languages but in Python, it is very important to indent the code in a specific order. Question Question 16 17 Curated by Curated by
  • 11.
    Global variables: Globalvariables are the ones that are defined and declared outside any function and are not specified to any function. Module-level scope: It refers to the global objects of the current module accessible in the program. Outermost scope: It refers to any built-in names that the program can call. The name referenced is located last among the objects in this scope. Local variable: Local variables are those that are initialized within a function and are unique to that function. It cannot be accessed outside of the function. What is Scope in Python? The location where we can find a variable and also access it if required is called the scope of a variable. Question 18 Curated by Curated by
  • 12.
    Python documentation strings(or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. Statically typed languages: In this type of language, the data type of a variable is known at the compile time which means the programmer has to specify the data type of a variable at the time of its declaration. Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method, or function declaration. All functions should have a docstring. Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function. What is docstring in Python? Question 19 What is a dynamically typed language? Typed languages are the languages in which we define the type of data type and it will be known by the machine at the compile-time or at runtime. Typed languages can be classified into two categories: Question 20 Curated by Curated by
  • 13.
    The break statementis used to terminate the loop or statement in which it is present. After that, the control will pass to the statements that are present after the break statement, if available. Continue is also a loop control statement just like the break statement. The continue statement is opposite to that of the break statement, instead of terminating the loop, it forces the execution of the next iteration of the loop. Pass means performing no operation or in other words, it is a placeholder in the compound statement, where there should be a blank left and nothing has to be written there. Dynamically typed languages: These are the languages that do not require any pre-defined data type for any variable as it is interpreted at runtime by the machine itself. In these languages, interpreters assign the data type to a variable at runtime depending on its value. What is a break, continue, and pass in Python? Question 21 Curated by Curated by Curated by
  • 14.
    Numeric: The numericdata type in Python represents the data that has a numeric value. A numeric value can be an integer, a floating number, a Boolean, or even a complex number. Sequence Type: The sequence Data Type in Python is the ordered collection of similar or different data types. There are several sequence types in Python: String List Tuple Dictionary Range Mapping Types: In Python, hashable data can be mapped to random objects using a mapping object. There is currently only one common mapping type, the dictionary, and mapping objects are mutable. Set: In Python, a Set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. What are Built-in data types in Python? The following are the standard or built-in data types in Python: Question 22 Curated by Curated by
  • 15.
    range() – Thisreturns a list of numbers created using the range() function. xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called lazy evaluation. How do you floor a number in Python? What is the difference between xrange and range functions? The Python math module includes a method that can be used to calculate the floor of a number. floor() method in Python returns the floor of x i.e., the largest integer not greater than x. ceil(x) in Python returns a ceiling value of x i.e., the smallest integer greater than or equal to x. range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python 3, there is no xrange, but the range function behaves like xrange in Python 2. Question Question 23 24 Curated by Curated by
  • 16.
    What is DictionaryComprehension? Give an Example Is Tuple Comprehension? If yes, how, and if not why? my_dict = {i:1+7 for i in range(1, 10)} Dictionary Comprehension is a syntax construction to ease the creation of a dictionary based on the existing iterable. Tuple comprehension is not possible in Python because it will end up in a generator, not a tuple comprehension. Question Question 25 26 (i for i in (1, 2, 3)) Curated by Curated by
  • 17.
    Lists are Mutabledata types. LISTS TUPLES Tuples are Immutable data types. Lists consume more memory Tuple consumes less memory as compared to the list The implication of iterations is comparatively Faster A Tuple data type is appropriate for accessing the elements The implication of iterations is Time-consuming The list is better for performing operations, such as insertion and deletion. Differentiate between List and Tuple? What is the difference between a shallow copy and a deep copy? Let’s analyze the differences between List and Tuple: Shallow copy is used when a new instance type gets created and it keeps values that are copied whereas deep copy stores values that are already copied. A shallow copy has faster program execution whereas a deep copy makes it slow. Question Question 27 28 Curated by Curated by
  • 18.
    Which sorting techniqueis used by sort() and sorted() functions of python? What are Decorators? Python uses the Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data. Decorators in simple terms is the specific change that we make in Python syntax to alter functions easily. Question Question 29 30 Curated by Curated by our Success Story GunjanBhadani From To our Success Story GunjanBhadani From To
  • 19.
    In Python, wecan use the debugger pdb for debugging the code. To start debugging we have to enter the following lines on the top of a Python script. import pdb pdb.set_trace() After adding these lines, our code runs in debug mode. Now we can usecommands like breakpoint, step through, step into etc for debugging. By using this command we can debug a Python program: $ python -m pdb python-script.py How do you debug a Python program? Question 31 What are Iterators in Python? In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are collections of items, and they can be a list, tuples, or a dictionary. Python iterator implements __itr__ and the next() method to iterate the stored elements. We generally use loops to iterate over the collections (list, tuple) in Python. Question 32 Curated by Curated by
  • 20.
    In Python, thegenerator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implement __itr__ and next() method and reduces other overheads as well. If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resumes from the same when required. What are Generators in Python? Question 33 Does Python support multiple Inheritance? Python does support multiple inheritances, unlike Java. Multiple inheritances mean that a class can be derived from more than one parent class. Question 34 Curated by Curated by
  • 21.
    Polymorphism means theability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism. Encapsulation means binding the code and the data together. A Python class is an example of encapsulation. What is Polymorphism and encapsulation in Python? Question 35 What is garbage collection in Python? A garbage collection in Python manages the memory automatically and heap allocation. In simpler terms, the process of automatic deletion of unwanted or unused objects to free the memory is called garbage collection in Python. Question 36 Curated by Curated by
  • 22.
    How do youdo data abstraction in Python? How is memory management done in Python? Data Abstraction is providing only the required details and hides the implementation from the world. It can be achieved in Python by using interfaces and abstract classes. Python uses its private heap space to manage the memory. Basically, all the objects and data structures are stored in the private heap space. Even the programmer can not access this private space as the interpreter takes care of this space. Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space. Question Question 37 38 Curated by Curated by
  • 23.
    os.remove() os.unlink() Lst[ Initial :End : IndexJump ] How to delete a file using Python? What is slicing in Python? We can delete a file using Python by following approaches: Python Slicing is a string operation for extracting a part of the string, or some part of a list. With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. Question Question 39 40 Curated by Curated by
  • 24.
    What is anamespace in Python? What is PIP? What is a zip function? A namespace is a naming system used to make sure that names are unique to avoid naming conflicts. PIP is an acronym for Python Installer Package which provides a seamless interface to install various Python modules. It is a command-line tool that can search for packages over the internet and install them without any user interaction. Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples. Question Question Question 41 42 43 Curated by Curated by
  • 25.
    What are Picklingand Unpickling? How can we do Functional programming in Python? The Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling. Python has a module named pickle. This module has the implementation of a powerful algorithm for serialization and deserialization of Python object structure. In Functional Programming, we decompose a program into functions. These functions take input and after processing give an output. The function does not maintain any state. Python provides built-in functions that can be used for Functional programming. Question Question 44 45 Curated by Curated by
  • 26.
    Map() reduce() filter() Some of thesefunctions are: Event iterators and generators can be used for Functional programming in Python. What is __init__() in Python? Write a code to display the current time? Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables. Question Question 46 47 current_time= time.localtime() print (“Current time is”, current_time) Curated by Curated by
  • 27.
    Public Access Modifier:The members of a class that are declared public are easily accessible from any part of the program. All data members and member functions of a class are public by default. Protected Access Modifier: The members of a class that are declared public are easily accessible from any part of the program. All data members and member functions of a class are public by default. Private Access Modifier: The members of a class that are declared private are accessible within the class only, the private access modifier is the most secure access modifier. Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class. What are Access Specifiers in Python? Python uses the ‘_’ symbol to determine the access control for a specific data member or a member function of a class. A Class in Python has three types of Python access modifiers: Question 48 Curated by Curated by
  • 28.
    What are unittests in Python? Python Global Interpreter Lock (GIL)? The Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling. Python has a module named pickle. This module has the implementation of a powerful algorithm for serialization and deserialization of Python object structure. Python Global Interpreter Lock (GIL) is a type of process lock that is used by Python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. The performance of the single-threaded process and the multi-threaded process will be the same in Python and this is because of GIL in Python. We can not achieve multithreading in Python because we have a global interpreter lock that restricts the threads and works as a single thread. Question Question 49 50 Curated by Curated by
  • 29.
    Function Annotation isa feature that allows you to add metadata to function parameters and return values. This way you can specify the input type of the function parameters and the return type of the value the function returns. Function annotations are arbitrary Python expressions that are associated with various parts of functions. These expressions are evaluated at compile time and have no life in Python’s runtime environment. Python does not attach any meaning to these annotations. They take life when interpreted by third-party libraries, for example, mypy. What are Function Annotations in Python? Question 51 Curated by Curated by Courses Offered by Tutort Academy Data Analytics and
 Business Analytics Program Data Science and
 Artificial Intelligence Program Learn more Learn more
  • 30.
  • 31.
    match term: case pattern-1: action-1 casepattern-2: action-2 case pattern-3: action-3 case _: action-default What is Python Switch Statement Python has implemented a switch case feature called “structural pattern matching”. You can implement this feature with the match and case keywords. Note that the underscore symbol is what you use to define a default case for the switch statement in Python. Note: Before Python 3.10 Python didn't support match Statements. Question 53 Curated by Curated by
  • 32.
    >>> thelist=['a','b'] >>> fori,j in enumerate(thelist): ... print i,j ... 0 a 1 b High readability reduces cost of program maintenance open source support third party packages modularity code reverse. What is the improvement in the enumerate() function of Python? In Python, enumerate() function is an improvement over regular iteration. The enumerate() function returns an iterator that gives (0, item[0]). Question 54 uses and benefits of python Question 55 Curated by Curated by
  • 33.
    Static- data typesare checked before execution. dynamic- data type are checked during execution Tutort Benefits 24x7 Live 1:1 Video based doubt support 1:1 Mentorship from Industry experts Resume building & Mock Interview Preparations Special support for foreign students Dynamically typed language? Typing refers to type checking in programming language storing type language such as a Python 1 + 2 will result in type error since this language don't allow for “type coercion” (implicit conversion of data types) on the other hand a weekly type data weakly typed language such as JS will simply output 12 to a result Two stage of a Typing- checking Question 56 Curated by Curated by
  • 34.
    Class address: def __init__(mine,street,number): Mine.street= street Mine.number = number Def myfunc(abc): print(“my address is “ abc,street) P1 = address(“Albert street”,20) p1.myfunc() What is self in code? self represents the instances of class . These handy keywords allow you to access the variables, attributes and methods of a defined class in Python. Self parameter doesn't have to be you named ‘self’ as you can call it by any other home however the self parameter must always be the first parameter of any class function regardless of a name choose chosen so instead of selfie you call you ‘mine’ or ‘ours’ or anything else Question 57 Curated by Curated by
  • 35.
    What is comprehensionin Python? It provide us with the short and a concise way to construct a new sequences [such as a list set dictionary etc] using sequences which have been already defined Python supports four types of a comprehension Question 58 A. List comprehension- it provide an elegant way to create a new list.The following is the basic structure of a list comprehension output list= [ output_execution for var in input_list if (var satisfy this condition)] Note - list comprehension may or may not contain and if condition list comprehension can contain multiple for nested list conference comprehension list comprehension set comprehension dictionary comprehension generator comprehension Curated by Curated by
  • 36.
    #without using listcomprehension Input_list = [1, 2, 3, 4, 4, 5, 6, 7,7] Output_list=[ ] #look for constructing output for var in input_list: If var % 2 ==0: Output_list.append(var) print(“Output list using for loop, output_list) # Constructing output list using for loop output list is equal to[] for war in range(1, 10): output_list.append(var ** 2): print(“Output list using for loops: “,output_list ) 1. example one suppose we want to create an output list which contains only the even number which are present in the input list let's see how to do this using for loops and list comprehension and decide which method suits better Output = output list using for loop : [2 4 4 6] output = output list using for loop : [1 4 9 16 25 36 49 64 81] 2. Suppose we want to create an output list which contains squares of all the numbers from 1 to 9 let's see how to do this using for loops and list comprehension Curated by Curated by
  • 37.
    B. Dictionary comprehension Extendingthe idea of list comprehensions, we can also create a dictionary using dictionary comprehensions. The basic structure of a dictionary comprehension looks like below. Example #1: Suppose we want to create an output dictionary which contains only the odd numbers that are present in the input list as keys and their cubes as values. Let’s see how to do this using for loops and dictionary comprehension. output = output list using for comprehension: [1 4 9 16 25 36 49 64 81] #using list comprehension list_using_comprehension=[ var * 2 for var in range(1,10)] print(“Output list using for loops: “, list_using_comprehension ) output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)} Curated by Curated by
  • 38.
    Example #2: Giventwo lists containing the names of states and their corresponding capitals, construct a dictionary which maps the states with their respective capitals. Let’s see how to do this using for loops and dictionary comprehension. Output: Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343} Output: Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7: 343} input_list = [1, 2, 3, 4, 5, 6, 7] output_dict = {} # Using loop for constructing output dictionary for var in input_list: if var % 2 != 0: output_dict[var] = var**3 print("Output Dictionary using for loop:", output_dict ) # Using Dictionary comprehensions # for constructing output dictionary input_list = [1,2,3,4,5,6,7] dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0} print("Output Dictionary using dictionary comprehensions:", dict_using_comp) Curated by Curated by
  • 39.
    Output Output Dictionaryusing for loop: {'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur'} Output: Output Dictionary using dictionary comprehensions: {'Rajasthan': 'Jaipur', 'Maharashtra': 'Mumbai', 'Gujarat': 'Gandhinagar'} state = ['Gujarat', 'Maharashtra', 'Rajasthan'] capital = ['Gandhinagar', 'Mumbai', 'Jaipur'] output_dict = {} # Using loop for constructing output dictionary for (key, value) in zip(state, capital): output_dict[key] = value print("Output Dictionary using for loop:", output_dict) # Using Dictionary comprehensions # for constructing output dictionary state = ['Gujarat', 'Maharashtra', 'Rajasthan'] capital = ['Gandhinagar', 'Mumbai', 'Jaipur'] dict_using_comp = {key:value for (key, value) in zip(state, capital)} print("Output Dictionary using dictionary comprehensions:", dict_using_comp) Curated by Curated by
  • 40.
    C. set comprehension: Setcomprehensions are pretty similar to list comprehensions. The only difference between them is that set comprehensions use curly brackets { }. Let’s look at the following example to understand set comprehensions. Example #1 : Suppose we want to create an output set which contains only the even numbers that are present in the input list. Note that set will discard all the duplicate values. Let’s see how we can do this using for loops and set comprehension. Output: Output Set using for loop: {2, 4, 6} input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7] output_set = set() # Using loop for constructing output set for var in input_list: if var % 2 == 0: output_set.add(var) print("Output Set using for loop:", output_set) Curated by Curated by
  • 41.
    D. generator comprehension GeneratorComprehensions are very similar to list comprehensions. One difference between them is that generator comprehensions use circular brackets whereas list comprehensions use square brackets. The major difference between them is that generators don’t allocate memory for the whole list. Instead, they generate each value one by one which is why they are memory efficient. Let’s look at the following example to understand generator comprehension: Output: Output Set using set comprehensions: {2, 4, 6} # Using Set comprehensions # for constructing output set input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7] set_using_comp = {var for var in input_list if var % 2 == 0} print("Output Set using set comprehensions:",set_using_comp) Curated by Curated by
  • 42.
    Output: Output valuesusing generator comprehensions: 2 4 4 6 input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] output_gen = (var for var in input_list if var % 2 == 0) print("Output values using generator comprehensions:", end = ' ') for var in output_gen: print(var, end = ' ') Curated by Curated by Courses Offered by Tutort Data Science and
 Artificial Intelligence Program Data Analytics and
 Business Analytics Program Learn more Learn more Full Stack Specialisation
 In Software Development Learn more Data Structures and Algorithms
 with System Design Learn more
  • 43.
    Output:- 6 def plus_one(number): returnnumber + 1 add_one = plus_one add_one(5) What is a decorator? A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate. ● Assigning Functions to Variables To kick us off we create a function that will add one to a number whenever it is called. We'll then assign the function to a variable and use this variable to call the function. Question 59 Curated by Curated by
  • 44.
    ● Defining FunctionsInside other Functions Next, we'll illustrate how you can define a function inside another function in Python. Stay with me, we'll soon find out how all this is relevant in creating and understanding decorators in Python. ● Passing Functions as Arguments to other Functions Functions can also be passed as parameters to other functions. Let's illustrate that below. Output:- 5 Output:- 5 def plus_one(number): def add_one(number): return number + 1 result = add_one(number) return result plus_one(4) def plus_one(number): return number + 1 def function_call(function): number_to_add = 5 return function(number_to_add) function_call(plus_one) Curated by Curated by
  • 45.
  • 46.
    ● Creating Decorators Withthese prerequisites out of the way, let's go ahead and create a simple decorator that will convert a sentence to uppercase. We do this by defining a wrapper inside an enclosed function. As you can see it is very similar to the function inside another function that we created earlier. Our decorator function takes a function as an argument, and we shall, therefore, define a function and pass it to our decorator. We learned earlier that we could assign a function to a variable. We'll use that trick to call our decorator function. Output 'HELLO THERE' def uppercase_decorator(function): def wrapper(): func = function() make_uppercase = func.upper() return make_uppercase return wrapper def say_hi(): return 'hello there' decorate = uppercase_decorator(say_hi) decorate() Curated by Curated by
  • 47.
    Output 'HELLO THERE' @uppercase_decorator defsay_hi(): return 'hello there' say_hi() def split_string(function): def wrapper(): func = function() splitted_string = func.split() return splitted_string return wrapper @split_string @uppercase_decorator def say_hi(): return 'hello there' say_hi() ['HELLO', 'THERE'] We can use multiple decorators to a single function. However, the decorators will be applied in the order that we've called them. Below we'll define another decorator that splits the sentence into a list. We'll then apply the uppercase_decorator and split_string decorator to a single function. However, Python provides a much easier way for us to apply decorators. We simply use the @ symbol before the function we'd like to decorate. Let's show that in practice below. Curated by Curated by
  • 48.
    From the aboveoutput, we notice that the application of decorators is from the bottom up. Had we interchanged the order, we'd have seen an error since lists don't have an upper attribute. The sentence has first been converted to uppercase and then split into a list. ● Accepting Arguments in Decorator Functions Sometimes we might need to define a decorator that accepts arguments. We achieve this by passing the arguments to the wrapper function. The arguments will then be passed to the function that is being decorated at call time. Output My arguments are: Nairobi, Accra Cities I love are Nairobi and Accra def decorator_with_arguments(function): def wrapper_accepting_arguments(arg1, arg2): print("My arguments are: {0}, {1}".format(arg1,arg2)) function(arg1, arg2) return wrapper_accepting_arguments @decorator_with_arguments def cities(city_one, city_two): print("Cities I love are {0} and {1}".format(city_one, city_two)) cities("Nairobi", "Accra") Curated by Curated by
  • 49.
    ●DefiningGeneralPurposeDecorators Todefineageneralpurposedecoratorthatcanbeappliedto anyfunctionweuseargsand**kwargs.argsand**kwargs collectallpositionalandkeywordargumentsandstorethem intheargsandkwargsvariables.argsandkwargsallowusto passasmanyargumentsaswewouldlikeduringfunction calls. Let'sseehowwe'dusethedecoratorusingpositional arguments. def a_decorator_passing_arbitrary_arguments(function _to_decorate): def a_wrapper_accepting_arbitrary_arguments(*args,** kwargs): print('Thepositionalargumentsare',args) print('Thekeywordargumentsare',kwargs) function_to_decorate(*args) returna_wrapper_accepting_arbitrary_arguments @a_decorator_passing_arbitrary_arguments deffunction_with_no_argument(): print("Noargumentshere.") function_with_no_argument() Thepositionalargumentsare() Thekeywordargumentsare{} Noargumentshere. Curatedby Curatedby
  • 50.
    Keyword arguments arepassed using keywords. An illustration of this is shown below. The positional arguments are () The keyword arguments are {'first_name': 'Derrick', 'last_name': 'Mwiti'} This has shown keyword arguments ● Passing Arguments to the Decorator Now let's see how we'd pass arguments to the decorator itself. In order to achieve this, we define a decorator maker that accepts arguments then defines a decorator inside it. We then define a wrapper function inside the decorator as we did earlier. @a_decorator_passing_arbitrary_arguments def function_with_arguments(a, b, c): print(a, b, c) function_with_arguments(1,2,3) The positional arguments are (1, 2, 3) The keyword arguments are {} 1 2 3 @a_decorator_passing_arbitrary_arguments def function_with_keyword_arguments(): print("This has shown keyword arguments") function_with_keyword_arguments(first_name="Der rick", last_name="Mwiti") Curated by Curated by
  • 51.
    def decorator_maker_with_arguments(decorator_arg1, decorator_arg2, decorator_arg3): defdecorator(func): def wrapper(function_arg1, function_arg2, function_arg3) : "This is the wrapper function" print("The wrapper can access all the variablesn" "t- from the decorator maker: {0} {1} {2}n" "t- from the function call: {3} {4} {5}n" "and pass them to the decorated function" .format(decorator_arg1, decorator_arg2,decorator_arg3, function_arg1, function_arg2,function_arg3)) return func(function_arg1, function_arg2,function_arg3) return wrapper return decorator pandas = "Pandas" @decorator_maker_with_arguments(pandas, "Numpy","Scikit-learn") def decorated_function_with_arguments(function_arg1, function_arg2,function_arg3): print("This is the decorated function and it only knows about its arguments: {0}" " {1}" " {2}".format(function_arg1, function_arg2,function_arg3)) decorated_function_with_arguments(pandas, "Science", "Tools") Curated by Curated by
  • 52.
    The wrapper canaccess all the variables - from the decorator maker: Pandas Numpy Scikit-learn - from the function call: Pandas Science Tools and pass them to the decorated function This is the decorated function, and it only knows about its arguments: Pandas Science Tools In order to solve this challenge Python provides a functools.wraps decorator. This decorator copies the lost metadata from the undecorated function to the decorated closure. Let's show how we'd do that. ● Debugging Decorators As we have noticed, decorators wrap functions. The original function name, its docstring, and parameter list are all hidden by the wrapper closure: For example, when we try to access the decorated_function_with_arguments metadata, we'll see the wrapper closure's metadata. This presents a challenge when debugging. decorated_function_with_arguments.__name__ 'wrapper' decorated_function_with_arguments.__doc__ 'This is the wrapper function' Curated by Curated by
  • 53.
    When we checkthe say_hi metadata, we notice that it is now referring to the function's metadata and not the wrapper's metadata. say_hi.__name__ 'say_hi' say_hi.__doc__ 'This will say hi' It is advisable and good practice to always use functools.wraps when defining decorators. It will save you a lot of headache in debugging. import functools def uppercase_decorator(func): @functools.wraps(func) def wrapper(): return func().upper() return wrapper @uppercase_decorator def say_hi(): "This will say hi" return 'hello there' say_hi() 'HELLO THERE' Curated by Curated by
  • 54.
    ● Python DecoratorsSummary Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated. Using decorators in Python also ensures that your code is DRY(Don't Repeat Yourself). Decorators have several use cases such as: Authorization in Python frameworks such as Flask and Django Logging Measuring execution time Synchronization What are Python Modules? Question 60 Files containing Python codes are referred to as Python Modules. This code can either be classes, functions, or variables and saves the programmer time by providing the predefined functionalities when needed. It is a file with “.py” extension containing an executable code. Commonly used built modules are listed below: os sys data time math random JSON Curated by Curated by
  • 55.
    Pandas: Powerful PythonData Analysis Toolkit Seaborn: This is a statistical data visualization library in Python. SciKit: This is a machine learning library in Python. SciPy: This is an open source system for science, mathematics and engineering implemented in Python. What is pep 8? What are Python packages? What are the popular Python libraries used in Data analysis? PEP in Python stands for Python Enhancement Proposal. It is a set of rules that specify how to write and design Python code for maximum readability. A Python package refers to the collection of different sub- packages and modules based on the similarities of the function. Some of the popular libraries of Python used for Data analysis are: Question Question Question 61 62 62 Curated by Curated by
  • 56.
    What is docstringin Python? Python lets users include a description (or quick notes) for their methods using documentation strings or docstrings. Docstrings are different from regular comments in Python as, rather than being completely ignored by the Python Interpreter like in the case of comments, these are defined within triple quotes. Using docstring as a comment. This code add two numbers """ x=7 y=9 z=x+y print(z) Question What is the difference between append() and extend() methods? 65 Question 64 Both append() and extend() methods are methods used to add elements at the end of a list. append(element): Adds the given element at the end of the list that called this append() method extend(another-list): Adds the elements of another list at the end of the list that called this extend() method Curated by Curated by
  • 57.
    What are thecommon built-in data types in Python? Question 67 Immutable data types: Number , String, Tuple Mutable data types: List, Dictionary, Set How is Multithreading achieved in Python? Question 66 Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time. Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core. Python supports the below-mentioned built-in data types: Curated by Curated by
  • 58.
    What is thedifference between split() and slicing in Python? How can you randomize the items of a list in place in Python? Question Question 68 69 Both split() function and slicing work on a String object. By using split() function, we can get the list of words from a String. E.g. 'a b c '.split() returns [‘a’, ‘b’, ‘c’] Slicing is a way of getting substring from a String. It returns another String. E.g. >>> 'a b c'[2:3] returns b This can be easily achieved by using the Shuffle() function from the random library as shown below: Output: [‘Loves’,’He’ ,’To ,’In’, ‘Python’,’Code’] from random import shuffle List = ['He', 'Loves', 'To', 'Code', 'In', 'Python'] shuffle(List) print(List) Curated by Curated by
  • 59.
    To access anelement from ordered sequences, we simply use the index of the element, which is the position number of that particular element. The index usually starts from 0, i.e., the first element has index 0, the second has 1, and so on. Python Indexing When we use the index to access elements from the end of a list, it’s called reverse indexing. In reverse indexing, the indexing of elements starts from the last element with the index number ‘−1’. The second last element has index ‘−2’, and so on. These indexes used in reverse indexing are called negative indexes. Guaranteed Job Referrals Highest CTC 100% Hiring Partners 350+ 2.1CR Why Tutort Academy? What are negative indexes and why are they used? Question 70 Curated by Curated by
  • 60.
    Explain split(), sub(),subn() methods of “re” module in Python? Question 71 These methods belong to the Python RegEx or ‘re’ module and are used to modify strings. split(): This method is used to split a given string into a list. sub(): This method is used to find a substring where a regex pattern matches, and then it replaces the matched substring with a different string. subn(): This method is similar to the sub() method, but it returns the new string, along with the number of replacements. Curated by Curated by
  • 61.
    What is amap function in Python? Question 72 The map() function in Python has two parameters, function and iterable. The map() function takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It returns an object list of results. def calculateSq(n): return n*n numbers = (2, 3, 4, 5) result = map( calculateSq, numbers) print(result) Curated by Curated by
  • 62.
    Python has variousfile processing modes. For opening files, there are three modes: For opening a text file using the above modes, we will have to append ‘t’ with them as follows: read-only mode (r) write-only mode (w) read–write mode (rw) read-only mode (rt) write-only mode (wt) read–write mode (rwt) Explain all file processing modes supported in Python? Question 73 Curated by Curated by
  • 63.
    Similarly, a binaryfile can be opened by appending ‘b’ with them as follows: To append the content in the files, we can use the append mode (a): For text files, the mode would be ‘at’ For binary files, it would be ‘ab’ To remove duplicate elements from the list we use the set() function. Consider the below example: read-only mode (rb) write-only mode (wb) read–write mode (rwb) demo_list=[5,4,4,6,8,12,12,1,5] unique_list = list(set(demo_list)) output:[1,5,6,8,12] How will you remove duplicate elements from a list? Question 74 Curated by Curated by
  • 64.
    How will youread a random line in a file? How can files be deleted in Python? Question Question 75 76 We can read a random line in a file using the random module. For example: You need to import the OS Module and use os.remove() function for deleting a file in python. consider the code below: import os os.remove("file_name.txt") import random def read_random(fname): lines = open(fname).read().splitlines() return random.choice(lines) print(read_random (‘hello.txt’)) Curated by Curated by
  • 65.
    How can yougenerate random numbers in Python? What is slicing in Python? Question Question 77 78 This is achieved with importing the random module,it is the module that is used to generate random numbers. Syntax: Slicing is a process used to select a range of elements from sequence data type like list, string and tuple. Slicing is beneficial and easy to extract out the elements. It requires a : (colon) which separates the start index and end index of the field. All the data sequence types List or tuple allows us to use slicing to get the needed elements. Although we can get elements by specifying an index, we get only a single element whereas using slicing we can get a group or appropriate range of needed elements. Syntax - List_name[start:stop] import random random.random # returns the floating point random number between the range of [0,1]. Curated by Curated by
  • 66.
    Define Constructor inPython? Question 79 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 Curated by Curated by Courses Offered by Tutort Academy Data Analytics and
 Business Analytics Program Data Science and
 Artificial Intelligence Program Learn more Learn more
  • 67.
    How can wecreate a constructor in Python programming? Question 80 The _init_ method in Python stimulates the constructor of the class. Creating a constructor in Python can be explained clearly in the below example. Output: ID: 1 Name: nirvi ID: 106 Name: Tanvi 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(); Curated by Curated by
  • 68.
    Start Your with us Upskilling www.tutort.net Followus on Watch us on Youtube Read more on Quora Explore our courses Data Science and
 Artificial Intelligence Program Data Analytics and
 Business Analytics Program