Author name: Prasanna

Python Interview Questions on User Defined Functions

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on User Defined Functions

While going through the chapter on standard data types you have learned about several inbuilt defined by functions. These functions already exist in Python libraries. However, programming is all about creating your own functions that can be called at any time. A function is basically a block of code that will execute only when it is called. To define a function we use the keyword def as shown in the following code:

def function_name ( ):
    to do statements

So, let’s define a simple function:

def new_year_greetings( ) :
    print("Wish you a very happy and properous new year")
new_year_greetings( )

The new_year_greetings( ) function is a very simple function that simply displays a new year message when called.

You can also pass a parameter to a function. So, if you want the function new_year_greetings( ) to print a personalized message, we may want to consider passing a name as a parameter to the function.

def new_year_greetings(name):
print("Hi ", name.upper(),"! ! Wish you a very happy and prosperous new year")
name = input("Hello!! May I know your good name please: ")
new_year_greetings(name)

The output for the code given above would be as follows:

Hello!! May I know your good name please: Jazz
Hi JAZZ !! Wish you a very happy and prosperous new year
>>>

Indentation is very important. In order to explain, let’s add another print statement to the code.

def new_year_greetings (name) :
print("Hi ", name.upper(),"! ! Wish you a very !
happy and prosperous new year")
print("Have a great year")
name = input("Hello!! May I know your good name please: ")
new_year_greetings(name)

So, when the function is called, the output will be as follows:

Hello!! May I know your good name please: Jazz
Hi JAZZ !! Wish you a very happy and properous new year
Have a great year

Improper indentation can change the meaning of the function: ;

def new_year_greetings(name):
print("Hi ", name.upper( ),"! ! Wish you a very happy and properous new year")
print("Have a great year")

In the code given above the second print, the statement will be executed even if the function is not called because it is not indented properly and it is no more part of the function. The output will be as follows:

Have a great year

Multiple functions can also be defined and one function can call the other.

def new_year_greetings(name):
print("Hi ", name.upper( ),"!! Wish you a very happy and properous new year")
extended_greetings( )
def extended_greetings( ):
print("Have a great year ahead") name = input ("Hello! !' May I know your good name please: ")
new-_year_greetings (name)

When a new year greeting ( ) a message is printed and then it calls the extended_greetings( ) function which prints another message.

Output

Hello!! May I know your good name please: Jazz
Hi JAZZ !! Wish you a very happy and properous new year
Have a great year ahead

Multiple parameters can also be passed to a function.

def new_year_greetings(name1,name2):
print("Hi ",namel," and ",name2,"!! Wish you a very happy and properous new year")
extended_greetings( )
def extended_greetings( ):
print("Have a great year ahead") new_year_greetings("Jazz","George")

The output will be as follows:

Hi Jazz and George !! Wish you a very happy and properous new year Have a great year ahead

Question 1.
What are the different types of functions in Python?
Answer:
There are two types of functions in Python:

  1. Built-in functions: library functions in Python
  2. User-defined functions: defined by the developer

Question 2.
Why are functions required?
Answer:
Many times in a program a certain set of instructions may be called again and again. Instead of writing the same piece of code where it is required it is better to define a function and place the code in it. This function can be called whenever there is a need. This saves time and effort and the program can be developed easily. Functions help in organizing coding work and testing of code also becomes easy.

Question 3.
What is a function header?
Answer:
The first line of function definition that starts with def and ends with a colon (:) is called a function header.

Question 4.
When does a function execute?
Answer:
A function executes when a call is made to it. It can be called directly from the Python prompt or from another function.

Question 5.
What is a parameter? What is the difference between a parameter and an argument?
Answer:
A parameter is a variable that is defined in a function definition whereas an argument is an actual value that is passed on to the function. The data carried in the argument is passed on to the parameters. An argument can be passed on as a literal or as a name.

def function_name(param):

In the preceding statement, param is a parameter. Now, take a look at the statement given below, it shows how a function is called:

function_name(arg):

arg is the data that we pass on while calling a function. In this statement arg is an argument.
So, a parameter is simply a variable in method definition and an argument is the data passed on the method’s parameter when a function is called.

Question 6.
What is a default parameter?
Answer:
The default parameter is also known as the optional parameter. While defining a function if a parameter has a default value provided to it then it is called a default parameter. If while calling a function the user does not provide any value for this parameter then the function will consider the default value assigned to it in the function definition.

Question 7.
What are the types of function arguments in Python?
Answer:
There are three types of function arguments in Python:
1. Default Arguments: assumes a default value, if no value is provided by the user.

def func(name = "Angel"):
print("Happy Birthday ", name)
func ( )
Happy Birthday Angel

You can see that the default value for the name is “Angel” and since the user has not provided any argument for it, it uses the default value.

2. Keyword Arguments: We can call a function and pass on values irrespective of their positions provided we use the name of the parameter and assign them values while calling the function.

def func(name1, name2):
print("Happy Birthday", name1, " and ",name2,"!!!")

Output:

func(name2 = "Richard",namel = "Marlin")
Happy Birthday Marlin and Richard !!!

3. Variable-length Arguments: If there is uncertainty about how many arguments might be required for processing a function we can make use of variable-length arguments. In the function definition, if a single is placed before the parameter then all positional arguments from this point to the end are taken as a tuple. On the other hand, if “**” is placed before the parameter name then all positional arguments from that point to the end are collected as a dictionary.

def func(*name, **age): print(name)
print(age)
func("Lucy","Aron","Alex", Lucy = "10",Aron ="15",Alex="12")

Output:

('Lucy', 'Aron', 'Alex')
{'Lucy': '10', 'Aron': '15', 'Alex': '12'}

Question 8.
What is a fruitful and non-fruitful function?
Answer:
The fruitful function is a function that returns a value and a non-fruitful function does not return a value. Non-fruitful functions are also known as void functions.

Question 9.
Write a function to find factorial of a number using for loop
Answer:
The code for finding a factorial using for loop will be as follows:
Code

def factorial(number):
j = 1
if number==0|number==1:
print(j)
else:
for i in range (1, number+1):
print (j," * ",i," = ", j * i)
j = j*i
print(j)

Execution

factorial(5)

Output

1 * 1 = 1
1 * 2 = 2
2 * 3 = 6
6 * 4 = 24
24 * 5 = 120
120

Question 10.
Write a function for Fibonacci series using a for loop:
Answer:
Fibonacci series: 0, 1, 1, 2, 3, 5, 8….
We take three variables:
i, j, and k:

  • If i = 0, j =0, k =0
  • If i =1, j =1, k =0
  • If i> 1:

temp =j
j =j+k
k=temp
The calculations are as shown as follows:

IKJ
000
101
20Temp = j = 1

J = j + k = 1+10 = 1

K = temp = 1

31Temp = j = 1

J = j +k = 1 +1 = 2

K = temp = 1

41Temp = j = 2

J = j + k = 2+1 = 3

K = temp = 2

52Temp = j = 3

J = j + k = 3+2 = 5

K = temp = 3

63Temp = j =5

J = j + k = 5+3=8

K = temp = 1

Code

def fibonacci_seq (num) :
i = 0
j = 0
k = 0
for i in range(num):
if i==0:
print(j)

elif i==1:
j = 1
print(j)
else:
temp = j
j = j+k
k = temp
print(j)

Execution

fibonacci_seq (10)

Output

0
1
1
2
3
5
8
13
21
34

Question 11.
How would you write the following code using a while loop?
[Note: You may want to refer to recursion before attempting this question.]

def test_function(i, j) :
if i == 0:
return j;
else:
return test_function(i-1, j+1)
print(test_function(6,7) )

Answer:

def test_function (i,j) :
while i > 0:
i =i- 1
j = j + 1
return j
print(test_function(6, 7) )

Question 12.
Write code for finding the HCF of two given numbers.
Answer:
HCF stands for Highest Common Factor or Greatest Common Divisor for two numbers. This means that it is the largest number within the range of 1 to smaller of the two given numbers that divides the two numbers perfectly giving the remainder as zero.
1. Define a function hcf() that takes two numbers as input.

def hcf(x,y):

2. Find out which of the two numbers is greatest, the other one will be the smallest.

small_num = 0
if x > y:
small_nura = y
else:
small_num = x

Set a for loop for the range 1 to small_num+1. (We take the upper limit as small_num+l because the for loop operates for one number less than the upper limit of the range). In this for loop, divide both the numbers with each number in the range and if any number divides both, perfectly assign that value to have as shown in the following code:

for i in range(1,small_num+1):
if (x % i == 0) and (y % i == 0) :
hcf = i

Suppose, the two numbers are 6 and 24, first both numbers are divisible by 2. So, hcf = 2, then both numbers will be divisible by 3 so, the value of 3 will be assigned to 3. Then the loop will encounter 6, which will again divide both the numbers equally. So, 6 will be assigned to hcf. Since the upper limit of the range has reached, the function will finally have hcf value of 6.
3. Return the value of hcf: return hcf
Code

def hcf (x,y) :
small_num = 0
if x>y:
small_num = y
else:
small_num = x

for i in range (1, small_num+1):
if (x % i ==0) and (y % i ==0):
hcf = i
return hcf

Execution

print (hcf(6,24))

Output

6

Scope of a variable

The scope of a variable can be used to know which program can be used from which section of a code. The scope of a variable can be local or global.
Local variables are defined inside a function and global functions are defined outside a function. Local variables can be accessed only within
the function in which they are defined. A global variable can be accessed throughout the program by all functions.

total = 0 # Global variable
def add(a,b) :
sumtotal = a+b #Local variable
print("inside total = ", total)

Question 13.
What will be the output of the following code?

total = 0
def add(a,b):
global total
total = a+b
print("inside total = ", total)

add(6,7)
print("outside total = ", total)

Answer:
The output will be as follows:

inside total = 13
outside total = 13

Question 14.
What would be the output for the following code?

total = 0
def add(a,b):
total = a+b
print("inside total = ", total)

add(6,7)
print("outside total = ", total)

Answer:

inside total = 13
outside total = 0

Question 15.
Write the code to find HCF using Euclidean Algorithm.
Answer:
The following figure shows two ways to find HCF.
On the left-hand side, you can see the traditional way of finding the HCF.

On the right-hand side is the implementation of the Euclidean Algorithm to find HCF.
Python Interview Questions on User Defined Functions chapter 5 img 1

Code

def hcf(x,y):
small_num = 0
greater_num = 0
temp = 0
if x > y:
small_num = y
greater_num = x
else:
small_num = x
greater_num = y

while small_num > 0:
temp = small_num
small_num = greater_num % small_num
greater_num = temp
return temp

Execution

print("HCF of 6 and 2 4 = ",hcf(6,24))
print("HCF of 400 and 300 = ",hcf(400,300))

Output

HCF of 6 and 24= 6
HCF of 400 and 300 = 100

Question 16.
Write code to find all possible palindromic partitions in a string.
Answer:
The code to find all possible palindromic partitions in a string will involve the following steps:

  1. Create a list of all possible substrings.
  2. Substrings are created by slicing the strings as all possible levels using for loop.
  3. Every substring is then checked to see if it is a palindrome.
  4. The substring is converted to a list of single characters.
  5. In reverse order, the characters from the list are added to a string.
  6. If the resultant string matches the original string then it is a palindrome.

Code

def create_substrings(x):
substrings = [ ]

for i in range(len (x)) :
for j in range(1, len(x)+l):
if x[i:j] != ' ' :
substrings.append(x[i:j])
for i in substrings:
check_palin(i)

def check_palin(x):
palin_str = ' '
palin_list = list(x)
y = len(x)-1
while y>=0:
palin_str = palin_str + palin_list[y]
y = y-1
if(palin_str == x):
print("String ", x," is a palindrome")

Execution

x = ''malayalam"
create_substrings(x)

Output

String m is a palindrome
String malayalam is a palindrome
String a is a palindrome
String ala is a palindrome
String alayala is a palindrome
String 1 is a palindrome
String layal is a palindrome
String a is a palindrome
String aya is a palindrome
String y is a palindrome
String a is a palindrome
String ala is a palindrome
String 1 is a palindrome
String a is a palindrome
String m is a palindrome

Question 17.
What are anonymous functions?
Answer:
Lambda facility in Python can be used for creating a function that has no names. Such functions are also known as anonymous functions. Lambda functions are very small functions that have just one line in the function body, ft requires no return statement.

total = lambda a, b: a + b
total(10,50)
60

Question 18.
What is the use of a return statement?
Answer:
The return statement exits the function and hands back value to the function’s caller. You can see this in the code given below. The function func( ) returns the sum of two numbers. This value assigned to “total” and then the value- of the total is printed.

def func(a,b):
return a+b
total = func(5,9)
print(total)
14

Question 19.
What will be the output of the following function?

def happyBirthday( ):
print("Happy Birthday")
a = happyBirthday() print(a)

Answer:

Happy Birthday
None

Question 20.
What will be the output of the following code?

def outerWishes( ):
global wishes
wishes = "Happy New Year"
def innerWishes():
global wishes
wishes = "Have a great year ahead"
print('wishes =', wishes)
wishes = "Happiness and Prosperity Always"
router wishes( )
print('wishes =', wishes)

Answer:
The output will be as follows:

wishes = Happy New Year

Question 21.
What is the difference between passing immutable and mutable objects as an argument to a function?
Answer:
If immutable arguments like strings, integers, or tuples are passed to a function, the object reference is passed but the value of these parameters cannot be changed. It acts like a pass-by-value call. Mutable objects too are passed by object reference but their values can be changed.

Python Interview Questions on User Defined Functions Read More »

Python Interview Questions on Algorithm Analysis and Big-O

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Algorithm Analysis and Big-O

Algorithm

An algorithm is a procedure or set of instructions that are carried out in order to solve a problem. Coding demands procedural knowledge which is expressed in the form of algorithms. An algorithm provides a recipe or a roadmap or a simple sequence of instructions that are required to accomplish a particular programming task. So, for things as simple as adding two numbers or as complex as designing a banking program, everything requires a systematic approach. It is important to create a roadmap that makes sense before going ahead with the coding part. For simple programs, it is easy to create algorithms by logical thinking. There are also some famous algorithms that can be used for complex problem solving and hence frequently used for coding.

Question 1.
What are the steps involved in writing an algorithm?
Answer:
There are three main steps involved in writing an algorithm:

1. Data Input

  • Formulate the problem and decide what data types will be the input.

2. Data Processing

  • Decide what computation will be carried off to get the desired result.
  • Also identify the decision points, conditions under which various functions will operate.

3. Results Output

  • One should know the expected results so that they can be verified by the actual results.

Question 2.
What are the characteristics of the Algorithm?
Answer:
An algorithm has the following five characteristics:

  1. Precision: It clearly defines one single starting point and one or more well-defined ending points.
  2. Effectiveness: It is composed of effective primitives that are understood by the person or machine using it.
  3. Input/Output Specified: The algorithm must receive input and it must also produce an output.
  4. Finiteness: An algorithm stops after the execution of a finite number of steps.
  5. Uniqueness: In an algorithm, the result of every step is uniquely defined and its value depends only on the input provided and the output generated by the previous steps.

Question 3.
What is the meaning of Problem solving?
Answer:
Problem-solving is a logical process in which a problem is first broken down into smaller parts that can be solved step by step to get the desired solution.

Question 4.
What would you call an algorithm that puts element lists in a certain order?
Answer:
An algorithm that puts elements of a list in a certain order is called a sorting algorithm. It uncovers a structure by sorting the input. Sorting is often required for optimizing the efficiency of other algorithms. The output of a sorting algorithm is in non-decreasing order where no element is smaller than the original element of the input and the output reorders but retains all the elements of the input which is generally in array form.
Some very commonly known sorting algorithms are as follows:

1. Simple sorts:
a. Insertion sort
b. Selection sort

2. Efficient Sorts:
a. Merge sort
b. Heap sort
c. Quick sort
d. Shell sort

3. Bubble sort

4. Distribution sort
a. Counting sort
b. Bucket sort
c. Radix sort

Question 5.
What type of algorithm calls itself with smaller or simpler input values?
Answer:
A recursive algorithm calls itself with smaller input values. It is used if a problem can be solved by using its own smaller versions.

Question 6.
What is the purpose of the divide and conquer algorithm? Where is it used?
Answer:
As the name suggests the divide and conquers algorithm divides the problem into smaller parts. These smaller parts are solved and the solutions obtained are used to solve the original problem. It is used in Binary search, Merge sort, quick sort to name a few.

Question 7.
What is dynamic programming?
Answer:
In a dynamic problem, an optimization problem is broken down into much simpler sub-problems, each sub-problem is solved only once and the result is stored. For example, Fibonacci Sequence (Explained in Chapter on Recursion).

Big-O Notation

Big-0 notation helps you analyze how an algorithm would perform if the data involved in the process increases or in simple words it is a simplified analysis of how efficient an algorithm can be.

Since algorithms are an essential part of software programming it is important for us to have some idea about how long an algorithm would take to run, only then can we compare two algorithms and a good developer would always consider time complexity while planning the coding process.

It helps in identifying how long an algorithm takes to run.

Big-O

(1) Gives us the algorithm complexity in terms of input size n.
(2) It considers only the steps involved in the algorithm.
(3) Big-O analysis can be used to analyze both time and space.

An algorithm’s efficiency can be measured in terms of the best-average or worst case but Big-O notation goes with the worst case scenario.
It is possible to perform a task in different ways which means that there can be different algorithms for the same task having different complexity and scalability.
Now, suppose there are two functions:

Constant Complexity [0(1)]

A task that is constant will never experience variation during runtime, irrespective of the input value. For Example:
>>> x = 5 + 7
>>> x
12
>>>
The statement x = 5+7 does not depend on the input size of data in any way. This is known as 0(l)(big oh of 1).
Example:
Suppose, there are sequence of steps all of constant time as shown in the following code:
>>> a= (4-6) + 9
>>> b = (5 * 8) +8
>>> print (a * b)
336
>>>
Now let’s compute the Big-0 for these steps:
Total time = O(1)+O(1)+O(1)
= 3O(1)
While computing Big – O we ignore constants because once the data size increases, the value of constant does not matter.
Hence the Big-0 would be 0(1).

Linear complexity: [O(n)]

In the case of linear complexity, the time taken depends on the value of the input provided.
Suppose you want to print a table of 5. Have a look at the following code:
>>> for i in range(0,n):
print (“\n 5 x “,i,”=”,5*i)
The number of lines to be printed depends on ‘n’. For n =10, only ten lines will be printed but for n= 1000, the for loop will take more time to execute.
The print statement is O(1).
So, the block of code is n*O(l) which is 0(n).
Consider following lines of code:
>>>j = 0                               ————(1)
>>> for i in range(0,n) :        ————(2)
print(“\n 5 x “,i,”=”,5*i)
(1) is O(1)
(2) block is O(n)
Total time = O(l)+O(n)

We can drop O(1) because it is a lower order term and as the value of n becomes large (1) will not matter and the runtime actually depends on the for a loop.
Hence the Big-0 for the code mentioned above is O(n).

Quadratic Complexity: [O(n2)]

As the name indicates quadratic complexity, the time taken depends on the square of the input value. This can be the case with nested loops. Look at the following code:

>>> for i in range (0,n):
for j in range(0,n):
print(“I am in “, j,” loop of i = “, i,”.”)

In this piece of code, the print statement is executed n2 times.

Logarithmic Complexity

Logarithmic complexity indicates that in the worst case the algorithm will have to perform log(n) steps. To understand this, let’s first understand the concept of the logarithm.

Logarithms are nothing but the inverse of exponentiation.

Now let’s take term 23. Here 2 is the base and 3 is the exponent. We, therefore, say that base 2 logs of 8 (log2 8) = 3. Same way if then base 105 = 100000 then base 10 log of 100000 (log10 of 100000) = 5.

Since the computer works with binary numbers, therefore in programming and Big O we generally work with base 2 logs.

Have a look at the following observation:

1. 20 = 1, log2 1 = 0
2. 21 = 2, log2 2 = 1,
3. 22 = 4, log2 4 = 2,
4. 23 = 8, log2 8 = 3,
5. 24 = 16,log2 16 = 4,
This means that if n =1, the number of steps = 1.
If n = 4, the number of steps will be 2.
If n = 8, then the number of steps will be 3.
So, as data doubles the number of steps increases by one.
The number of steps grows slowly in comparison to the growth in data size.
The best example of logarithmic complexity in software programming is the Binary Search tree. You will learn more about it in the chapter based on Trees.

Question 8.
What is worst-case time complexity of an algorithm?
Answer.
The worst-case time complexity in computer science means worst-case in terms of time consumed while execution of a program. It is the longest-running time that an algorithm can take. The efficiency of algorithms can be compared by looking at the order of growth of the worst-case complexity.

Question 9.
What is the importance of Big-O notation?
Answer:
Big-0 notation describes how fast the runtime of an algorithm will increase with respect to the size of the input. It would give you a fair idea about how your algorithm would scale and also give you an idea about the worst-case complexity of the algorithms that you might be considering for your project. You would be able to compare two algorithms and decide which would be a better option for you.

Question 10.
What is the need for run-time analysis for an algorithm when you can find the exact runtime for a piece of code?
Answer:
The exact runtime is not. considered because the results can vary depending on the hardware of the machine, the speed of the processor, and the other processors that are running in the background. What is more important to understand is that how the performance of the algorithm gets affected with an increase in input data.

Question 11.
The big-O analysis is also known as.
Answer:
Asymptotic analysis

Question 12.
What do you understand by asymptotic notation?
Answer:
It is very important to know how fast a program would run and as mentioned earlier we do not want to consider the exact ran time because different computers have different hardware capabilities and we may not get the correct information in this manner.
In order to resolve this issue, the concept of asymptotic notation was developed. It provides a universal approach for measuring the speed and efficiency of an algorithm. For applications dealing with large inputs we are more interested in behaviour of an algorithm as the input size increases. Big O notation is one of the most important asymptotic notations.

Question 13.
Why is Big O notation expressed as O(n)?
Answer:
Big-0 notation compares the runtime for various types of input sizes. The focus is only on the impact of input size on the runtime which is why we use the n notation. As the value of n increases, our only concern is to see how it affects the runtime. If we had been measuring the runtime directly then the unit of measurement would have been time units like second, micro-second, and so on. However, in this case, ‘n’ represents the size of the input, and ‘O’ stands for ‘Order’. Hence, 0(1) stands for the order of 1, 0(n) stands for the order of n, and 0(n2) stands for the order of the square of the size of the input.
Big-0 notations and names:

  1. Constant – 0(1)
  2. Logarithmic – 0(log(n))
  3. Linear -0(n)
  4. Log Linear – 0(nlog(n))
  5. Quadratic – 0(«2)
  6. Cubic – 0(«3)
  7. Exponential – 0(2″)

Question 14.
Write a code in python that takes a list of alphabets such as [‘a’ , ‘b’ , ‘c’, ‘d’ , ‘e’ , ’f’ , ’g’] and returns a list of combination such as [‘bcdefg’, ‘acdefg’, ‘abdefg’, ‘abcefg’, ‘abcdfg’, ‘abcdeg’, ‘abcdef’]. Find the time complexity for the code.
Answer:
Code

input_value = input("enter the list of alphabets separate by comma : ")
alphabets = input_value.split(' , ')
final = [ ]
str = ' '
for element in range(0,len(alphabets)):
for index, item in alphabets:
if(item != alphabets[element]):
str = str+item
final. append (str)
str=' '

Execution

print (final)

Output

enter the list of alphabets seperate by comma : a,b,c,d,e,f,g
[‘bcdefg’, ‘acdefg’, ‘abdefg’, ‘abcefg’, ‘abcdfg’, ‘abcdeg’, ‘abcdef’]
>>>

Conclusion:

The code has a runtime of O(n<sup>2</sup>).

Question 15.
The following code finds the sum of all elements in a list. What is its time complexity?

def sum(input_list):
total = 0
for i in input_list:
total = total + i
print(total)

Answer:

def sum(input_list):
total = 0                              -----------(1)
for i in input list:                   -----------(2)
total = total + i
         print(total)                  -----------  (3)
time for block (1) = O(1)
time for block (2) = O(n)
time for block (3) = O(1)
Total time = O(1) + O(n) + O(1)
Dropping constants
Total time = O(n)

Question 16.
What are the pros and cons of time complexity?
Answer:
Pros:
It is a good way of getting an idea about the efficiency of the algorithm.
Cons:
It can be difficult to assess complexity for complicated functions.

Question 17.
What is the difference between time and space complexity?
Answer:
Time complexity gives an idea about the number of steps that would be involved in order to solve a problem. The general order of complexity in ascending order is as follows:

O(1) < O(log n) < O(n) < O(n log n) <O(n<sup>2</sup>)

Unlike time, memory can be reused and people are more interested in how fast the calculations can be done. This is one main reason why time complexity is often discussed more than space complexity. However, space complexity is never ignored. Space complexity decides how much memory will be required to run a program completely. Memory is required for:

  1. Instruction space
  2. Knowledge space for constants, variables, structured variables, dynamically altered areas, etc
  3. Execution

Question 18.
What is the difference between auxiliary space and space complexity?
Answer:
Auxiliary space is the extra space that is required while executing an algorithm and it is temporary space.
Space complexity on the other hand is the sum of auxiliary space and input space:

Space complexity = Auxiliary space + Input space

Question 19.
What is the memory usage while executing the algorithm?
Answer:
Memory is used for:

  1. Saving the compiled version of instructions.
  2. In the case of nested functions or one algorithm, calling another algorithm, the variables are pushed to a system stack and made to wait till the internal algorithm has finished executing.
  3. To store data and variables.

Space Complexity

You have learned about time complexity. Now, let’s move on to space complexity. As the name suggests space complexity describes how much memory space would be required if the size of input n increases. Here too we consider the worst-case scenario.

Now have a look at the following code:
>>> X = 23                                                                               (1)
>>> y = 34                                                                               (2)
>>> sum = x + y                                                                      (3)
>>> sum
57
>>>

In this example, we need space to store three variables: x in (1), y in (2), and sum in (3). However, this scenario will not change, and the requirement for 3 variables is constant and hence the space complexity is 0(1).

Now, have a look at the following code:

word = input(“enter a word : “)
word_list = [ ]
for element in word:
print(element)
word_list.append(element)
print(word_list)

The size of the word_list object increase with n. Hence, in this case, the space complexity is 0(n).

If there is a function 1 which has to suppose three variables and this functional calls another function named function2 that has 6 variables then the overall requirement for temporary workspace is 9 units. Even if functional calls function2 ten times the workspace requirement will remain the same.

Question 20.
What would be the space complexity for the following piece of code? Explain.

n = int(input("provide a number : "))
statement = "Happy birthday"
for i in range(0,n):
print(i+1,". ”, statement)

Answer:
The space complexity for the above code will be 0(1) because the space requirement is only for storing value of integer variable n and string statement. Even if the size of n increases the space requirement remains constant. Hence, 0(1).

Question 21.
What is the time and space complexity for the following:

a = b = 0
for i in range(n):
a = a + i
for j in range(m):
b = b + j

Answer:
Timecomplexity
Time for first loop = O(n)
Time for second loop = O(m)
Total time = O(n) + O(m) = O(n + m)
Space complexity
O(1)

Question 22.
Find the time complexity for the following code:

a = 0
for i in range(n):
a = a + i
for j in range(m):
a = a + i + j

Answer:
Time complexity: O(n2)

Question 23.
What will be the time complexity for the following code?

i = j = k =0
for i in range(n/2,n):
for j in range(2,n):
k = k+n/2
j = j*2

Answer:
The time complexity for the first for loop O(n/2).
The time complexity for second for loop: O(logn) because j is doubling itself till it is less than n.
Total time = O(n/2)*O(logn)
= O(nlogn)

Question 24.
What is the time complexity for the following code:

i = a = 0
while i>0:
a = a+i
i = i/2

Answer:
Time complexity will be O(logn).

Big O for Python Data Structures

Python language comprises mutable and immutable objects. Numbers, strings, and tuple come in the latter category whereas lists, sets, and dictionary data types are mutable objects. The reason why lists and dictionaries are called mutable is that they can be easily altered at any time. They are like arrays because the data elements can be inserted or deleted easily by providing an index value and since the values can be easily added or removed from any point, the lists are considered to be dynamic. Hence, lists are known to be dynamic arrays. You can also say that lists are called dynamic array because:

  1. Its size can be dynamically modified at run time.
  2. You need not define the size of the list when you create it.
  3. They allow you to store more than one variable.
  4. Dynamic arrays once filled allocate a bigger chunk of memory, and elements of the original array are copied to this section of the memory as a result it can continue to fill available slots.

The most important operations that are performed on a list are as follows:

  1. Indexing
  2. Assigning value to an index value

Both the methods mentioned above are designed to run at constant time 0(1). The Big-0 for common list operations are given as follows:

  1. index[ ] : O(1)
  2. index assignment: O(1)
  3. append: O(1)
    1. pop( ): O(1)
  4. pop(i): O(n)
  5. insert(i, item): O(n)
  6. delete operator: O(n)
  7. contains(in): O(n)
  8. get slice[x:y]: O(k)
  9. del slice: O(n)
  10. set slice : O(n+k)
  11. reverse: O(n)
  12. concatenate: O(k)
  13. sort: O(nlog n)
  14. multiply O(nk)

Dictionaries

Dictionaries are implementation of hashtables and can be operated with keys and values.

Big-O efficiencies for common dictionary objects are given as follows:

  1. copy : 0(n)
  2. get item : 0(1)
  3. set item: 0(1)
  4. delete item : 0(1)
  5. contains(in): 0(1)
  6. iteration: 0(n)

Python Interview Questions on Algorithm Analysis and Big-O Read More »

Python Interview Questions on File Manipulation

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on File Manipulation

Till now you have learned how to implement logic in Python to write blocks of code that can help you accomplish certain tasks. In this section, we will learn about how to use Python to work with files. You can read data from files and you can also write data to the files. You can not only access the internet but also check your emails and social media accounts using the Python programming language.

Files

A file has a permanent location. It exists somewhere on the computer disk and can be referred to anytime. It is stored on the hard disk in non-volatile memory which means the information in the file remains even if the computer is switched off. In this section, we will learn how to deal with files in Python.

Open a File

If you want to work on an existing file, then you will have to first open the file. In this section, we will learn how to open a file.
In order to open a file, we will make use of the open( ) function which is an inbuilt function. When we use the open( ) function, a file object is returned which can be used to read or modify the file. If the file exists in the same directory where python is installed then you need not give the entire pathname. However, if the location is different then you will have to mention the entire path.

For this example, I have created a file by the name: learning_files.txt in the current directory of python /home/pi.

The content of the file is as follows:

I am great a learning files

See how Good I am at opening Files

Thank you Python

Look at the following piece of code:

>>> f_handle = open ("learning_files . txt")
>>> print (f_handle . read ( ) )

In case the file is not available, the error message will be displayed as follows:

>>> f_handle = open ("llllearning_files . txt")
Traceback (most recent call last):
   File "<pyshell#0>", line 1, in <module>
      f_handle = open ("llllearning_files . txt")
FileNotFoundError: [Errno 2] No such file or
directory: ' llllearning_files.txt'
>>>

Output

I am great a learning files
See how Good I am at opening Files
Thank you Python

Python File Modes

Python has defined file modes that can be implemented when a file is opened. These modes define what can be done with the file once it is opened. If you do not mention the mode then “read” is considered the default mode. The list of various modes is given as follows:

‘r’ is also the default mode, it means that the file has been opened for reading purposes. You have already seen the usage of reading mode. To explain this a file by the name “test.txt” has been created. The content of the file is as follows:

“I am excited about writing on the file using Python for the first time. Hope You feel the same. ”

We will now give the following commands.:

>>> f_handle = open("test.txt" , 'r')
>>> f_handle . read (4)

The output for the above code is :
‘I am’

f_handle.read(4) retrieves the first four characters from the file and displays it.

‘w’ stands for writing. It means that you want to open a file and write in it. In case the file that you have mentioned does not exist then a new file will be created.

>>> f_handle = open("test .txt",'w')
>>> f_handle.write("I am excited about writing on the file using Python for the first time.")
71
>>> f_handle.write("Hope you feel the same.")
22
>>> f_handle.close( )
>>>

So, if you open the file now this is how the contents would look like:

The original content of the file before passing the write instructions was:
“I am excited about writing on the file using Python for the first time. Hope you feel the same.”
If you open the file after passing “write” instructions now the contents of the file will be as follows:
“Hi I have opened this file again and I feel great again. ”

As you can see that the previous lines (/ am excited about writing on the file using Python for the first time. Hope you feel the same.) have been erased from the file.

Now, we close the file and try to write something again in it.

>>> f_handle = open (test. txt", ' w' )
>>> f_handle.write ("\n Hi I have opened this file again and I feel great again.")
58
>>> f_handle.close ( )
>>>

‘x’ stands for exclusive creation. An error will be displayed if the file already exists. Let’s see what happens when we try to use ‘x’ mode with an already existing test.txt file.

>>> f_handle = open("F:/test.txt"x')
Traceback (most recent call last):
    File "<pyshell#l>", line 1, in <module>
f_handle = open("F:/test.txt"x')
FileExistsError: [Errno 17] File exists: 'F:/test.txt'

‘a’ is used to append an existing file. If a file does not exist then a new file will be created.

So, now we try to add new text to an already existing file.

The contest of test.txt file is as follows:

“I am excited about writing on the file using Python for the first time.
Hope You feel the same. ”

We will try to add the following line to it:

“Hi I have opened this file again and I feel great again. ”

In order to append, we follow the following steps:

>>> f_handle = open("test.txt",'a')
>>> f_handle.write("Hi I have opened this file again and I feel great again.")
56
>>> f_handle.close()
>>>

Output

I am excited about writing on the file using Python for the first time.
Hope You feel the same.


Hi, I have opened this file again and I feel great again.

‘t’ is used to open a file in text mode and ‘b’ is used to open the file in binary mode.

In the above examples, you must have noticed f_handle.close( ) command. It is important to use the close( ) command after you have stopped working with a file in order to free up operating system resources. If you leave the file open, you may encounter problems.

A better way of dealing with files is to keep the code related to file reading in a try block as shown in the following code:

>>> try:
       f_handle = open ("llllearning_files . txt")
       content = f_handle.read()
       f_handle.close()
except for IOError:
       print (''Could not find the file. Please check again")
       exit( )

Output

Could not find the file. Please check again

In the above piece of code, the file name given does not exist in the given location. Hence, the remaining code of the try block is ignored and the code written in the except block is applied. In the except block, we have provided a simpler and user-friendly message which is easier for the user to understand. Without the try expect to block the following message will be displayed:

Traceback (most recent call last):
   File "<pyshell#10>", line 1, in <module>
      f_handle = open ("llllearning_files .txt")
FileNotFoundError: [Errno 2] No such file or
directory: 'llllearning_files . txt'

Which can be difficult to decipher.

File-system-type commands:

Now we will have a look at some very common file-system-type operations such as move, copy, and so on.
We now try to copy the contents of this file to another file. For this we require to import shutil as shown in the following code:

>>> import shutil
>>> shutil. copy("F:/test.txt","F:/testl.txt")
'F:/testl.txt'

Output

Content of testl.txt file:

You can move the file or change the name of the file using the move command as shown in the following code:

>>> import shutil
>>> shutil.move("test.txt","test2.txt")
'test2.txt'
>>>

The above set of instructions changes the name of the file test.txt to test2. txt.

Another important package available with Python is glob.

The glob package allows you to create a list of a particular type of files by using the star * operator.

>>> import glob
>>> glob.glob("*.txt")
['important.txt', 'learning_files.txt', ' test1. txt', 'test2.txt']
>>>

Question 1.
How is a file opened for reading? Provide an example.
Answer:
Using the open function, and the ‘r’ mode.
myFile = openCpathToFile’,’r’)

Question 2.
What is the appropriate method to call when a file is no longer being used?
Answer:
file.close( )

Question 3.
What are the modes that a file can be opened in? Answer:

  • ‘r’ – reading,
  • ‘w’ – writing,
  • ‘a’ – append,
  • ‘r+’ reading and writing, contents intact,
  • ‘w+’ reading and writing, contents deleted,
  • ‘a+’ same as ‘r+’

Question 4.
What does the ‘b’ modifier do when appended to a file mode?
Answer:
It changes the handling of the file from text to binary mode.

Question 5.
What does the ‘U’ modifier do when appended to a file mode?
Answer:
It applies the universal new-line translator to the file when it is opened.

Question 6.
How is the buffer size specified in the file opening?
Answer:
It is an optional parameter to the open function. A 0 indicates the file is unbuffered, 1 indicates that line by line buffering. Any other positive number is the actual buffer size to be allocated.

Question 7.
How is an entire file read into a buffer and returned as a string? When is it a bad practice to do so?
Answer:
With the .read( ) method. When the file may be large, because the buffer may consume excessive memory.

Question 8.
How is a file read using a limited buffer size?
Answer:
By specifying how many bytes to read in the read method. file.read(20) would read the next 20 bytes from the file.

Question 9.
How can a single line be read from a text file? Provide an illustration.
Answer:
Using the linecache module.
import linecache
myFile = “’file.txt”
print linecache.getline(myFile, 1) # prints the first line
print linecache.getline(myFile,40) # prints the 40th line, etc.

Question 10.
What are two ways to write a line of text to a file?
Answer:
Using the .write method on an open file, or >>> redirection operator to use the print statement.

Question 11.
With a list of strings, how can they all be written out to a file in a single statement?
Answer:
Using the .writelines( ) method. Example:
myFile.writelinesdistName)

Question 12.
Illustrate how to determine the number of lines in a text file, using the readlines method. When would it be inappropriate to use this technique?
Answer:
myLineCount = len(open(myFilePath, Y).readlines())
It would be inappropriate to use if the file might be large, because the readlines method will generate a list of strings that includes the entire file’s contents. It would consume too much memory.

Question 13.
What module and method is used to traverse the file system directory tree?
Answer:
The os module. Specifically os.walk.

Question 14.
How are files deleted?
Answer:
Using the os.remove method. os.remove(‘myFile’)

Question 15.
How are files renamed?
Answer:
Using the os.rename method. os.renameColdFileName’, ‘newFileName’)

Question 16.
How are entire non-empty directory trees removed?
Answer:
Each directory must be walked using the os.walk method, then the files within must be deleted. Then and only then can the directory be removed using the os.rmdir method.

Question 17.
How is a tarfile created?
Answer:
Using the tarfile module.
import tarfile
my Tar = tarfile.open(“my Tarfile”, ‘w’)

Question 18.
How are files added to a tarfile or zipfile?
Answer:
Using the .add method to an open tar or zip file.

Question 19.
How are files extracted from a tar or zip file?
Answer:
Using the .extract method on an open tar or zip file, and specifying the file name and the extraction path.

Question 20.
Illustrate extracting all of the .txt files from a zip file.
Answer:
import os
import zipfile
myZip = zipfile.open(“myZip.zip “, Y)
for myFile in myZip.getnames( ):
if myFile.endswith(“txt”):
myZip.extract(myFile, “-/temp/”)
myZip.close( )

Python Interview Questions on File Manipulation Read More »

Python Interview Questions on Decision Making and Loops

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Decision Making and Loops

Control Statements

Control statements are used to control the flow of program execution. They help in deciding the next steps under specific conditions also allow repetitions of the program a certain number of times.
Two types of control statements are as follows:

1. Conditional branching

  • If
    Syntax:
    if (condition): to do statement
    If the condition evaluates to be true only then if code under if block will be executed.
  • if. . .else Syntax:
    if (condition): to do statement else:
    to do statement
  • Nested if statements Syntax:
    if (condition1):
    to dd statement elif(condition2):
    else do this
    elif(condition3):
    else do this

2. Loops

  • while: repeat a block of statements as long as a given condition is true
    Syntax:
    while(condition): ;
    to do statement
  • for: repeat a block of statements for a certain number of times
    , Syntax: ‘
    for < iterating_variable > in sequence:
    Repeat these steps
  • nested loops

Question 1.
What would be the output for the following piece of code?

animals = [ 'cat', 'dog'] .
for pet in animals: .
pet.upper( ) 
print(animals)

Answer:
The output will be [‘cat’, ‘dog’]. The value returned by a pet. upper( ) is not assigned to anything hence it does not update the value in any way.

Question 2.
What would be the output of the following code?

for i in range(len(animals)):
animals[i] = animals[i].upper( ) 
print(animals)

Answer:

[‘CAT’, ‘DOG’]

Question 3.
What would be the output of the following code?

numbers = [1,2,3,4] 
for i in numbers:
numbers.append(i + 1) 
print(numbers)

Answer:
This piece of code will not generate any output as the ‘for’ loop will never stop executing. In every iteration, one element is added to the end of the list and the list keeps growing in size.

Question 4.
What will be the output for the following code?

i = 6
while True:
if i%4 == 0:
break
print(i)
i -= 2

Answer:
6

Question 5.
Write a code to print the following pattern:
*
**
***
****
Answer:

for i in range(1,5):
print("*"*i)

Or

count = 1 
while count < 5:
print(*count) 
count = count + 1

Question 6.
Write code to produce the following pattern:
1
22
333
4444
Answer:
The code will be as follows:

count = 1 
while count < 5:
print(str(count)*count) 
count = count + 1

Question 7.
Write a code to generate the following pattern:
1
12
123
1234
Answer:
The code will be as follows:

count = 1 
string1 =' ' 
while count < 5:
for i in range(1, count+1):
string1 = string1+str(i)
count = count + 1 
print(string1) 
string1 =' '

Question 8.
Write code to spell a word entered by the user.
Answer:
The code will be as follows:

word = input ("Please enter a word : ") 
for i in word: 
print (i)

Output
Please enter a word: Aeroplane
A
e
r
0
P
l
a
n
e

Question 9.
Write code to reverse a string.
Answer:
The code:

string1 = "AeRoPlAnE" 
temp = list (string1) 
count = len(temp)-1 
reverse_str=' ' 
while count>=0:
reverse_str = reverse_str + temp[count] 
count = count-1 
print(reverse_str)

Output

EnAlPoReA

Statements to control a loop
The following three statements can be used to control a loop:

  1. break: breaks the execution of the loop and jumps to the next statement after the loop
  2. continue: takes the control back to the top of the loop without executing the remaining statements
  3. pass: does nothing

Question 10.
What will be the output for the following code?

a = 0
for i in range(5): 
a = a+1 
continue 
print(a)

Answer:
5

Question 11.
What would be the output for the following code?
Answer:
The code:

for item in ('a','b','c','d'): 
print (item) 
if item == 'c' : 
break 
continue
print ("challenge to reach here")

Question 12.
How would you use a “if ” statement to check whether an integer is even ?
Answer:
Code

x = int(input("enter number : ")) 
if x%2 == 0:
print("You have entered an even number")

Output

enter number: 6
You have entered an even number
>>>

Question 13.
How would you use an  “if ” statement to check whether an integer is odd?
Answer:
Code

x = int(input("enter number : ")) 
if x%2 != 0:
print("You have entered an odd number")

Output
enter number: 11
You have entered an odd number

Question 14.
Use an if-else statement to check if a given number is even if yes then display that a message stating that the given number is even else print that the given number is odd.
Answer:
Please have a look at the following code:
Code

x = int(input("enter number : ")) if x%2 == 0:
print("You have entered an even number") else:
print("You have entered an odd number")

Output

enter number: 11
You have entered an odd number
>>>
enter number: 4
You have entered an even number
>>>

Question 15.
What is a ternary operator?
Answer:
The ternary operator is a conditional expression used to compress the if.. .else block in one single line.

[to do if true] if [Expression] else [to do if false]

Code

X = 27
print("You have entered an even number") if x%2
== 0 else print("You have entered an odd number")

Output

You have entered an odd number

Question 16.
What would be the output of the following code? Why?
i = j = 10 if i > j:
print(“i is greater than j”) elif i<= j:
print(“i is smaller than j”) else:
print(“both i and j are equal”)
Answer:
The output of the above code will be:
i is smaller than j
i is equal to j.
So, the second condition elif i>j evaluates to true and so, the message printed in this block is displayed.

Question 17.
How can the following piece of code be expressed in one single line?
i = j = 10 if i > j :
print(“i is greater than j”)
elif i< j:
print(“i is smaller than j”)
else:
print(“both i and j are equal”)
Answer:
print (“i is greater than j” if i > j else “i is smaller than j” if i < j else “both i and j are equal”)

Question 18.
What will be the output for the following code?
i = 2 j = 16
minimum_val = i < j and i or j minimum_val
Answer:
2

Question 19.
What is the meaning of conditional branching?
Answer:
Deciding whether certain sets of instructions must be executed or not based on the value of an expression is called conditional branching.

Question 20.
What would be the output for the following code?
a = 0
b = 9
i = [True,False] [a > b]
print(i)
Answer:
The answer would be “True”. This is another ternary syntax: [value_if_false, value_if_true][testcondition]
In the above code a < b, therefore the test condition is false. Hence, ‘i’ will be assigned the value of value_if_false which in this case is set to “True”.

Question 21.
What is the difference between the continue and pass statement?
Answer:
pass does nothing whereas continue starts the next iteration of the loop.

Python Looping

Question 22.
What are the two major loop statements?
Answer:
for and while

Question 23.
Under what circumstances would you use a while statement rather than for?
Answer:
The while statement is used for simple repetitive looping and the for statement is used when one wishes to iterate through a list of items, such as database records, characters in a string, etc.

Question 24.
What happens if you put an else statement after a block?
Answer:
The code in the else block is executed after the for loop completes, unless a break is encountered in the for loop execution, in which case the else block is not executed.

Question 25.
Explain the use of break and continue in Python looping.
Answer:
The break statement stops the execution of the current loop, and transfers control to the next block. The continue statement ends the current block’s execution and jumps to the next iteration of the loop.

Question 26.
When would you use a continue statement in a for loop?
Answer:
When processing a particular item was complete; to move on to the next, without executing further processing in the block.
The continued statement says, “I’m done processing this item, move on to the next item.”

Question 27.
When would you use a break statement in a for loop?
Answer:
When the loop has served its purpose. As an example, after finding the item in a list searched for, there is no need to keep looping. The break statement says, “I’m done in this loop; move on to the next block of code.”

Question 28.
What is the structure of a for loop?
Answer:
for <item> in <sequence>:… The ellipsis represents a code block to be executed, once for each item in the sequence. Within the block, the item is available as the current item from the entire list.

Question 29.
What is the structure of a while loop?
Answer:
while <condition>:… The ellipsis represents a code block to be executed until the condition becomes false. The condition is an expression that is considered true unless it evaluates to 0, null or false.

Question 30.
Use a for loop and illustrate how you would define and print the characters in a string out, one per line.
Answer:
my String = “I Love Python”
for my Char in my String:
print myChar

Question 31.
even the string “I LoveQPython” uses a for loop and illustrates printing each character up to, but not including the Q.
Answer:
my String = “I Love Python”
for my car in my String:
if my car = ‘Q’:
break
print myChar

Question 32.
Given the string “I Love Python” print out each character except for the spaces, using a for a loop.
Answer:
my String = “I Love Python”
for myChar in my String:
if myChar — ‘ ‘ ,
continue print myChar

Question 33.
Illustrate how to execute a loop ten times.
Answer:
i = 1
while i < 10:
i+=1

Question 34.
When using a while loop, a condition was encountered that made staying in the loop pointless, what statement is used to transfer control?
Answer:
The break statement is used to terminate the processing of the loop and move on to the next block of code.

Question 35.
How is execution in the while loop block abandoned, but the loop itself is not exited?
Answer:
The continue statement is used to terminate the processing of the block and move control to the next iteration of the loop.

Question 36.
What is a looping use of the range( ) function?
Answer:
The range function is used to generate a sequence of numbers for iteration. For example range(5) returns the list [0,1, 2, 3, 4] This list could be used in a a loop.

Question 37.
Can the else clause be used after a while loop? When is it executed? ,
Answer:
Yes. The else block is executed after the while condition becomes false, but not if the while loop is exited with a break statement.

Question 38.
Illustrate how the range( ) and len( ) functions be used to iterate over the indices of a sequence?
Answer:
myltems = [T, ‘Love’, ‘Python’]
for i in rangeden(myltems)):
print i, myltems[i]

Question 39.
How is the body of a loop defined?
Answer:
The body of the loop is defined by indentation.

Question 40.
How are loops nested?
Answer:
Ever greater levels of indentation.

Question 41.
Illustrate a nested loop that uses the following list IT, ‘Love’, ‘Python’] and outputs each character on a separate line.
Answer:
myltems = [T, ‘Love’, ‘Python’]
for myWord in myltems:
for myChar in myWord:
print myChar

Python Interview Questions on Decision Making and Loops Read More »

CBSE Class 12 Computer Science Python Syllabus

CBSE Class 12 Computer Science Python Syllabus 2021 | Check 12th CBSE Computer Science Python Exam Pattern & How to Download easily?

CBSE Class 12th Computer Science Syllabus 2021 Free Download: Central Board of Secondary Education (CBSE) released the new and revised Computer Science Python Syllabus for Class 12 students (reduced by 30%) 2021. The deleted syllabus of class 12th CBSE Computer Science python is given here in a detailed way along with the latest syllabus 2021-2022.

So, students are urged to check the Revised CBSE 12th Computer Science Syllabus 2021 & kickstart their preparation for future CBSE Class 12 board exams. Below we have also provided some useful links to access and score well in the upcoming CBSE 12th Computer Science Board Exam 2021. Also, check out the detailed steps on how to download the CBSE Class 12 Computer Science Syllabus 2021 from the official site by heading to the below modules.

Click Here To Download CBSE 12th Computer Science Python Syllabus 2021

CBSE Class 12 Computer Science Python Syllabus 2021-22 (New)

For perfect CBSE 12th Board Exam Preparation, you should have to be familiar with the latest and revised CBSE Class 12 Computer science python syllabus and then need to gather the best books and study resources. Here we have provided the unit-wise syllabus of computer science for cbse class 12 students. Access them online and offline by downloading the latest CBSE Syllabus for Class 12 computer science 2021-2022 from the above link and below topics text.

Unit I: Computational Thinking and Programming – 2 – (80 Theory + 70 Practical)

  • Revision of the basics of Python
  • Functions: scope, parameter passing, mutable/immutable properties of data objects, pass arrays to functions, return values, functions using libraries: mathematical, and string functions.
  • File handling: open and close a file, read, write, and append to a file, standard input, output, and error streams, relative and absolute paths.
  • Using Python libraries: create and import Python libraries
  • Recursion: simple algorithms with recursion: factorial, Fibonacci numbers; recursion on arrays: binary search
  • Idea of efficiency: performance defined as inversely proportional to the wall clock time, count the number of operations a piece of code is performing, and measure the time taken by a program. Example: take two different programs for the same problem, and understand how the efficient one takes less time.
  • Data visualization using Pyplot: line chart, pie chart, and bar chart.
  • Data structures: lists, stacks, queues.

Unit 2: Computer Networks (CN) – (30 Theory + 10 Practical)

  • Structure of a network: Types of networks: local area and wide area (web and internet), new technologies such as cloud and IoT, public vs. private cloud, wired and wireless networks; concept of a client and server.
  • Network devices such as a NIC, switch, hub, router, and access point.
  • Network stack: amplitude and frequency modulation, collision in wireless networks, error checking, and the notion of a MAC address, main idea of routing.
  • IP addresses: (v4 and v6), routing table, router, DNS, and web URLs, TCP: basic idea of retransmission, and rate
    modulation when there is congestion (analogy to a road network), Protocols: 2G, 3G, 4G, WiFi. What makes a protocol have a higher bandwidth?
  • Basic network tools: traceroute, ping, ipconfig, nslookup, whois, speed-test.
  • Application layer: HTTP (basic idea), working of email, secure communication: encryption and certificates (HTTPS), network applications: remote desktop, remote login, HTTP, FTP, SCP, SSH, POP/IMAP, SMTP, VoIP, NFC.

Unit 3: Data Management (DM-2) – (20 Theory + 20 Practical)

  • Write a minimal Django based web application that parses a GET and POST request, and writes the fields to a file – flat file and CSV file.
  • Interface Python with an SQL database
  • SQL commands: aggregation functions – having, group by, order by.

Unit 4: Society, Law, and Ethics (SLE-2) – (10 Theory)

  • Intellectual property rights, plagiarism, digital rights management, and licensing (Creative Commons, GPL, and Apache), open source, open data, privacy.
  • Privacy laws, fraud; cyber-crime- phishing, illegal downloads, child pornography, scams; cyber forensics, IT Act, 2000.
  • Technology and society: understanding of societal issues and cultural changes induced by technology.
  • E-waste management: proper disposal of used electronic gadgets.
  • Identity theft, unique ids, and biometrics.
  • Gender and disability issues while teaching and using computers.

Do Refer: Python Programs for Class 12

Deleted Syllabus of Class 12 Computer Science Python CBSE

Unit I: Computational Thinking and Programming – 2

● Recursion – simple algorithms with recursion: print a message forever, the sum of the first n natural numbers, factorial, Fibonacci numbers, recursion on arrays: binary search
● The idea of efficiency: performance measurement in terms of the number of operations.
● Data-structures: Lists as covered in Class XI, Stacks – Push, Pop using a list, Queues – Insert, Delete using a list. (One of the data structures Stack or Queue. Note: While setting the question paper a student will have an option between Stack and Queue.)

Unit II: Computer Networks

● Web Scripting Client-side (VB Script, JavaScript, PHP) and Server-side (ASP, JSP, PHP), Web 2.0 (for social networking)
● E-commerce payment transactions using online banking, mobile banking, payment apps, and services.

Unit III: Database Management

CREATE TABLE, DROP TABLE, ALTER TABLE, UPDATE ….SET, INSERT, DELETE

1. Suggested Practical List: Python Programming

● Recursively find the factorial of a natural number
● Write a recursive code to find the sum of all elements of a list.
● Write a recursive code to compute the nth Fibonacci number

CBSE 12th Class Computer Science Exam Pattern 2021

Marking Scheme plays a vital role in exam preparation time. It covers all required details about the question paper like how many marks each question carries and many more. From the below tabulated CBSE Class 12 Computer Science Python Exam Pattern 2021, you can easily understand which chapter contains a number of marks and the total number of marks to be gained by the students in the examination.

Chapter NameTheory marksTheory periodsPractical periods
Computational Thinking and Programming – 2407050
Computer Networks1015
Database Management202520
TOTAL7011070

12th CBSE Computer Science Practical Exam Pattern & Syllabus

Students of class 12 should aware of the practical exam pattern and provided important lab syllabus topics before they start preparing for the cbse class 12 computer science board exams.

AreaMarks Allotted
Lab Test12
Report file7
Project8
Viva voce3
Total Marks30

A few of the sample lab assignments are listed below:

Python Programming:

  • Recursively find the factorial of a natural number.
  • Write a recursive code to find the sum of all elements of a list.
  • Write a recursive code to compute the nth Fibonacci number.
  • Read a text file line by line and display each word separated by a #.
  • Read a text file and display the number of vowels/ consonants/ uppercase/ lowercase characters in the file.
  • Create a binary file with a name and roll number. Search for a given roll number and display the name, if not found display the appropriate message.
  • Create a binary file with roll numbers, names, and marks. Input a roll number and update the marks.
  • Remove all the lines that contain the character `a’ in a file and write it to another file.
  • Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
  • Write a Python program to implement a stack and queue using a list data-structure.
  • Take a sample of ten phishing e-mails (or any text file) and find the most commonly occurring word(s)

Database Management

  • Create a student table and insert data. Implement the following SQL commands on the student table:
  • ALTER table to add new attributes / modify data type / drop attribute
  • UPDATE table to modify data
  • ORDER By to display data in ascending/descending order DELETE to remove tuple(s)
  • GROUP BY and find the min, max, sum, count, and average
  • A similar exercise may be framed for other cases.
  • Integrate SQL with Python by importing the MySQL module.

Computer Science Project for CBSE Class XII

The aim of the class project is to create something that is tangible and useful. This should be done in groups of 2 to 3 students, and should be started by students at least 6 months before the submission deadline. The aim here is to find a real world problem that is worthwhile to solve. Students are encouraged to visit local businesses and ask them about the problems that they are facing. For example, if a business is finding it hard to create invoices for filing GST claims, then students can do a project that takes the raw data (list of transactions), groups the transactions by category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students can be extremely creative here. They can use a wide variety of Python libraries to create user friendly applications such as games, software for their school, software for their disabled fellow students, and mobile applications, Of course to do some of this projects, some additional learning is required; this should be encouraged. Students should know how to teach themselves.

If three people work on a project for 6 months, at least 500 lines of code is expected. The committee has also been made aware about the degree of plagiarism in such projects. Teachers should take a very strict look at this situation, and take very strict disciplinary action against students who are cheating on lab assignments, or projects, or using pirated software to do the same. Everything that is proposed can be achieved using absolutely free, and legitimate open-source software.

How to download CBSE 12th Class Computer Science Syllabus 2021?

Students who want to download the revised CBSE 12th Class Computer Science Python Syllabus 2021 from the official website should follow the steps furnished below and get a pdf formatted 12th Computer Science syllabus 2021-2022.

  • Step 1 – Open the official website of CBSE ie., cbseacademic.nic.in.
  • Step 2 – After entering the home page, tap the ‘Senior secondary curriculum (XI-XII)’ menu.
  • Step 3 – Now, select ‘Academic Electives – (Group-A)’ option and then choose the ‘Computer Science New XII’
  • Step 4 – Once you choose that option, you will be available with the CBSE Class 12 Computer Science Syllabus 2021 to download for free in PDF. So, download and save it for further reference.

FAQs on CBSE Syllabus for Class 12 Computer Science Python 2021

1. How many units are there in the Class 12 CBSE Computer Science Python Syllabus?

Basically, there are four units that include sub-topics of computer science python in the CBSE Class 12 Computer Science Python Syllabus.

2. Is there any reduced syllabus in CBSE 12th Computer Science Syllabus 2021?

Yes, there is a 30% reduction of the syllabus for the academic year 2021-2022. So, you have to check the deleted syllabus of CBSE Class 12 Computer Science Python from our site before preparation.

3. How to download CBSE Syllabus for Class 12 Computer Science 2021 in PDF?

Just by clicking on the link provided in the above article, you can download CBSE Syllabus for Class 12 Computer Science 2021 in PDF format for free of cost.

4. What is the distribution of marks in the CBSE 12th Computer Science 2020-21 Syllabus?

The marks distribution for CBSE 12th Computer Science 2020-21 Syllabus is as follows:

I. Computational Thinking and Programming 2 – 40 Marks,
II. Computer Networks- 10 Marks and
III. Database Management -20 Marks

CBSE Class 12 Computer Science Python Syllabus 2021 | Check 12th CBSE Computer Science Python Exam Pattern & How to Download easily? Read More »

Python Programming – NumPy

Learn NumPy Library in Python – Complete Guide

Creating Numpy Arrays

  • Create NumPy Arrays from list, tuple, or list of lists
  • Create NumPy Arrays from a range of evenly spaced numbers using np.arrange().
  • Create NumPy Array of zeros (0’s) using np.zeros()
  • Create 1D / 2D NumPy Array filled with ones (1’s) using np.ones()
  • Create NumPy Array of different shapes & initialize with identical values using numpy.full()
  • Create NumPy Array with same sized samples over an interval in Python using numpy.linspace()
  • Create a NumPy Array of bool value.

Adding Elements in Numpy Array

Searching in Numpy Arrays

Get Metadata of Numpy Array

Selecting elements from Numpy Array

Modifying a Numpy Array

Converting NumPy Array to Other Data Structures

Numpy Array and File I/O

Verify Contents of Numpy Array

Counting Elements in Numpy Array

Advance Topics about Numpy Array

  • What is a Structured Numpy Array and how to create and sort it in Python?
  • numpy.zeros() & numpy.ones() | Create a numpy array of zeros or ones

Python Programming – NumPy

NUMPY

As discussed previously, simple one dimensional array operations can be executed using list, tuple etc. But carrying out multi-dimensional array operations using list is not easy. Python has an array module which provides methods for creating array, but they are slower to index than list. A good choice for carrying array operations is by using “NumPy” package.

NumPy is a Python package (licensed under the BSD license) which is helpful in scientific computing by providing multi-dimensional array object, various derived objects (such as masked arrays and matrices), and collection of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, basic linear algebra, basic statistical operations, and many more. At the core of the NumPy package, there is array object which encapsulates n-dimensional arrays of homogeneous data types. There are several important differences between the NumPy array and the standard Python sequence:

  • NumPy array has a fixed size at creation, unlike Python list (which can grow dynamically). Changing the size of a ndarray will create a new array and delete the original.
  • All elements in a NumPy array are required to be of the same data type.
  • NumPy array facilitates advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less code than is possible using Python’s built-in sequences.

History

NumPy is built on (and is a successor to) the successful “Numeric” package. Numeric was reasonably complete and stable, remains available, but is now obsolete. Numeric was originally written in 1995 largely by Jim Hugunin, while he was a graduate student at MIT. In 2001, Travis Oliphant along with Eric Jones and Pearu Peterson created “SciPy”, which had the the strenght of Numeric package along additional functionality. At about the same time as SciPy was being built, some Numeric users were hitting up against the limited capabilities of Numeric.

As a result, “numarray” (now obselete) was created by Perry Greenfield, Todd Miller, and RickWhite at the Space Science Telescope Institute as a replacement for Numeric. In early 2005, Travis Oliphant initiated an effort to bring the diverging community together under a common framework. The effort was paid off with the release of a new package Numpy (with version 0.9.2) in early 2006, which is an amalgam of the code base of Numeric with additional features of numarray. The NumPy name was christened from the unofficial name of “Numerical Python”.

Universal functions

NumPy provides familiar mathematical functions such as sin ( ), cos ( ), exp ( ), etc. In NumPy, these are called “universal functions”. Within NumPy, these functions operate element-wise on an array, producing an array as output.

>>> a=np . arange ( 3 ) 
>>> a 
array ( [ 0 , 1 , 2 ] ) 
>>> np . exp ( a ) 
array ( [ 1 . , 2 . 71828183 , 7 . 3890561 ] )
>>> np . sqrt ( a ) 
array ( [ 0 . , 1 . , 1 . 41421356 ] )

The Matrix Class

There is also a matrix class, which returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations.

>>> np . matrix ( [ [ 1 . 0 , 2 . 0 ] , [ 3 . 0 , 4 . 0 ] ] ) 
matrix ( [ [ 1 . , 2 . ] , 
[ 3 . , 4 . ] ] )
>>> a=np . matrix ( ' 1 . 0 2 . 0 ; 3 . 0 4 . 0 ' ) 
>>> a
matrix ( [ [ 1 . , 2 . ] , 
[ 3 . , 4 . ] ] )
>>> a . T                                                                           # Transpose of a matrix
matrix ( [ [ 1 . , 3 . ] ,
[ 2 . , 4 .] ] ) 
>>> x=np . matrix ( ' 5 . 0 7 . 0 ' )
>>> y=x.T
>>> y
matrix ( [ [ 5 . ] ,
[ 7 . ] ] )
>>> a*y                                                                          # Matrix multiplication
matrix ( [ [ 19 . ] ,
[ 43 . ] ] )
>>> a.I                                                                           # Inverse of a matrix
matrix ( [ [ -2 . , 1 . ] ,
[ 1 . 5 , -0 . 5 ] ] )

In this Page, We are Providing Python Programming – NumPy. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – NumPy Read More »

Python Programming – Basic Operations

In this Page, We are Providing Python Programming – Basic Operations. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Basic Operations

Basic Operations

Arithmetic operations when applied on NumPy arrays, they are implemented element-wise.

>>> a=np . array ( [ 20 , 30 , 40 , 50 ] )
>>> b=np . arange ( 4 ) 
>>> c=a - b 
>>> c
array ( [ 20 , 29 , 38 , 47 ] )
>>> b**2
array ( [ 0 , 1 , 4 , 9 ] )
>>> a<39
array ( [ True , True , False , False ] , dtype=bool )

The product operator * operates element-wise in NumPy arrays. The matrix product can be performed using the dot ( ) function or creating matrix objects (refer section 7.8).

>>> a=np . array ( [ [ 1 , 1 ] ,
. . . [ 0 , 1 ] ] )
>>> b=np . array ( [ [ 2 , 0 ] ,
. . . [ 3 , 4 ] ] )
>>> a*b 
array ( [ [ 2 , 0 ] ,
[ 0 , 4 ] ] )
>>> np . dot ( a , b ) 
array ( [ [ 5 , 4 ] ,
[ 3 , 4 ] ] )

Some operations, such as +=, *=, etc., modifies an existing array, rather than creating a new array.

>>> a=np . array ( [ [ 1 , 2 ] ,                        # a is integer type
. . . [ 3 , 4 ] ] )
>>> b=np . array ( [ [ 1 . , 2 . ] ,                   # b is float type
. . . [ 3 . , 4 . ] ] )
>>> a*=2 
>>> a
array ( [ [ 2 , 4 ] ,
[ 6 , 8 ] ] )
>>> b+=a 
>>> b
array ( [ [ 3 . , 6 . ] ,
[ 9 . , 12 . ] ] )
>>> a+=b                                                  # b is converted to integer type
>>> a
array ( [ [ 5 , 10 ] ,
[ 15 , 20 ] ] )

When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as “upcasting”).

>>> a=np . array ( [ 1 . 1 , 2 . 2 , 3 . 3 ] )
>>> a . dtype . name
' float64 ' 
>>> b=np . array ( [ 4 , 5 , 6 ] )
>>> b . dtype . name ' int32 '
>>> c=a+b 
>>> c
array 0( [ 5 . 1 , 7 . 2 , 9 . 3 ] )
>>> c . dtype . name ' float64 '

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class .

>>> a=np . array ( [ [5 , 8 ] ,
. . . [ 3 , 6 ] ] )
>>> a . sum ( )
22
>>> a . min ( )
3
>>> a . max ( )
8

By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

>>> a=np . arange ( 12 ) . reshape ( 3 , 4 )
>>> a
array ( [ [ 0 , 1 , 2 , 3 ] ,
[ 4 , 5 , 6 , 7 ] ,
[ 8 , 9 , 10 , 11 ] ] )
>>> a.sum(axis=0)                                             # Sum of each column
array ( [12, 15, 18, 21] )
>>> a.min(axis=1)                                             # Minimum of each now
array ( [ 0 , 4 , 8 ] )
>>> a . cumsum ( axis=1 )                                  # Cumulative sum along each now
array ( [ [ 0 , 1 , 3 , 6 ] ,
[ 4 , 9 , 15 , 22 ] ,
[ 8 , 17 , 27 , 38 ] ] )

Python Programming – Basic Operations Read More »

Python Programming – NumPy Array

In this Page, We are Providing Python Programming – Numpy Array. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – NumPy Array

NumPy array

NumPy’s main object is the homogeneous multi-dimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy, array dimensions are called “axes”, and the number of axes is known as “rank”. For example, the coordinates of a point in 3D space [ 1, 2, 1 ] is an array of rank 1, because it has one axis and that axis has a length of 3. In the following example, the array has rank 2 (it is two-dimensional). The first dimension (axis) has a length of 2, the second dimension has a length of 3.

[ [ 1 . , 0 . , 0 . ] , 
[ 0 . , 1 . , 2 . ] ]

Some of the attributes of an ndarray object are:

ndarray . ndim
The number of axes (dimensions) or rank of the array.

ndarray . shape
The dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For an array of n rows and m columns, shape will be (n, m). The length of the shape tuple is therefore the rank ndim.

ndarray.size
The total number of elements of the array. This is equal to the product of the elements of shape.

ndarray.dtype
An object describing the type of the elements in the array. One can create or specify dtype using standard Python type. Additionally, NumPy provides types of its own, numpy.int32, numpy. intl6, and numpy. f loat64 are some examples.

ndarray.itemsize
The size in bytes of each element of the array. For example, an array of elements of type float 6 4 has itemsize as 8 (=64/8), while one of type complex32 has itemsize as 4 (=32/8). It is equivalent to ndarray. dtype . itemsize.’

 

>>> import numpy as np
>>> a=np . array ( [ [ 0 , 1 , 2 , 3 , 4 ] ,
. . .                           [ 5 , 6 , 7 , 8 , 9 ] , 
. . .                           [ 10 , 11 , 12 , 13 , 14 ] ] )
. . . 
>>> type ( a )
<type ' numpy . ndarray ' > 
>>> a . shape 
( 3 , 5 )
>>> a . ndim 
2
>>> a.dtype 
dtype ( ' int32 ' )
>>> a . dtype . name
' int32 '
>>> a.itemsize 
4
>>> a . size 
15

Array creation

There are several ways to create NumPy array, one approach is from a regular Python list or tuple using the array () method. The type of the resulting array is deduced from the type of the elements in the sequences.

>>> import numpy as np 
>>> a=np.array ( [ 1 , 2 , 3 ] )
>>> a . dtype 
dtype ( ' int32 ' )
>>> b=np . array ( ( 1 . 2 , 3 . 4 , 5 . 6 ) )
>>> b. dtype 
dtype ( ' float64 ' )

A frequent error consists in calling array ( ) with multiple numeric arguments, rather than providing a single list or tuple of numbers as an argument.

>>> a=np . array ( 1 , 2 , 3 , 4 )      # WRONG
>>> a=np . array ( [ 1 , 2 , 3 , 4] )  # RIGHT

array ( ) transforms sequence of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.

>>> b=np . array ( [ ( 1 . 5 , 2 , 3 ) , ( 4 , 5 , 6 ) ] )
>>> b
array ( [ [ 1 . 5 , 2 . , 3 . ] ,
[ 4 . , 5 . , 6 . ] ] )

The type.of the array can also be explicitly specified at creation time:

>>> c=np . array ( [ [ 1 , 2 ] , [ 3 , 4 ] ] , dtype=np.complex)
>>> c
array ( [ [ 1 .+0 . j , 2 . + 0 . j ] ,
[ 3 . +0 . j , 4 . + 0 . j ] ] )

Often the elements of an array are initially unknown, but array size is known. Hence, NumPy offers several functions to create array with initial placeholder content. The function zeros ( ) create an array full of zeros, the function ones ( ) create an array full of ones, and the function empty ( ) create an array whose initial content is random. By default, the dtype of the created array is f loat6 4.

>>> np. zeros ( ( 3 , 4 ) )
array ( [ [ 0 . , 0 . , 0 . , 0 . ] ,
             [ 0 . , 0 . , 0 . , 0 . ] ,
             [ 0 . , o . , 0 . , 0 . ] ] )
>>> np . zeros [ 3 , 4] ) 
array ( [ [ 0 . , o . , o . , 0 . ] ,
           [ o . , o . , o . , 0 . ] ,
           [ o . , o . , o . , 0 . ] ] )
>>> np . ones ( ( 2 , 3 , 4 ) , dtype=np . int16 ) 
array ( [ [ [ 1 , 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 , 1] ] ,

           [ [ 1 , 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 , 1 ] ] ] , dtype=intl6 )
>>> np . empty ( ( 2 , 3 ) )
array ( [ [ 1 . 39069238e-309 , 1 . 39069238e-309 , 1 . 39069238e-309 ] ,
           [ 1 . 39069238e-309 , 1 . 39069238e-309 , 1 . 39069238e-309 ] ] )

 

To create sequences of numbers, NumPy provides a function arange ( ), analogous to Python’s built- in function range ( ), that returns array instead of list.

>>> np . arange ( 10 , 30 , 5 ) 
array ( [ 10 , 15 , 20 , 25 ] )
>>> np . arange ( 0 , 2 , 0 . 3 )
array ( [ 0 . , 0 . 3 , 0 . 6 , 0 . 9 , 1 . 2 , 1 . 5 , 1 . 8 ] )

When arange ( ) is used with floating point arguments, it is generally not possible to predict the number of elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the function linspace ( ), that receives as an argument the number of elements that we want, instead of the step:

>>> np . linspace ( 0 , 2 , 5 )
array ( [ 0 . , 0 . 5 , 1 . , 1 . 5 , 2 . ] )
>>> np . linspace ( 0 , np . pi , 4 )
array ( [ 0 . , 1 . 04719755 , 2 . 0943951 , 3 . 14159265 ] )

Printing array

While printing an array, NumPy display it in a similar way to nested lists, but with the following layout:

  • the last axis is printed from left to right.
  • the second-to-last is printed from top to bottom.
  • the rest are also printed from top to bottom, with each slice separated from the next by an empty line.
>>> np . arange ( 6 )                                                     # Id array
array ( [ 0 , 1 , 2 , 3 , 4 , 5 ] )
>>>
>>> np . arange ( 12 ) . reshape ( 4 , 3 )                       # 2d array
array ( [ [ 0 , 1 , 2 ] ,
           [ 3 , 4 , 5 ] ,
           [ 6 , 7 , 8 ] ,
           [ 9 , 10 , 11 ] ] )
>>>
>>> np . arange ( 24 ) . reshape ( 2 , 3 , 4 )                    # 3d array
array ( [ [ [ 0 , 1 , 2 , 3 ] ,
           [ 4 , 5 , 6 , 7 ] , 
           [ 8 , 9 , 10 , 11 ] ]

          [ [12 , 13 , 14 , 15 ] ,
          [ 16 , 17 , 18 , 19 ] ,
          [ 20 , 21 , 22 , 23 ] ]

If an array is too large to be printed, NumPy automatically skips the central part of the array and only print the corners:

>>> np . arange ( 10000 )
array ( [ 0 , 1 , 2 , 9997 , 9998 , 9999 ] )
>>>
>>> np . arange ( 10000 ) . reshape ( 100 , 100 )
array ( [ [ 0 , 1 , 2 , . . . , 97 , 98 , 99 , ] , 
[ 100, 101, 102, . . . , 197 , 198 , 199 ] ,
[ 200 , 201 , 202 , . . . , 297 , 298 , 299 ] ,
. . . 
[ 9700 , 9701 , 9702 , . . . , 9797 , 9798 , 9799 ] ,
[ 9800 , 9801 , 9802 , . . . , 9897 , 9898 , 9899 ] ,
[ 9900 , 9901 , 9902 , . . . , 9997 , 9998 , 9999 ] ]

To disable this behaviour and force NumPy to print the entire array, the printing option set_printoptions need to be changed.

>>> np . set_printoptions ( threshold=' nan '

Python Programming – NumPy Array Read More »

Python Programming – Inheritence

In this Page, We are Providing Python Programming – Inheritence. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Inheritence

Inheritence

A class can be based on one or more other classes, called its “base class(es)”. It then inherits the data attributes and methods of its base classes. This is called “inheritance”, and the class which inherits from the base class is called “derived class”. A class definition first evaluates the inheritance list, if present. A simple form of derived class definition looks like this:

class DerivedClassName ( BaseClassName ) :
<statement-1> 
.
.
.
<statement-N>

In place of a base class name BaseClassName, other arbitrary expressions are also allowed. This is useful, for example, when the base class is defined in another module:

class DerivedClassName ( modname . BaseClassName ) :

The following example demonstrates class inheritance.

class Parent:                              # Base class definition
parentAttr=100

def ___init___ ( self ) :
        print "Base class"

def parentMethod ( self ) :
         print ' Base class method '

def setAttr ( self , attr ) :
          Parent.parentAttr=attr

def getAttr ( self ) :
    print "Parent attribute : " , Parent . parentAttr

class Child ( Parent ) :               # Derived class definition

def ___init___ ( self ) :
      print " Derived class "

def childMethod ( self ) :
print ' Derived class method '

c=Child ( ) 
c . childMethod ( ) 
c . parentMethod ( ) 
c.setAttr ( 200 ) 
c . getAttr ( )

The output is:

Derived class 
Derived class method 
Base class method 
Parent attribute : 200

Execution of a derived class definition proceeds in the same way as for a base class. If a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.

The following example is a step further in understanding inheritance.

class Person :
population=0

def ___init___ ( self , Name , Age ) :
         self . name=Name 
         self . age=Age
        Person . population+=1

def Record ( self ) :
          print ( ' Name : " { 0 } " Age : { 1 }" ' . format ( self . name , self . age ) )

class Employee ( Person ) :
def ___init___ ( self , Name , Age , Salary ) :
           Person. ___init___ ( self , Name , Age )
           self . salary=Salary
           print ( ' Entered record for { 0 } ' . format ( self . name ) )

def Record ( self ) :
       Person . Record ( self )
       print ( ' Salary : " { 0 : d } " ' . format ( self . salary ) )

class Employer ( Person ) :

def ___init___ ( self , Name , Age , Percentage ) :
          Person. ___init___ ( self , Name , Age )
          self . percentage=Percentage
          print ( 'Entered record for { 0 } ' .format ( self . name ) )

def Record ( self ) :
       Person . Record ( Self )
       print ( ' Partnership percent : "{ 0 : d }" ' . format ( self . percentage ) )

employee1=Employee ( ' Ram ', 26 , 25000 ) 
employee2=Employee ( ' Ahmed ' , 20 , 50000 )
employee3=Employee ( ' John ' , 22 , 75000 ) 
employer1=Employer ( ' Michael ' , 58 , 60 ) 
employer2=Employer ( ' Kishah ' , 52 , 40)

members=[employee1 , employee2 , employee3 , employer1,employer2] 
for member in members : 
member . Record ( )

The output is:

Entered record for Ram 
Entered record for Ahmed
Entered: record for John .
Entered record for Michael 
Entered record for Kishan 
Name : " Ram " Age : " 26 "
Salary : " 25000 " 
Name : " Ahmed " Age : " 20 " 
Salary : " 50000 " 
Name : " John " Age : " 22 "
Salary : " 75000 " 
Name : "Michaei " Age : " 58 "'
Partnership percent : " 60 "
Name : " Kishan " Age : " 52 " 
Partnership percent : " 40 "

Please note that, if a base class has an ___init___ ( ) method, the derived class’s ___init___ ( ) method, if any, must explicitly call it, to ensure proper initialization of the base class part of the instance; for example : BaseClass. ___init____ ( self , [ args . . . ] ).

New-style and classic classes

Classes and instances come in two flavors: old-style (or classic) and new-style. New-style classes were introduced in Python 2.2. For compatibility reasons, classes are still old-style by default. Any class which inherits from object is a new-style class. The object class is a base for all new style classes. The following is an example showing simple definitions of old-style and new-style classes.

>>> class ClassicExample :
. . .               def ___init___ ( self ) :
. . .               pass
. . . 
>>> class NewStyleExample ( object ) :
. . .                def ___init___ ( self ) :
. . .                       pass 
. . .
>>>

Overriding Methods

Derived classes may override methods of their base classes. A method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it.

# InheritenceExample2 . py

class Parent :                                                                # Base class definition

def printlnfo ( self ) :
                  print ' Base class method '

def parentMethod ( self ) :
                   self . printlnfo ( )

class Child ( Parent ) :                                                   # Derived class definition

def printlnfo ( self ) :
       print ' Derived class method '

c=Child ( ) 
c . parentMethod ( )

The output is:

Derived class method

It can be seen that printlnfo ( ) of derived class is called instead of base class.

Super ( ) function

The is a built-in function super ( ), which can be used for accessing inherited methods that have been overridden in a class. The super ( ) only works for new-style classes; in a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable.

class Parent ( object ) :                              # Base class definition

def printlnfo ( self ) :
            print ' Base class method '
            def parentMethod ( self ) :
            self . printlnfo ( )

class Child ( Parent ) :                              # Derived class definition

def printinfo ( self ) :
              super ( Child , self ) . printlnfo ( )
#            Parent . printlnfo ( self ) 
              print ' Derived class method '

e=Child ( )
c . parentMethod ( )

The output is:

Base class method 
Derived class method

In the above example, to access the printlnfo ( ) method of Parent class, super ( ) method in the form of super (Child, self) .printlnfo () is used, where the name of base class is not mentioned. The other way would have been by using Parent .printlnfo (self).

Name mangling

In Python, there is a mechanism called “name mangling” to avoid name clashes of names in class with names defined by sub-classes. Any identifier of the form ____spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname___ spam, where classname is the current class name. Note that, the mangling rule is designed mostly to avoid accidents.

# InheritenceExample3 . py

Class Parent :                                       # Base class definition

def ___printlnfo ( self ) :
         print ' Base class method '

def parentMethod ( self ) :
             self. ___print Info ( )

class Child (Parent) :                         # Derived class definition

def printlnfo ( self ) :
          print ' Derived class method '

c=Child ( ) 
print Parent. ___diet___ . keys ( )
print Child. ___diet___ . keys ( )
c . parentMethod ( )
c ._Child___printlnfo ( )
c . _Parent___printlnfo ( )

The output is:

[ ' ____module___ ' , ___Parent___printlnfo ' , ' ____doc___ ' , ' parentMethod ' ]
[' ____module ____ ' , ' ___doc____ ' , ' ___Child____printlnfo ' ]
Base class method 
Derived class method 
Base class method

Multiple inheritence

Till now, the discussion was about inheriting from one class; this is called “single inheritance”. Python also supports “multiple inheritance”, where a class can inherit from more than one class. A simple class definition inheriting from multiple base classes looks like:

class DerivedClassName ( Base1 , Base2 , Base3 ) :
<statement-1>
.
.
.
<statement-N>

Whenever there is a call via DerivedClassName class instance, Python has to look-up the possible function in the class hierarchy for Basel, Base2 , Base3 , but it needs to do this in a consistent order. To do this, Python uses an approach called “method resolution order” (MRO) using an algorithm called “C3” to get it straight.

Consider the following multiple inheritance example.

class A ( object ) :
        def printlnfo ( self ) : 
         print ' Class A '

class B ( A ) : 
       def printlnfo ( self ) : 
       print ' Class B '
#     super ( B , self ) . printlnfo ( )
        A . printlnfo ( self )

class C ( A ) :
         def printlnfo ( self ) : 
         print ' Class C ' 
         super ( C , self ) . printlnfo ( )
class D ( B , C ) : 
       def printlnfo ( self ) : 
       print ' Class D ' 
       super ( D , self ) . printlnfo ( ) 
foo=D ( )
foo . printInfo ( )

Running the code yield the following output.

Class D
Class B
Class A

It can be observed that C class printlnfo ( ) is skipped. The reason for that is because B class printlnfo ( ) calls A class printlnfoO directly. The purpose of super ( ) is to entertain method resolution order. Now un-comment super (B, self) .printlnfoO and comment-out A. print Info (self). The code now yields a different result.

Class D 
Class B 
Class C 
Class A

Now all the printinfo ( ) methods get called. Notice that at the time of defining B. print Info ( ), one can think that super (B, self) .printlnfo ( ) is the same as calling A. print Info (self), however, this is wrong. In the above situation, super (B, self). print Info ( ) actually calls C . printInfo ( self ).

Python Programming – Inheritence Read More »

Python Programming – Package

In this Page, We are Providing Python Programming – Package. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Package

Package

As discussed previously, functions and global variables usually reside inside a module. There might be a scenario where organizing modules needs to be done. That is where packages come into the picture. Packages are just folders of modules with a special ” ____init___ .py” file, that intimate Python that this folder is special because it contains Python modules. In the simplest case, ” ____init_____ .py” can just be an empty file, but it can also execute initialization code for the package or set _____all _____variables, described later.

Suppose there is an objective to design a collection of modules (a “package”) for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: .wav, .aiff, .au), so it might be needed to create and maintain a growing collection of modules for the conversion between the various files formats. There are also many different operations that are needed to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so there will be numerous modules to perform these operations. Here is a schematic structure for the package:

sound/                                                            Top-level package
                      _____init_____ .                           py Initialize the sound package
formats/                                                          Subpackage for file format conversions
                    _____init______ .py
                    wavread . py 
                    wavwrite . py 
                    aiffread . py 
                    aiffwrite . py 
                    auread . py 
                    auwrite . py
                    . . . 
effects/                                                            Subpackage for sound effects
                     _____init_______ .py
                     echo . py 
                     surround . py
                     reverse . py
                      . . . 
filters/                                                               Subpackage for filters
                     _____init_______ .py
                     equalizer . py 
                     vocoder . py 
                     karaoke . py
                     . . .

When importing the package, Python searches through the directories on sys .path looking for the package subdirectory. Users of the package can import individual modules from the package, for example:

import sound . effects . echo

This loads the sub-module sound. effects. echo. It must be referenced with its full name.

sound . effects . echo . echofilter ( input , output , delay=0 . 7 , atten=4 )

An alternative way of importing the sub-module is:

from sound .  effect's import echo

This loads the sub-module echo, and makes it available without its package prefix, so it can be used as follows:

echo . echofilter ( input , output , delay=0 . 7 , atten=4 )

Yet another variation is to import the desired function or variable directly:

from sound . effects . echo import echofilter

This makes echofilter ( ) directly available:

echofilter ( input , output , delay=0 . 7 , atten=4 )

Note that when using from package import item, the item can be either a sub-module (or sub-package) of the package, or some other name defined in the package, like a function, class, or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised. Contrarily, when using syntax like import item, subitem, sub subitem, each item except for the last must be a package; the last item can be a module or a package but cannot be a class or function or variable defined in the previous item.

Importing * from a package

What happens when the programmer writes from sound, effects import *? Ideally, one would hope that this somehow goes out to the file system, finds which sub-modules are present in the package, and imports them all. This could take a long time.

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s _____init_____ .py code defines a list named _____all_____, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they does not see a use for importing * from their package. For example, the file sounds/effects/ ____init_____ .py could contain the following code:

____all_____ = [ " echo " ,  " surround " ,  " reverse " ]

This would mean that from the sound. effects import * would import the three named sub-modules of the sound package.

If _____all_____ is not defined, the statement from sound, effects import * does not import all sub-modules from the package sound. effects into the current namespace; it only ensures that the package sound. effects have been imported (possibly running any initialization code init .py) and then imports whatever names are defined in the package. This includes any names defined (and sub-modules explicitly loaded) by ____init______ .py. It also includes any sub- .rhodules of the package that were explicitly loaded by previous import statements.

Remember, there is nothing wrong with using from Package import specific___submodule. In fact, this is the recommended notation, unless the importing module need to use sub-modules with the same name from different packages.

Intra-package references

The sub-modules often need to refer to each other. For example, the surround module might use the echo module. In fact, such references are so common that the import statement first looks in the containing package before looking in the standard module search path. Thus, the surround module can simply use import echo or from echo import echofilter. If the imported module is not found in the current package (the package of which the current module is a sub-module), the import statement looks for a top-level module with the given name.

When packages are structured into sub-packages (as with the sound package in the example), the programmer can use absolute imports to refer to sub-modules of siblings packages. For example, if the module sound, filters .vocoder needs to use the echo module in the sound. effects package,it can use from sound.effects import echo.

Starting with Python 2.5, in addition to the implicit relative imports described above, the programmer can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use:

from . import echo
from . . import formats
from . .filters import equalizer

Packages in multiple directories

Package support one more special attribute, ____path____ . This is initialized to be a list containing the name of the directory holding the package’s ___init____ .py before the code in that file is executed. This variable can be modified, doing so affects future searches for modules and sub-packages contained in the package. While this feature is not often needed, it can be used to extend the set of modules found in a package.

>>> import numpy 
>>> numpy. _____path_____
[ ’ C : \ \ Python27 \ \ lib \ \ site - packages \ \ numpy ' ]

Python Programming – Package Read More »