Python Knowledge 2023 (2)
Python Knowledge 2023 (2)
In Python, we can use the <yield> keyword to convert any Python function into a
Python generator. Yields function similarly to a conventional return keyword.
However, it will always return a generator object. A function can also use the
<yield> keyword multiple times.
Code
1. def creating_gen(index):
2. months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
3. yield months[index]
4. yield months[index+2]
5. next_month = creating_gen(3)
6. print(next(next_month), next(next_month))
Output:
We can transform a list into a tuple using the Python tuple() method. Since a
tuple is immutable, we can't update the list after it has been converted to a tuple.
Code
1. month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
2. converting_list = tuple(month)
3. print(converting_list)
4. print(type(converting_list))
Output:
('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
<class 'tuple'>
NumPy arrays are much more versatile than Python lists. Reading and writing
objects are quicker and more efficient using NumPy arrays.
Code
1. import numpy
2. #method 1
3. array_1 = numpy.array([])
4. print(array_1)
5. #method 2
6. array_2 = numpy.empty(shape=(3,3))
7. print(array_2)
Output:
[]
[[9.03420200e-308 7.54982336e-308 0.00000000e+000]
[0.00000000e+000 0.00000000e+000 0.00000000e+000]
[0.00000000e+000 0.00000000e+000 1.20953760e-311]]
Code
1. import array
2. a = [4, 6, 8, 3, 1, 7]
3. print(a[-3])
4. print(a[-5])
5. print(a[-1])
Output:
3
6
7
8) What is the Python data type SET, and how can I use it?
"set" is a Python data type which is a sort of collection. Since Python 2.4, it's been
a part of the language. A set is a collection of distinct and immutable items that
are not in any particular sequence.
We can create random data in Python utilizing several functions. They are as
follows:
10) How do you print the summation of all the numbers from 1 to 101?
Using this program, we can display the summation of all numbers from 1 to 101:
Code
1. Print( sum(range(1,102)) )
Output:
5151
Code
1. global_var = 0
2. def modify_global_var():
3. global global_var # Setting global_var as a global variable
4. global_var = 10
5. def printing_global_var():
6. print(global_var) # There is no need to declare global variable
7. modify_global_var()
8. printing_global_var() # Prints 10
Output:
10
12) Is it possible to construct a Python program that calculates the mean of
numbers in a list?
Code
Output:
Code
Output:
List Tuple
Lists are editable, which means that we Tuples (which are just lists that we cannot
can change them. alter) are immutable.
Lists are comparatively slower Tuples are more efficient than lists.
Syntax: list1 = [100, 'Itika', 200] Syntax: tup1 = (100, 'Itika', 200)
Decorators are just employed to add certain layout patterns to a method without
affecting the structure of the function. Typically, decorators are identified before
the event they will be improving. We should first define a decorator's function
before using it. The function to which We will implement the decorator's function
is then written, and the decorator function is simply positioned above it. In this
instance, the @ symbol comes preceding the decorator.
20) How is a Python Dictionary different from List comprehensions?
Dictionary & list comprehensions are yet another means of defining dictionaries
and lists in a simple manner.
Code
Output:
[0, 1, 2, 3]
This is example of dictionary
Code
Output:
Numbers- Integers, complex numbers, and floating points are Python's most
prevalent built-in data structures. For example, 1, 8.1, 3+6i.
List- A list is a collection of objects that are arranged in a specific order. A list's
components could be of multiple data kinds. For example, [[10,'itika',7] .4]
Tuple- It's also a set of items in a specific order. Tuples, not like lists, are
immutable, meaning we cannot modify them. For example, (7,'itika',2)
Boolean- True and False is indeed the two possible boolean values.
The Python code we save is contained in the .py files. The .pyc files are created
when the program is integrated into the current program from some other
source. This file contains the bytecode for the Python files that we imported. The
interpreter reduces processing time if we transform the source files having the
format of .py files to .pyc files.
Global Variables: Global variables are those that have been declared outside of a
function. The scope outside of the function is known as global space. Any program
function has access to these variables.
Code
1. # Python program to show how global variables and local variables are different
2. var = 56
3. # Creating a function
4. def addition():
5. var1 = 7
6. c = var + var1
7. print("In local scope: ", var1)
8. print("Adding a global scope and a local scope variable: ", c)
9. addition()
10.print("In global scope: ", var)
Output:
In local scope: 7
Adding a global scope and a local scope variable: 63
In global scope: 56
It will generate an error if you attempt to access the local variable exterior of the
function addition().
24) What is the distinction between Python Arrays and Python Lists?
In Python, arrays and lists both store data similarly. On the other hand, arrays can
only have a single data type element, while lists can contain any data type
component.
Code
Output:
Code
Output:
Itika
10
26) What is a lambda function, and how does it work?
A lambda function is a type of nameless function. This method can take as many
parameters as you want but a single statement.
Code
Output:
A self is a class instance or object. This is explicitly supplied as the initial argument
in Python. However, in Java, in which it is optional, that's not the case. Local
variables make it easy to differentiate between a class's methods and attributes.
In the init method of a class, the self variable corresponds to the freshly
generated objects, whereas it relates to the entity whose method can be called in
the class's other methods.
Break The loop is terminated when a criterion is fulfilled, and control is passed to the
subsequent statement.
Pass You can use this when you need a code block syntactically correct but don't want to
run it. This is a null action in essence. When it is run, nothing takes place.
Continue When a specified criteria is fulfilled, the control is moved to the start of the loop,
allowing some parts of the loop currently in execution to be skipped.
Code
Output:
Original list:
After randomising the list:
The Pickle module takes any Python object and then transforms it into the
representation of a string, which it then dumps into a file using the dump method.
Unpickling is the procedure of recovering authentic Python items from a saved
string representation.
31) What method will you use to turn the string's all characters into lowercase
letters?
Code
Output:
javatpoint
Multi-line comments span many lines. A # must precede all lines that we will
comment on. You could also use a convenient alternative to comment on several
lines. All you have to do is press down the ctrl key, hold it, and click the left mouse
key in every area where you need a # symbol to appear, then write a # once. This
will add a comment to the lines wherever you insert your cursor.
Docstrings stands for documentation strings, which are not just comments. We
enclose the docstrings in triple quotation marks. They are not allocated to any
variable, and, as a result, they can also be used as comments.
Code
34) Explain the split(), sub(), and subn() methods of the Python "re" module.
Python's "re" module provides three ways for modifying strings. They are as
follows:
sub() finds all substrings that match the regex pattern given by us. Then it
replaces that substring with the string provided.
subn() is analogous to sub() in that it gives the new string and the number of
replacements.
We can use the append(), extend(), as well as insert (i,x) methods to add items to
an array.
Code
Output:
array('d', [1.0, 2.0, 3.0, 8.0])
array('d', [1.0, 2.0, 3.0, 8.0, 4.0, 6.0, 9.0])
array('d', [1.0, 2.0, 9.0, 3.0, 8.0, 4.0, 6.0, 9.0])
36) What is the best way to remove values from a Python array?
The pop() or remove() methods can be used to remove array elements. The
distinction between these 2 methods is that the first returns the removed value,
while the second does not.
Code
Output:
4.0
8.0
array('d', [3.0, 8.0, 1.0, 4.0, 2.0])
Code
1. class My_Class:
2. def f(self):
3. print("f()")
1. import monk
2. def monkey_f(self):
3. print ("we are calling monkey_f()")
4.
5. # changing address of func
6. monk.My_Class.func = monkey_f
7. object_ = monk.My_Class()
8.
9. object_.func()
An empty class has no statements contained within its blocks. It can be produced
by using the pass keyword. But you can make an object outside the class. The
PASS statement doesn't do anything in Python.
Code
Output:
Name =
Javatpoint
39) Write sort algorithm.
Output:
Code
Output:
Code
Output:
Code
Output:
Code
1. import numpy
2. array = numpy.array([4, 8, 4, 9, 2])
3. print(array.argsort()[-2:][::-1])
Output:
[3 1]
Code
1. import numpy
2. array = numpy.array([3, 6, 1, 6, 5, 2])
3. percentile = numpy.percentile(array, 45) #Returns 45th percentile
4. print(percentile)
Output:
3.5
Code
1. num = 1101001
2. while(num > 0):
3. l = num % 10
4.
5. if l!=0 and l!=1:
6.
7. print("given number is not binary")
8.
9. break
10.
11.num = num // 10
12.
13.if num == 0:
14.
15.print("given number is binary")
Output:
Code
1. num = 12
2. fact = 1
3. if num < 0:
4.
5. print("Since number is negative factorial cannot be calculated")
6. elif num == 0:
7.
8. print("Factorial of 0 is 1")
9. else:
10.
11.for f in range(1, num + 1):
12.
13.fact = fact * i
14.
15.print("Factorial of",num ,"is",fact)
Output:
Factorial of 12 is 1449225352009601191936
47) Compute the LCM of two given numbers using Python code.
Code
1. num_1 = 24
2. num_2 = 92
3. if num_1 > num_2:
4.
5. greater_num = num_1
6. else:
7.
8. greater_num = num_2
9. while(True):
10.
11.if((greater_num % num_1 == 0) and (greater_num % num_2 == 0)):
12.
13.lcm = greater_num
14.
15.break
16.
17.greater_num += 1
18.print("LCM of", num_1, "and", num_2, "=", greater_num)
Output:
Code
1.
Output:
49)
Code
1. string = 'Javatpoint'
2. result=''
3. for s in string:
4. if s in ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'):
5. s = ''
6. result += s
7. print("Required string without vowels is:", result)
Output:
1. array = [23, 12, 5, 24, 23, 76, 86, 24, 86, 24, 75]
2.
3. print("Reverse order of array is")
4. # Reversing the given array
5. for i in range(len(array)-1, -1, -1):
6.
7. print(array[i], end=' ')
Output:
51) Write a Python program that rotates an array by two positions to the right.
Code
1. listt = [23, 12, 5, 24, 23, 76, 86, 24, 86, 24, 75]
2.
3. for _ in range(0,2):
4. temp = listt[len(listt)-1]
5. for i in range(len(listt)-1,-1,-1):
6. listt[i]=listt[i-1]
7. listt[0]=temp
8. print("After implementing right rotation the list is :")
9. print(listt)
Output:
MCQ’S
1. Who developed Python Programming Language?
a) Wick van Rossum
b) Rasmus Lerdorf
c) Guido van Rossum
d) Niene Stom
4+3%5
a) 7
b) 2
c) 4
d) 1