You are on page 1of 18

1. What is the global variable?

Variables that are created outside of a functions are known as global variables.


Global variables can be used by everyone, both inside of functions and outside.
Example:
x = "Good Morning"
def myfunc():
  print("Python is " + x)
myfunc()

2. What is the local variable?


Local variables in python are those variables that are declared inside the function.
Alternatively, they are said to defined within a local scope. A user can only access a
local variable inside the function but never outside it.
Example:
def f():
      s = "I love Geeksforgeeks"
     print("Inside Function:", s)
   f()
print(s)

3. What is the difference between Python Arrays and lists?


List: A list in Python is a collection of items which can contain elements of multiple
data types, which may be either numeric, character logical values, etc. It is an
ordered collection supporting negative indexing. A list can be created using []
containing data values. Contents of lists can be easily merged and copied using
python’s inbuilt functions.
Array: An array is a vector containing homogeneous elements i.e. belonging to the
same data type. Elements are allocated with contiguous memory locations allowing
easy modification, that is, addition, deletion, accessing of elements. In Python, we
have to use the array module to declare arrays.

4. What does len() do?


The len() function returns the number of items in an object. When the object is a
string, the len() function returns the number of characters in the string.
Syntax:
len(object)

Example:
mylist = "Hello"
x = len(mylist)

5. How to add values to a python array?


An array is a special variable, which can hold more than one value at a time. You can
use the append() method to add an element to an array.
Example

Add one more element to the cars array:


cars.append("Honda")

6. How to remove values to a python array?


You can use the pop() method to remove an element from the array.
Example

Delete the second element of the cars array:

cars.pop(1)

You can also use the remove() method to remove an element from the array.

Delete the element that has the value "Volvo":

cars.remove("Volvo")

7. What are Python libraries? Name a few of them.


Python Libraries are a set of useful functions that eliminate the need for writing
codes from scratch.

 TensorFlow.
 Scikit-Learn.
 Numpy.
 Keras.
 PyTorch.
 LightGBM.
 Eli5.
 SciPy.

8. How to import modules in python?


Import in python is similar to #include header_file in C/C++. Python modules can
get access to code from another module by importing the file/function using import.
The import statement is the most common way of invoking the import machinery,
but it is not the only way.
import module_name
When the import is used, it searches for the module initially in the local scope by
calling __import__() function. The value returned by the function is then reflected in
the output of the initial code. 

Example
import math
pie = math.pi
print("The value of pi is : ",pie)

9. Give some examples of string functions.


Python string is a sequence of Unicode characters that is enclosed in the quotations
marks.

lower(): Converts all uppercase characters in a string into lowercase


upper(): Converts all lowercase characters in a string into uppercase
title(): Convert string to title case 
replace() : returns a copy of the string where all occurrences of a substring are
replaced with another substring. 

10. What is recursion?


Python also accepts function recursion, which means a defined function can call
itself. Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.

11. What is split used for?


Split is used to break a delimited string into substrings. You can use either a
character array or a string array to specify zero or more delimiting characters or
strings.
Example:
txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(", ")
print(x)

12. What does [::-1} do?


If you leave slots empty, there's a default. [:] means: The whole thing. [::1]
means: Start at the beginning, end when it ends, walk in steps of 1 (which is the
default, so you don't even need to write it). [::-1] means: Start at the end (the minus
does that for you), end when nothing's left and walk backwards by 1.

13. How do you access an element in the array?

An array in Python is used to store multiple values or items or elements of the same
type in a single variable. To access elements of an array using the index operator [].
To access a particular element is to call the array you created. Beside the array is the
index [] operator, which will have the value of the particular element’s index position
from a given array.

14. What are the advantages of Numpy?


NumPy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays. It is the
fundamental package for scientific computing with Python. It is open-source software.
It contains various features including these important ones:
 A powerful N-dimensional array object
 Sophisticated (broadcasting) functions
 Tools for integrating C/C++ and Fortran code
 Useful linear algebra, Fourier transform, and random number capabilities

15. What is function composition?


Function composition is the way of combining two or more functions in such a way
that the output of one function becomes the input of the second function and so
on. For example, the composition of a function is an operation where two functions
say f and g generate a new function say h in such a way that h(x) = g(f(x)). It
means here function g is applied to the function of x. So, basically, a function is
applied to the result of another function.
Part - B
16. Explain about functions and return values.
The Python return statement is a special statement that you can use inside a function or
method to send the function's result back to the caller. A return statement consists of
the return keyword followed by an optional return value. The return value of a
Python function can be any Python object. A return statement is overall used to
invoke a function so that the passed statements can be executed. Return statement
can not be used outside the function.

Syntax:
def fun():
statements
.
.
return [expression]

Example:
def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Returning Multiple Values


In Python, we can return multiple values from a function. Following are different
ways.  
Using Object: This is similar to C/C++ and Java, we can create a class (in C,
struct) to hold multiple values and return an object of the class. 
Example:
class Test:
    def __init__(self):
        self.str = "geeksforgeeks"
        self.x = 20  
def fun():
    return Test()
t = fun() 
print(t.str)
print(t.x)

17. Write a Python function that takes two lists and returns True if they have at least one
common member.

def common_data(list1, list2):


result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [5,6,7,8,9]))
print(common_data([1,2,3,4,5], [6,7,8,9]))

18. Explain local and global scope with example?


There are two types of variables: global variables and local variables.
The scope of global variables is the entire program whereas the scope of local variable
is limited to the function where it is defined.
def func():
x = "Python"
print(x)
print(s)
s = "Programming"
print(s)
func()
print(x)

In above program- x is a local variable whereas s is a global variable, we can access


the local variable only within the function it is defined (func() above) and trying to call
local variable outside its scope(func()) will through an Error. However, we can call
global variable anywhere in the program including functions (func()) defined in the
program.
Local Variable:
Local variables can only be reached within their scope(like func() above).
def sum(x,y):
sum = x + y
return sum
print(sum(5, 10))
Global variables
A global variable can be used anywhere in the program as its scope is the entire
program.
z = 25
def func():
global z
print(z)
z=20
func()
print(z)

19. Write short notes on function composition.


Function composition is the way of combining two or more functions in such a way
that the output of one function becomes the input of the second function and so on.
For example, let there be two functions “F” and “G” and their composition can be
represented as F(G(x)) where “x” is the argument and output of G(x) function will
become the input of F() function.
Example:
def add(x):
    return x + 2
def multiply(x):
    return x * 2
print("Adding 2 to 5 and multiplying the result with 2: ", 
      multiply(add(5)))

First the add() function is called on input 5. The add() adds 2 to the input and the


output which is 7, is given as the input to multiply() which multiplies it by 2 and the
output is 14
Better way to implement composition
There is a better way to implement the composition of Function. We can create a
special function which can combine any two functions.
def composite_function(f, g):
    return lambda x : f(g(x))
def add(x):
    return x + 2
  
def multiply(x):
    return x * 2
add_multiply = composite_function(multiply, add)
print("Adding 2 to 5 and multiplying the result with 2: ",
      add_multiply(5))
20. Write short notes on recursion.

Python also accepts function recursion, which means a defined function can call
itself.Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.The developer should be very careful with recursion as it can be quite
easy to slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly recursion
can be a very efficient and mathematically-elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself


("recurse"). We use the k variable as the data, which decrements (-1) every time we
recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

Example:

def tri_recursion(k):
  if(k>0):
    result = k+tri_recursion(k-1)
    print(result)
  else:
    result = 0
  return result

print("\n\nRecursion Example Results")


tri_recursion(6)

21. Explain any five string functions .


Python string is a sequence of Unicode characters that is enclosed in the quotations
marks. In this article, we will discuss the in-built function i.e. the functions provided
by the Python to operate on strings. 

The below functions are used to change the case of the strings.
lower(): Converts all uppercase characters in a string into lowercase
upper(): Converts all lowercase characters in a string into uppercase
title(): Convert string to title case

Python String capitalize() method


Python String capitalize() method returns a copy of the original string and converts
the first character of the string to a capital (uppercase) letter, while making all other
characters in the string lowercase letters.

Syntax
string_name.capitalize()
Parameter:  The capitalize() function does not takes any parameter. 
Return: The capitalize() function returns a string with the first character in the
capital.
Example:
name = "Welcome"
print(name.capitalize())

String casefold() Method


Python String casefold() method is used to convert string to lower case. It is similar
to lower() string method, but case removes all the case distinctions present in a
string.
Syntax: 
 string.casefold()
Parameters: The casefold() method doesn’t take any parameters.
Return value: Returns the case folded string the string converted to lower case.
Example
string = "Welcome"
print("lowercase string: ", string.casefold())

22. Explain about the string module.


There is an older module named string. Almost all of the functions in this module are
directly available as methods of the string type. The one remaining function of value is
the maketrans function, which creates a translation table to be used by
the translate method of a string. Beyond that, there are a number of public module
variables which define various subsets of the ASCII characters.
maketrans( from , to ) → string
Return a translation table (a string 256 characters long) suitable for use
in string.translate. The strings from and to must be of the same length.
The following example shows how to make and then apply a translation table.
>>>
from string import maketrans

>>>
t= maketable("aeiou","xxxxx")

>>>
phrase= "now is the time for all good men to come to the aid of their party"

>>>
phrase.translate(t)

'nxw xs thx txmx fxr xll gxxd mxn tx cxmx tx thx xxd xf thxxr pxrty'

This module contains a number of definitions of the characters in the ASCII character
set. These definitions serve as a central, formal repository for facts about the character
set. Note that there are general definitions, applicable to Unicode character setts,
different from the ASCII definitions.
ascii_letters
The set of all letters, essentially a union
of ascii_lowercase and ascii_uppercase.
ascii_lowercase
The lowercase letters in the ASCII character
set: 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase
The uppercase letters in the ASCII character
set: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits
The digits used to make decimal numbers: '0123456789'
hexdigits
The digits used to make hexadecimal numbers: '0123456789abcdefABCDEF'
letters
This is the set of all letters, a union of lowercase and uppercase, which depends
on the setting of the locale on your system.
lowercase
This is the set of lowercase letters, and depends on the setting of the locale on
your system.
octdigits
The digits used to make octal numbers: '01234567'
printable
All printable characters in the character set. This is a union of digits, letters,
punctuation and whitespace.
punctuation
All punctuation in the ASCII character set, this is '!"#$%&\'()*+,-./:;<=>?
@[\\]^_`{|}~'
uppercase
This is the set of uppercase letters, and depends on the setting of the locale on
your system.
whitespace
A collection of characters that cause spacing to happen. For ASCII this is '\t\n\
x0b\x0c\r ’

23. Explain about arrays in python.


An array is a collection of items stored at contiguous memory locations. The idea is
to store multiple items of the same type together. This makes it easier to calculate the
position of each element by simply adding an offset to a base value, i.e., the memory
location of the first element of the array (generally denoted by the name of the
array).
Creating an Array
Array in Python can be created by importing array
module. array(data_type, value_list) is used to create an array with data type and
value list specified in its arguments. 

import array as arr


a = arr.array('i', [1, 2, 3])
print ("The new created array is : ", end =" ")
for i in range (0, 3):
    print (a[i], end =" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print ("The new created array is : ", end =" ")
for i in range (0, 3):
    print (b[i], end =" ")

Adding Elements to an Array


Elements can be added to the Array by using built-in insert() function. Insert is used
to insert one or more data elements into an array. Based on the requirement, a new
element can be added at the beginning, end, or any given index of array. append() is
also used to add the value mentioned in its arguments at the end of the array.  

import array as arr


a = arr.array('i', [1, 2, 3])
print ("Array before insertion : ", end =" ")
for i in range (0, 3):
    print (a[i], end =" ")
print()
a.insert(1, 4)
print ("Array after insertion : ", end =" ")
for i in (a):
    print (i, end =" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print ("Array before insertion : ", end =" ")
for i in range (0, 3):
    print (b[i], end =" ")
print()

b.append(4.4)
 
print ("Array after insertion : ", end =" ")
for i in (b):
    print (i, end =" ")
print()

Accessing elements from the Array


To access the array items refer to the index number. Use the index operator [ ] to access an
item in a array. The index must be an integer. 

24. Explain any five methods used on arrays.


1. append() 
The append() method appends an element to the end of the list.
Syntax
list.append(elmnt)
Example
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
2. clear() 
The clear() method removes all the elements from a list.
Syntax
list.clear()

Example
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()

3. copy()
The copy() method returns a copy of the specified list.
Syntax
list.copy()
Example
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
4. count()
The count() method returns the number of elements with the specified value.
Syntax
list.count(value)
Example
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
5. extend() 
The extend() method adds the specified list elements (or any iterable) to the end of the
current list.
Syntax
list.extend(iterable)
Example
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)

25. Write a program to access an element in arrays.


To access the array elements using the respective indices of those elements.
import array as arr  
a = arr.array('i', [2, 4, 6, 8])  
print("First element:", a[0])  
print("Second element:", a[1])  
print("Second last element:", a[-1])  
Output : 
First element: 2
Second element: 4
Second last element: 8
PART – C
1. Explain about functions and its returning types with an example.
A function is a collection of related assertions that performs a mathematical,
analytical, or evaluative operation. Python functions are simple to define and essential
to intermediate-level programming. The exact criteria hold to function names as they
do to variable names. The goal is to group up certain often performed actions and
define a function. Rather than rewriting the same code block over and over for varied
input variables, we may call the function and repurpose the code included within it
with different variables.
Advantages
o By including functions, we can prevent repeating the same code block repeatedly in a
program.
o Python functions, once defined, can be called many times and from anywhere in a
program.
o If our Python program is large, it can be separated into numerous functions which is
simple to track.
o The key accomplishment of Python functions is we can return as many outputs as we
want with different arguments.
Syntax
def name_of_function( parameters ):  
    """This is a docstring"""  
    # code block 
return Statement
We write a return statement in a function to leave a function and give the calculated
value when a defined function is called.
Syntax:
return < expression to be returned as output >  
An argument, a statement, or a value can be used in the return statement, which is given as
output when a specific task or function is completed. If we do not write a return statement,
then None object is returned by a defined function.
Example:
def square( num ):  
    return num**2  
   
print( "With return statement" )  
print( square( 39 ) )  
  
def square( num ):  
     num**2   
  
print( "Without return statement" )  
print( square( 39 ) )  

2. Explain about recursion with an example.


It is a process in which a function calls itself directly or indirectly.

Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a


function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.

In this example, tri_recursion() is a function that we have defined to call itself


("recurse"). We use the k variable as the data, which decrements (-1) every time we
recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

Advantages

 A complicated function can be split down into smaller sub-problems utilizing


recursion.
 Sequence creation is simpler through recursion than utilizing any nested iteration.
 Recursive functions render the code look simple and effective.

Disadvantages
 A lot of memory and time is taken through recursive calls which makes it
expensive for use.
 Recursive functions are challenging to debug.
 The reasoning behind recursion can sometimes be tough to think through.

Syntax:

def func(): <--


|
| (recursive call)
|
func() ----

Example:

def recursive_fibonacci(n):
  if n <= 1:
      return n
  else:
      return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
 
n_terms = 10
 
# check if the number of terms is valid
if n_terms <= 0:
  print("Invalid input ! Please input a positive value")
else:
  print("Fibonacci series:")
for i in range(n_terms):
    print(recursive_fibonacci(i))

3. Explain all the string functions and methods with examples.


Python string is a sequence of Unicode characters that is enclosed in the quotations
marks. In this article, we will discuss the in-built function i.e. the functions provided
by the Python to operate on strings. 

The below functions are used to change the case of the strings.
lower(): Converts all uppercase characters in a string into lowercase
upper(): Converts all lowercase characters in a string into uppercase
title(): Convert string to title case

Python String capitalize() method


Python String capitalize() method returns a copy of the original string and converts
the first character of the string to a capital (uppercase) letter, while making all other
characters in the string lowercase letters.

Syntax
string_name.capitalize()
Parameter:  The capitalize() function does not takes any parameter. 
Return: The capitalize() function returns a string with the first character in the
capital.

Example:
name = "Welcome"
print(name.capitalize())
String casefold() Method
Python String casefold() method is used to convert string to lower case. It is similar
to lower() string method, but case removes all the case distinctions present in a
string.
Syntax: 
 string.casefold()
Parameters: The casefold() method doesn’t take any parameters.
Return value: Returns the case folded string the string converted to lower case.
Example
string = "Welcome"
print("lowercase string: ", string.casefold())

Everything in Python is an object. A string is an object too. Python provides us with


various methods to call on the string object.
1. s.capitalize() in Python

Capitalizes a string
>>> s = "heLLo BuDdY"
>>> s2 = s.capitalize()
>>> print(s2)
2. s.lower() in Python

Converts all alphabetic characters to lowercase


>>> s = "heLLo BuDdY"
>>> s2 = s.lower()
>>> print(s2)
3. s.upper() in Python

Converts all alphabetic characters to uppercase


>>> s = "heLLo BuDdY"
>>> s2 = s.upper()
>>> print(s2)
4. s.title() in Python

Converts the first letter of each word to uppercase and remaining letters to


lowercase
>>> s = "heLLo BuDdY"
>>> s2 = s.title()
>>> print(s2)
5. s.swapcase() in Python

Swaps case of all alphabetic characters.


>>> s = "heLLo BuDdY"
>>> s2 = s.swapcase()
>>> print(s2)
6. s.count(<sub>[, <start>[, <end>]])

Returns the number of time <sub> occurs in s.


>>> s = 'Dread Thread Spread'
>>> s.count('e')
3
>>> s.count('rea')
3
>>> s.count('e', 4, 18)
2
>>>
7. s.find(<sub>[, <start>[, <end>]])

Returns the index of the first occurrence of <sub> in s. Returns -1 if the substring is


not present in the string.
>>> s = 'Dread Thread Spread'
>>> s.find('Thr')
6
>>> s.find('rea')
1
>>> s.find('rea', 4, 18)
8
>>> s.find('x')
-1
>>>

4. Explain about arrays with examples.


An array is defined as a collection of items that are stored at contiguous memory
locations. It is a container which can hold a fixed number of items, and these items
should be of the same type. An array is popular in most programming languages like
C/C++, JavaScript, etc.
Array is an idea of storing multiple items of the same type together and it makes easier
to calculate the position of each element by simply adding an offset to the base value.
A combination of the arrays could save a lot of time by reducing the overall size of the
code. It is used to store multiple values in single variable. If you have a list of items
that are stored in their corresponding variables like this:
car1 = "Lamborghini"
car2 = "Bugatti"
car3 = "Koenigsegg"
The array can be handled in Python by a module named array. It is useful when we have to
manipulate only specific data values. Following are the terms to understand the concept of an
array:
Element - Each item stored in an array is called an element.
Index - The location of an element in an array has a numerical index, which is used to
identify the position of the element.
Array Representation
An array can be declared in various ways and different languages. The important points that
should be considered are as follows:
o Index starts with 0.
o We can access each element via its index.
o The length of the array defines the capacity to store the elements.
Array operations
Some of the basic operations supported by an array are as follows:
o Traverse - It prints all the elements one by one.
o Insertion - It adds an element at the given index.
o Deletion - It deletes an element at the given index.
o Search - It searches an element using the given index or by the value.
o Update - It updates an element at the given index.
Accessing array elements
o To access the array elements using the respective indices of those elements.

import array as arr  
a = arr.array('i', [2, 4, 6, 8])  
print("First element:", a[0])  
print("Second element:", a[1])  
print("Second last element:", a[-1])  
To delete elements from an array
The elements can be deleted from an array using Python's del statement. If we want to
delete any value from the array, we can do that by using the indices of a particular
element.
import array as arr  
number = arr.array('i', [1, 2, 3, 3, 4])  
del number[2]                           # removing third element  
print(number)                           # Output: array('i', [1, 2, 3, 4])  

Finding the length of an array


The length of an array is defined as the number of elements present in an array. It
returns an integer value that is equal to the total number of the elements present in that
array.
Syntax
len(array_name) 
Array Concatenation
Concatenate any two arrays using the + symbol.
Example
a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8])  
b=arr.array('d',[3.7,8.6])  
c=arr.array('d')  
c=a+b  
print("Array c = ",c)  

5. Write a program to reverse and sort elements in an array.

#Initialize array     
arr = [1, 2, 3, 4, 5];     
print("Original array: ");    
for i in range(0, len(arr)):    
    print(arr[i]),     
print("Array in reverse order: ");    
#Loop through the array in reverse order    
for i in range(len(arr)-1, -1, -1):     
    print(arr[i]),     

Example

def solve(l):
rev = list(reversed(l))
print (rev)

srt = sorted(l)
print(srt)

l = [2,5,8,6,3,4,7,9]
solve(l)

Input
[2,5,8,6,3,4,7,9]
Output:
[9, 7, 4, 3, 6, 8, 5, 2] [2, 3, 4, 5, 6, 7, 8, 9]

You might also like