0% found this document useful (0 votes)
11 views

Python Knowledge 2023 (2)

Python

Uploaded by

Sahil Rahate
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Knowledge 2023 (2)

Python

Uploaded by

Sahil Rahate
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

1) What is the best way to debug a Python program?

This command can be used to debug a Python program.

1. Python -m pdb Python-script.py

2) What does the Python keyword the <yield> imply?

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:

Backward Skip 10sPlay VideoForward Skip 10s


apr jun

3) How can I make a tuple out of a list?

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'>

4) What exactly is a NumPy array?

NumPy arrays are much more versatile than Python lists. Reading and writing
objects are quicker and more efficient using NumPy arrays.

5) In Python, in what ways can you make an empty NumPy array?

In Python, there are two ways to build an empty array:

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]]

6) In Python, what is a negative index?


In Arrays and Lists, Python contains a unique feature called negative indexing.
Python starts indexing from the beginning of an array or list in a positive integer
but reads items from the ending of an array or list in a negative index.

7) Tell the output of the following code?

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.

9) In Python, how do you create random numbers?

We can create random data in Python utilizing several functions. They are as
follows:

o random() - This instruction gives a floating-point value ranging from 0 to 1.


o uniform(X, Y) - This function gives a floating-point value in the X and Y
range.
o randint(X, Y) - This function gives a random integer between X and Y
values.

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

11) In a function, how do you create a global variable?

We can create a global variable by designating it as global within every function


that assigns to it; we can utilize it in other functions:

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?

Calculating the Average of Numbers in Python:

Code

1. n = int(input("Number of Elements to take average of: "))


2. l=[]
3. for i in range(1,n+1):
4. element = int(input("Enter the element: "))
5. l.append(element)
6. average = sum(l)/n
7. print("Average of the elements in list",round(average,2))

Output:

Number of Elements to take average of: 4


Enter the element: 5
Enter the element: 25
Enter the element: 74
Enter the element: 24
Average of the elements in list 32.0

13) Is it possible to build a Python program that reverses a number?

Python program to reverse number:

Code

1. n = int(input("Enter number: "))


2.
3. reverse = 0
4.
5. while(n>0):
6. digit = n%10
7. reverse = reverse*10+digit
8. n=n//10
9. print("The reverse of the number:",reverse)

Output:

Enter number: 35257


The reverse of the number: 75253

14) In Python, what is the distinction between a list and a tuple?

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)

15) Is Python programming language or scripting language?

Although we can use Python to write scripts, it is primarily used as a general-


purpose programming language.

16) Python is an interpreted programming language. Explain.

Any scripting language not in machine code before execution is called an


interpreted language. Python is thus an interpreted language.

17) What is the meaning of pep 8?


PEP (Python Enhancement Proposal) is the acronym for Python Enhancement
Proposal. It's a collection of guidelines for formatting Python code for better
readability.

18) What are the advantages of Python?

The advantages of utilizing Python are as follows:

o Simple to understand and utilize- Python is a powerful language of


programming that is simple to learn, read, and write.
o Interpreted language- Python is an interpreted language, which means it
runs the program line by line & pauses if any line contains an error.
o Dynamically typed- when coding, the programmer does not set data types
to variables. During execution, it is automatically assigned.
o Python is free and open-source to use and share. It's free and open source.
o Extensive library support- Python has a large library of functions that can
perform practically any task. It also allows you to use Python Package
Manager to import additional packages (pip).
o Python applications are portable and can execute on any system without
modification.
o Python's data structures are easy to understand.
o It allows for additional functionality while requiring less coding.

19) In Python, what are decorators?

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.

This is example of list comprehension

Code

1. list_comp = [i for i in range(4)]


2. print(list_comp)

Output:

[0, 1, 2, 3]
This is example of dictionary

Code

1. dictt = {i : i+2 for i in range(10)}


2. print(dictt)

Output:

{0: 2, 1: 3, 2: 4, 3: 5, 4: 6, 5: 7, 6: 8, 7: 9, 8: 10, 9: 11}

21) What is the most prevalent Python built-in data types?

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)

String- A string is a collection of characters. Single or double quotations are used


to declare them. "Itika," "She is learning coding through Javatpoint", and so on.
Set- A set is a group of unrelated elements which are not in any particular
sequence. (2, 3, 4, 5)

Dictionary- A dictionary is a collection of key and value combinations in which


each value may be accessed by its key. The sequence of the items is irrelevant.
For example, {3:'ape', 6:'monkey'}

Boolean- True and False is indeed the two possible boolean values.

22) What's the distinction between .py and.pyc files?

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.

23) How is a local variable different from a global variable?

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.

Local Variables: Any variable declared inside a function is referred to as a local


variable. This variable does not exist in the global domain; it only exists locally.

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

1. # Python program to show the difference between a list and an array


2.
3. # Importing array module
4. import array as arr
5.
6. # Creating an array and a list
7. array_1 = arr.array("i", [3, 6, 2, 7, 9, 5])
8. list_1 = [4, ', 7.20]
9.
10.print(array_1)
11.print(list_1)
12.
13.# Trying to create an array with multiple data types
14.try:
15. array_2 = arr.array("i", [3, 7, 3, ""])
16.except Exception as e:
17. print(e)

Output:

array('i', [3, 6, 2, 7, 9, 5])


[4, ', 7.2]
'str' object cannot be interpreted as an integer

25) What exactly is __init__?

In Python, __init__ is a function or function Object() { [native code] }. When a new


object/instance of a class is created, this function is automatically called to
reserve memory. The __init__ method is available in all classes.

Here's an instance of how to put it to good use.

Code

1. # Python program to explain __init__


2.
3. class Student:
4. def __init__(self, st_name, st_class, st_marks):
5. self.st_name = st_name
6. self.st_class = st_class
7. self.st_marks = 67
8. S1 = Student("Itika", 10, 67)
9. print(S1.st_name)
10.print(S1.st_class)

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

1. # Python program to show how to use lambda functions


2.
3. # Creating a lambda function for addition
4. sum_ = lambda x, y, z : x + y + z
5. print("Sum using lambda function is: ", sum_(4, 6, 8))

Output:

Sum using lambda function is: 18

27) In Python, what is the self?

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.

28) How do these commands work: break, pass and continue?


29) In Python, how would you randomise the elements of a list while it's running?

Consider the following scenario:

Code

1. # Python program to show to randomise elements of a list


2.
3. # Importing the random module
4. import random
5. list_ =
6. print("Original list: ", list_)
7. random.shuffle(list_)
8. print("After randomising the list: ", list_)

Output:

Original list:
After randomising the list:

30) What is the difference between pickling and unpickling?

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?

The lower() function could be used to reduce a string to lowercase.

Code

1. # Python program to show how to convert a string to lower case


2.
3. string = 'JAVATPOINT'
4. print(string.lower())

Output:

javatpoint

32) How do you comment on multiple lines at once in Python?

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.

33) In Python, what are docstrings?

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

1. # Python program to show how to write a docstring


2.
3. """
4. This is a docstring.
5. We write docstrings to explain a program.
6. This program will multiply two numbers and then display the output.
7. """
8. a = 39
9. b = 45
10.c = a * b
11.print("Result of multiplication: ", c)
Output:

Result of multiplication: 1755

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:

split() "splits" a string into a list using a regex pattern.

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.

35) What is the best way to add items to a Python array?

We can use the append(), extend(), as well as insert (i,x) methods to add items to
an array.

Code

1. # Python program to show how to add elements to an array


2.
3. array = arr.array('d', [1 , 2 ,3] )
4. array.append(8) # appending will add an element to the end of the array
5. print(array)
6. array.extend([4,6,9]) # extending will add elements by looping through the given i
terable
7. print(array)
8. array.insert(2, 9) # inserting will add the element at the specified index
9. print(array)

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

1. # Python program to show how to remove elements from a Python array


2.
3. array = arr.array('d', [1, 3, 8, 1, 4, 8, 2, 4])
4. print(array.pop()) # By default it will remove and return the last element of the ar
ray
5. print(array.pop(5)) # It will return and remove the element present at 5th index
6. array.remove(1) # It will remove only the first occurrence of the element - 1 from
the array
7. print(array)

Output:

4.0
8.0
array('d', [3.0, 8.0, 1.0, 4.0, 2.0])

37) In Python, what is monkey patching?

The phrase "monkey patch" in Python exclusively references run-time dynamic


alterations to a module. Monkey patching in python refers to modifying or
updating a piece of code or class or any module at the runtime.

Code

1. class My_Class:
2. def f(self):
3. print("f()")

The monkey-patch testing will then be done as follows:

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()

38) In Python, how do you make an empty class?

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

1. # Python program to show how to make an empty class


2.
3. class my_class:
4. pass
5. object_ = my_class()
6. object_.name = "Javatpoint"
7. print("Name = ", object_.name)

Output:

Name =
Javatpoint
39) Write sort algorithm.

Code a Python script to implement the Bubble

1. # Python program to show how to implement bubble sort


2.
3. def bubble_Sort(array):
4. n = len(array)
5.
6. for i in range(n-1):
7.
8. for j in range(0, n-i-1):
9.
10.if array[j] > array[j + 1] :
11. array[j], array[j + 1] = array[j + 1], array[j]
12.
13.print(array)
14.
15.#example array
16.arr = [23, 14, 64, 13, 64, 23, 86]
17.
18.bubble_Sort(arr)

Output:

[13, 14, 23, 23, 64, 64, 86]

40) In Python, create a program that generates a Fibonacci sequence.

Code

1. #taking number of terms to print the series


2. n=9
3. first = 0 #first value of series
4. second = 1 #second value of series
5. series = [first, second]
6. if n == 0:
7.
8. print("The required fibonacci series is",first)
9. else:
10.
11.for i in range(0,n-2):
12.
13.num = series[i] + series[i+1]
14.
15.series.append(num)
16.print(series)

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21]

41) Make a Python script that checks if a given number is prime.

Code

1. # Python program to check if a number is prime or not


2.
3. # Declaring a variable
4. n = 37
5. if n == 2:
6. print("2 is a prime number")
7.
8. if n != 1:
9. for i in range(2, n):
10. if n % i == 0:
11. print("The given number is a composite number")
12. break
13. if i == n-1:
14. print("The given number is a prime number")
15.else:
16. print("1 is not a prime number")

Output:

The given number is a prime number

42) Create a Python program that checks if a given sequence is a Palindrome.

Below is the program.

Code

1. # Python program to check if the given string is a palindrome


2.
3. # Creating a string
4. sequence = 'abjucujba'
5. # Reversing the string
6. reverse = sequence[::-1]
7.
8. # Checking if the string is a palindrome
9. if reverse == sequence:
10. print("The sequence is a palindrome")
11.else:
12. print("The sequence is not a palindrome")

Output:

The sequence is a palindrome

43) In a NumPy array, how do I extract the indices of N maximum values?

Using the code below.

Code

1. import numpy
2. array = numpy.array([4, 8, 4, 9, 2])
3. print(array.argsort()[-2:][::-1])

Output:

[3 1]

44) Using Python/ NumPy, write code to compute percentiles?

The following method can be used to determine percentiles.

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

45) Write a Python program to determine whether a number is binary.

Following is the code.

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:

given number is binary

46) Using the Iterative technique, calculate factorial in Python.

Following is the code.

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.

Following is the 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:

LCM of 24 and 92 = 552

48) Write a Python program that removes vowels from a string.

Following is the code.

Code

1.
Output:

49)

Following is the code.

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:

Required string without vowels is: Jvtpnt

50) Write a Python code to reverse a given list.

Following is the code.

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:

Reverse order of array is


75 24 86 24 86 76 23 24 5 12 23

51) Write a Python program that rotates an array by two positions to the right.

Following is the code.

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:

After implementing right rotation the list is :


[24, 75, 23, 12, 5, 24, 23, 76, 86, 24, 86]

MCQ’S
1. Who developed Python Programming Language?
a) Wick van Rossum
b) Rasmus Lerdorf
c) Guido van Rossum
d) Niene Stom

2. Which type of Programming does Python support?


a) object-oriented programming
b) structured programming
c) functional programming
d) all of the mentioned
3. Is Python case sensitive when dealing with identifiers?
a) No
b) yes
c) machine dependent
d) none of the mentioned

4. Which of the following is the correct extension of the Python file?


a) .python
b) .pl
c) .py
d) .p

5. Is Python code compiled or interpreted?


a) Python code is both compiled and interpreted
b) Python code is neither compiled nor interpreted
c) Python code is only compiled
d) Python code is only interpreted

6. All keywords in Python are in _________


a) Capitalized
b) lower case
c) UPPER CASE
d) None of the mentioned

7. What will be the value of the following Python expression?

4+3%5
a) 7
b) 2
c) 4
d) 1

8. Which of the following is used to define a block of code in Python language?


a) Indentation
b) Key
c) Brackets
d) All of the mentioned

9. Which keyword is used for function in Python language?


a) Function
b) def
c) Fun
d) Define

10. Which of the following character is used to give single-line comments in


Python?
a) //
b) #
c) !
d) /*

You might also like