Author name: Prasanna

Python Interview Questions on Operators in Python

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

Python Interview Questions on Operators in Python

What are operators?
Operators are required to perform various operations on data. They are special symbols that are required to carry out arithmetic and logical operations. The values on which the operator operates are called operands.
So, if we say 10/5=2
Here 7’ is the operator that performs division and 10 and 5 are the operands. Python has the following operators defined for various operations:

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical/Boolean Operators
  4. Assignment Operators
  5. Bitwise Operators
  6. Membership Operators
  7. Identity Operators

Question 1.
What are Arithmetic Operators? What are various types of arithmetic operators that we can use in Python?
Answer:
Arithmetic operators are used to performing mathematical functions such as addition, subtraction, division, and multiplication. Various types of Arithmetic operators that we can use in Python are as follows:

‘+’for Addition

>>> a = 9
>>> b = 10
>>> a + b
19
>>>

‘-’ for Subtraction

>>> a = 9
>>>b = 10
>>> a - b
-1
>>>

‘*’ for Multiplication

>>> a = 9
>>> b = 10
>>> a * b
90
>>>

‘/’ for division

>>> a = 9
>>> b = 10
>>> a/b
0.9
>>>

“%’ for Modulus – provides the value of the remainder

>>> a = 9
>>> b = 10
>>> a % b
9
>>> a = 11
>>> b = 2
>>> a % b
1
>>>

‘//’ for Floor division – a division of operands, provides integer value of quotient. The value after decimal points is removed.

>>> a = 9
>>> b = 10
>>> a // b
0
>>> a = 11
>>> b = 2
>>> a // b
5
>>>

‘**’ for finding Exponential value

>>> a = 2
>>> b = 3
>>> a**b
8
>>>b**a
9
>>>

Question 2.
What is the Arithmetic operator’s precedence in Python?
Answer:
When more than one arithmetic operator appears in an expression the operations will execute in a specific order. In Python, the operation precedence follows as per the acronym PEMDAS.
Parenthesis
Exponent
Multiplication
Division
Addition
Subtraction
(2+2)/2-2*2/(2/2)*2
= 4/2 -4/1*2
= 2-8
= -6
>>> (2+2)/2-2*2/(2/2)*2
-6.0

Question 3.
a = 2, b =4, c = 5, d = 4 Evaluate the following keeping Python’s precedence of operators:

  1. a+b+c+d
  2. a+b*c+d 4
  3. a/b+c/d
  4. a+b*c+a/b+d

Answer:

>>> a=2
>>> b=4
>>> c=5
>>> d=4
>>> a+b+c+d
15
>>> a+b*c+d
26
>>> a/b+c/d
1.75
>>> a+b*c+a/b+d
26.5
>>>

Question 4.
What are relational operators?
Answer:
Relational operators are also known as conditional or comparison operators. Relational operators in Python are defined as follows:

  1. ==: returns true if two operands are equal
  2. !=: returns true if two operands are not equal
  3. >: returns true if the left operand is greater than the right operand
  4. <: returns true if the left operand is smaller than the right operand
  5. >=: returns true if the left operand is greater than or equal to the right operand
  6. <=: returns true if the left operand is smaller or equal to the right operand
>>> a = 5
>>> b = 6
>>> c = 7
>>> d = 7
>>> a == b
False
>>> c == d
True
>>> a ! = b
True
>>> c ! = d
False
>>>
>>> a > b
False
>>> a < b
True
>>> a>=b
False
>>> c>=d
True
>>> a<=b
True
>>> c<=d
True

Question 5.
a = 5, b = 6, c =7, d=7 What will be the outcome for the following:

  1. a<=b>=c
  2. -a+b==c>d
  3. b+c==6+d>=13

Answer:

>>> a<=b>=c
False
>>> -a+b==c>d
False
>>> b+c==6+d>=13
True
>>>

Question 6.
What are assignment operators?
Answer:
Assignment operators are used for assigning values to variables. Various types of assignment operators are as follows:

  1. =: a = 5 means that a is assigned value of 5
  2. += a += 5 is same as a = a+5
  3. -=: a -= 5 is same as a = a – 5
  4. *=. a *= 5 js same as a = a * 5
  5. /=: a /= 5 is same as a = a/5
  6. %=: a %=5 is same as a = a%5
  7. //=: x //= 5 is same as x= x//5
  8. **=• x **=5 js same as x = x**5
  9. &=: x &= 5 is same as x = x&5
  10. |=: x |= 5 is same as x = x|5
  11. A=: x A= 5 is same as x = xA5
  12. >>=: x >>= 5 is same as x = x>>5
  13. <<=: x <<= 5 is same as x = x<<5

Question 7.
Is a = a*2+6 same as a *= 2 + 6?
Answer:
No, a = a*2+6 is not same as a *= 2 + 6 this is because assign operator have lower precedence than the addition operator. So, if a = 5 then,
a = a *2+6 => a = 16
a *= 2 + 6 => a = 40

>>> a = 5
>>> a = a *2+6
>>> a
16
>>> a = 5
>>> a*= 2+6
>>> a
40
>>>

Question 8.
What are logical operators?
Answer:
Logical operators are generally used in control statements like if and while. They are used to control program flow. The logical operator evaluates a condition and returns “True” or “False” depending on whether the condition evaluates to True or False. Three logical operators in Python are as follows:

  • ‘and’
  • ‘or’ and
  • ‘not’
>>> a = True
>>> b = False
>>> a and b
False
>>> a or b
True
>>> not a
False
>>> not b
True
>>>

Question  9.
What are membership operators?
Answer:
The membership operators are used to check if a value exists in a sequence or not.
Two types of membership operators are as follows:

  1. in: returns true if a value is found in a sequence
  2. not in: returns true if a value is not found in a sequence
>>> a = "Hello World"
>>> "h" in a
False
>>> "h" not in a
True
>>> "H" not in a
False
>>>

Question 10.
What are bitwise operators?
Answer:
Bitwise operators work on bits and perform bit-by-bit operations. In Python, the following bit-wise operations are defined:
1. AND – &
2 & 3
2
2. OR-|
2|3
3
3. One’s complement – ~
>>> ~2
-3
4. XOR -∧
2∧3
1
5. Right shift ->>
2>>2
0
6. Left shift -<<
2<<2
8

Question 11.
What are identity operators?
Answer:
Identity operators are used to verifying whether two values are on the same part of the memory or not. There are two types of identity operators:

  1. is: return true if two operands are identical
  2. is not: returns true if two operands are not identical
>>> a = 3
>>> id(a)
140721094570896
>>> b = 3
>>> id (b)
140721094570896
>>> a is b
True
>>> a = 3
>>> b = 6
>>> c = b - a
>>> id(c)
140721094570896
>>> a is c
True
>>> a = 4
>>> b = 8
>>> a is b
False
>>> a is not b
True
>>>

Question 12.
What is the difference between a = 10 and a= = 10?
Answer:
The expression a = 10 assigns the value 10 to variable a, whereas a == 10 checks if the value of a is equal to 10 or not. If yes then it returns ‘Ti^te’ else it will return ‘False’.

Question 13.
What is an expression?
Answer:
A logical line of code that we write while programing, is called expressions. An expression can be broken into operator and operands. It is therefore said that an expression is a combination of one or more operands and zero or more operators that are together used to compute a value.
For example:
a = 6
a + b = 9
8/7

Question 14.
What are the basic rules of operator precedence in Python?
Answer:
The basic rule of operator precedence in Python is as follows:

  1. Expressions must be evaluated from left to right.
  2. Expressions of parenthesis are performed first.
  3. In Python the operation precedence follows as per the acronym PEMDAS:
  • Parenthesis
  • Exponent
  • Multiplication
  • Division
  • Addition
  • Subtraction

4. Mathematical operators are of higher precedence and the Boolean operators are of lower precedence. Hence, mathematical operations are performed before Boolean operations.

Question 15.
Arrange the following operators from high to low precedence:

  1. Assignment
  2. Exponent
  3. Addition and Subtraction
  4. Relational operators
  5. Equality operators
  6. Logical operators
  7. Multiplication, division, floor division, and modulus

Answer:
The precedence of operators from high to low is as follows:

  1. Exponent
  2. Multiplication, division, floor division, and modulus
  3. Addition and subtraction operators
  4. Relational operators
  5. Equality operators
  6. Assignment operators
  7. Logical Operators

Question 16.
Is it possible to change the order of evaluation in an expression?
Answer:
Yes, it is possible to change the order of evaluation of an expression. Suppose you want to perform addition before multiplication in an expression, then you can simply put the addition expression in parenthesis.
(2+4)*4

Question 17.
What is the difference between implicit expression and explicit expression?
Answer:
Conversion is the process of converting one data type into another. Two types of conversion in Python are as follows:

  1. Implicit type conversion
  2. Explicit type conversion

When Python automatically converts one data type to another it is called implicit conversion.

>>> a = 7
>>> type(a)
Cclass 'int'>
>>> b = 8.7
>>> type(b)
<class 'float'>
>>> type(a+b)
<class 'float' >
>>>

Explicit conversion is when the developer has to explicitly convert datatype of an object to carry out an operation.

>>> c = "12"
>>> type(c)
<class 'str'>
>>> d = 12
# addition of string and integer will generate error
>>> c+d
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module> c+d
TypeError: can only concatenate str (not "int") to str
# convert string to integer and then add
>>> int (c) +d 24
# convert integer to string and then perform concatenation
>>> c+str(d)
'1212'
>>>

Question 18.
What is a statement?
Answer:
A complete unit of code that a Python interpreter can execute is called a statement.

Question 19.
What is an input statement?
Answer:
The input statement is used to get user input from the keyboard. The syntax for input() function is as follows:
input(prompt)
The prompt is a strong message for the user.

>>> a = input ("Please enter your message here :")
Please enter your message here: It is a beautiful
day
>>> a
' It is a beautiful day'
>>>

Whenever an input function is called, the program comes on hold till an input is provided by the user. The input( ) function converts the user input to a string and then returns it to the calling program.

Question 20.
Look at the following code:

num1 = input ("Enter the first number: ")
num2 = input("Enter the second number: ")
print(num1 + num2)

When the code is executed the user provides the following values:
Enter the first number: 67 Enter the second number: 78 What would be the output?
Answer:
The output will be 6778. This is because the input() function converts the user input into a string and then returns it to the calling program. So, even though the users have entered integer values, the input() function has returned string values ‘67’ and ‘78’ and the ‘+’ operator concatenates the two strings giving ‘6778’ as the answer. To add the two numbers they must be first converted to an integer value. Hence, the code requires slight modification:

num1 = input ("Enter the first number: ")
num2 = input("Enter the second number: ")
print(int(num1) + int(num2))

Output:

Enter the first number: 67
Enter the second number: 78
145
>>>

Question 21.
What is the Associativity of Python Operators? What are non-associative operators?
Answer:
Associativity defines the order in which an expression will be evaluated if it has more than one operator having the same precedence. In such a case generally left to right associativity is followed.
Operators like assignment or comparison operators have no associativity and are known as Nonassociative operators.

Python Interview Questions on Operators in Python Read More »

Python Interview Questions on Data Types and Their in-built Functions

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

Python Interview Questions on Data Types and Their in-built Functions

Data types in Python

Numbers: int, float, and complex
List: Ordered sequence of items
tuple: Ordered sequence of items similar to list but is immutable
Strings: Sequence of characters
Set: an unordered collection of unique items
Dictionary: an unordered collection of key-value pair

Question 1.
Differentiate between mutable and immutable objects?
Answer:

Mutable ObjectsImmutable Objects
Can change their state or contentsCannot change their state or contents
Type: list, diet, setInbuilt types: int, float, bool, string, Unicode, tuple
Easy to changeQuick to access but making changes require the creation of a copy
Customized container like types are mostly mutablePrimitive like data types are immutable
  • Mutable objects are recommended when one has the requirement to change the size or content of the object
  • The exception to immutability: tup1es are immutable but may contain elements that are mutable

Question 2.
What is Variable in Python?
Answer:
Variables in Python are reserved memory locations that store values. Whenever a variable is created, some space is reserved in the memory. Based on the data type of a variable, the interpreter will allocate memory and decide what should be stored in the memory.

>>> a = 9 #assign value to a
>>> type(a) #check type of variable a
<class 'int'>
>>>

Question 3.
How can we assign the same value to multiple variables in one single go?
Answer:
The same value can be assigned to multiple variables in one single go as shown in the following code:

>>> a = b = c = "Hello World ! ! ! "
>>> a
' Hello World ! ! ! '
>>> b
' Hello World ! ! ! '
>>> c
' Hello World ! ! ! '
>>>

Numbers
Types of numbers supported are as follows:

  1. Signed integers int: these can be +ve or -ve and do not have any decimal point
  2. Long integers long: these are integers of unlimited size followed by capital or lowercase ‘L’
  3. Float: are real numbers with decimal points
  4. Complex numbers: have real and imaginary parts

Question 4.
What are the methods available for the conversion of numbers from one type to another?
Answer:
The following functions are available to convert numbers from one form to another.

# convert to integer
a = 87.8
print("a = ", a)
print ("****************")
#After conversion to integer
print("After conversion to integer value of a will be a = ", int(a))
print("*****************")
# convert to float
a = 87
print("a = ", a)
print("*****************")
#After conversion to float
print ("After conversion to float value of a will
be a = ", float (a) )
print("*****************")
# convert to complex
a = 87
print("a = ",a)
#After conversion to complex
print("After conversion to complex value of a will be = ", complex(a))
print("*****************")

Output

a = 87.8
*****************
After conversion to integer, the value of a will be a = 87
*****************
a = 87
*****************
After conversion to float value of a will be a = 87.0
a = 87
After conversion to complex value of a will be =
(87 + 0j)
*****************
>>>

Question 5.
What are the mathematical functions defined in Python to work with numbers?
Answer:
Mathematical functions are defined in the

import math
#ceiling value
a = -52.3
print ("math ceil for ",a, " is : " ceil(a))
print ("********************")
#exponential value
a = 2
print("exponential value for ", a , exp(2))
print ("********************")
#absolute value of x
a = -98.4
print ("absolute value of ",a," is: ", abs(a) )
print("********************")
#floor values
a = -98.4
print ("floor value for ",a," is: " print )
# log(x)
a = 10
print ("log value for ",a," is : ", math . floor (a))
print ("********************")
# log10(x)
a = 56
print ("log to the base 10 for ",a," is : ", math . log10(a))
print ("********************")
# to the power of
a = 2
b = 3
print (a," to the power of ",b," is : " , pow(2,3))
print ("********************")
# square root
a = 2
print("sqaure root")
print ("Square root of ",a," is : " , math . sqrt(25))
print("********************")

math module. You will have to import this module in order to work with these functions.

Output

math ceil for -52.3 is: -52
********************
exponential value for 2 is: 7.38905609893065
********************
the absolute value of -98.4 is: 98.4
********************
floor value for -98.4 is: -99
********************
log value for 10 is: 2.302585092994046
********************
log to the base 10 for 56 is :
1.7481880270062005
********************
2 to the power of 3 is: 8.0
********************
square root
The square root of 2 is: 5.0
********************

Question 6.
What are the functions available to work with random numbers?
Answer:
To work with random numbers you will have to import a random module. The following functions can be used:

import random
#Random choice
print (" Working with Random Choice")
seq=[8,3,5,2,1,90,45,23,12,54]
print ("select randomly from ", seq," : ", random, choice(seq))
print("*******************")
#randomly select f?om a range
print ("randomly generate a number between 1 and 10 : ", random.randrange(1, 10))
print("*******************")
#random( )
print ("randomly display a float value between 0 and 1 : ",random.random())
print("* * * * * *")
#shuffle elements of a list or a tup1e
seq= [1,32,14,65,6,75]
print ("shuffle ",seq,"to produce ", random,
shuffle (seq) )
#uniform function to generate a random float number between two numbers
print ("randomly display a float value between 65 and 71 : ", random.uniform(65,71))

Output

Working with Random Choice
select randomly from [8, 3, 5, 2, 1, 90, 45, 23, 12, 54] : 2
*******************
randomly generate a number between 1 and 10: 8
*******************
randomly display a float value between 0 and 1: 0.3339711273144338
* * * * * *
shuffle [1, 32, 14, 75, 65, 6] to produce: None
randomly display a float value between 65 and 71 :
65.9247420528493

Question 7.
What are the trigonometric functions defined in the math module?
Answer:
Some of the trigonometric functions defined in the

import math
# calculate arc tangent in radians
print ("atan(0) : ",math.atan(0))
print ("**************")
# cosine of x
print ("cos (90) : ", math.cos(0))
print("**************")
# calculate hypotenuse
print ("hypot(3,6) : ",math.hypot(3,6))
print ("**************")
# calculates sine of x
print ("sin(O) : ", math.sin(0))
print ("**************")
# calculates tangent of x
print ("tan(0) : ", math.tan(0))
print("**************")
# converts radians to degree
print ("degrees(0.45) : ", math.degrees(0.45))
print("**************")
# converts degrees to radians
print ("radians(0) : ", math.radians(0))

math module is as follows:

Question 8.
What are number data types in Python?
Answer:
Number data types are the one which is used to store numeric values such as:

  1. integer
  2. long
  3. float
  4. complex

Whenever you assign a number to a variable it becomes a numeric data type.

>>> a = 1
>>> b = -1
>>> c = 1 . 1
>>> type (a)
<class 'int'>
>>> type (b)
<class 'int'>
>>> type (c)
<class 'float'>

Question 9.
How will you convert float value 12.6 to integer value?
Answer:
Float value can be converted to an integer value by calling int() function.

>>> a = 12.6
>>> type(a)
<class 'float' >
>>> int(a)
12
>>>

Question 10.
How can we delete a reference to a variable?
Answer:
You can delete a reference to an object using the del keyword.

>>> a=5
>>> a 5
>>> del a
>>> a
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a
NameError: name 'a' is not defined
>>>

Question 11.
How will you convert real numbers to complex numbers?
Answer:
Real numbers can be converted to complex numbers as shown in the following code:

>>> a = 7
>>> b = -8
>>> x = complex(a,b)

>>> x.real
7.0
>>> x.imag
-8.0
>>>

Keywords, Identifiers, and Variables

Keywords

  • Keywords are also known as reserved words.
  • These words cannot be used as a name for any variable, class, or function.
  • Keywords are all in lower case letters.
  • Keywords form vocabulary in Python.
  • The total number of keywords in Python is 33.
  • Type help() in Python shell, a help> prompt will appear. Type keywords. This would display all the keywords for you. The list of keywords is highlighted for you.

Welcome to Python 3.7’s help utility?

If this is your first time using Python, you should definitely check: cut the tutorial on the Internet at https://docs.python.orgy 3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type “quit”.

To get a list of available modules, keywords, symbols, or topics, type “modules”, “keywords”, “symbols”, or “topics”. Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such 33 “spam”, type “modules spam”.

help> keywords

Here is a list of the python keywords, Enter any keyword to get more help.

Python Interview Questions on Data Types and Their in-built Functions chapter 2 img 1

help

Identifiers

  • Python Identifier is a name given to a variable, function, or class.
  • As the name suggests identifiers provide an identity to a variable, function, or class.
  • An identifier name can start with upper or lower case letters or an underscore followed by letters and digits.
  • An identifier name cannot start with a digit.
  • An identifier name can only contain letters, digits, and an underscore.
  • special characters such as @,%,! , #,$,’.’ cannot be a part of the identifier name.
  • As per naming convention, generally, the class name starts with a capital letter, and the rest of the identifiers in a program should start with lower case letters.
  • If an identifier starts with a single underscore then it is private and two leading underscores in front of an identifier’s name indicate that it is strongly private.
  • Avoid using an underscore as a leading or trailing character in an identifier because this notation is being followed for Python built-in types.
  • If an identifier also has two trailing underscores then it is a language-defined special name.
  • Though it is said that a Python identifier can be of unlimited length but having a name of more than 79 characters is a violation of the PEP-8 standard which asks to limit all lines to a maximum of 79 characters.
    You can check if an identifier is valid or not by calling iskeywords( ) function as shown in the following code:
>>> import keyword
>>> keyword.iskeyword("if")
True
>>> keyword.iskeyword("only")
False

Variables

  • Variables are nothing but a label to a memory location that holds a value.
  • As the name suggests, the value of a variable can change.
  • You need not declare a variable in Python but they must be initialized before use E.g, counter =0.
  • When we pass an instruction counter=0, it creates an object and a value 0 is assigned to it. If the counter variable already exists then it will be assigned a new value 0 and if it does not exist then it will get created.
  • By assigning a value we establish an association between a variable and an object.
  • counter=0 means that the variable counter refers to a value of ‘0’ in memory. If a new value is assigned to the counter then that means the

variable now refers to a new memory chunk and the old value was garbage collected.

>>> counter = 0
>>> id(counter)
140720960549680
>>> counter =10
>>> id(counter)
140720960550000
>>>

Question 12.
What are tokens?
Answer:
Tokens are the smallest units of the program in Python. There are four types of tokens in Python:

  • Keywords
  • Identifiers
  • Literals
  • Operators

Question 13.
What are constants?
Answer:
Constants (literals) are values that do not change while executing a program.

Question 14.
What would be the output for 2*4**2? Explain.
Answer:
The precedence of** is higher than the precedence of*. Thus, 4**2 will be computed first. The output value is 32 because 4**2 = 16 and 2*16 = 32.

Question 15.
What would be the output for the following expression:

print('{0:.4}'.format(7.0 / 3))

Answer:
2.333

Question 16.
What would be the output for the following expression?

print('(0:.4%}'.format(1 / 3))

Answer:
33.3333%

Question 17.
What would be the value of the following expressions?

  1. ~5
  2. ~~5
  3. ~~~5

Answer:
~x = -(x+1). Therefore the output for the given expressions would be as follows:

  1. -6
  2. 5
  3. -6

We will now have a look at the three most important sequence types in Python. All three represent a collection of values that are placed in order. These three types are as follows:

  1. String: immutable sequence of text characters. There is no special class for a single character in Python. A character can be considered as a String of text having a length of 1.
  2. List: Lists are very widely used in Python programming and a list represents a sequence of arbitrary objects. The list is mutable.
  3. tuple: tup1e is more or less like a list but it is immutable.

Strings

  • The sequence of characters.
  • Once defined cannot be changed or updated hence strings are immutable.
  • Methods such as replace( ), join( ), etc. can be used to modify a string variable. However, when we use these methods, the original string is not modified instead Python creates a copy of the string which is modified and returned.

Question 18.
How can String literals be defined?
Answer:
Strings can be created with single/double/triple quotes.

>>> a = "Hello World"
>>> b = 'Hi'
>>> type(a)
<class 'str'>
>>> type(b)
<class 'str' >
>>>
>>> c = """Once upon a time in a land far far away there lived a king"""
>>> type(c)
<class 'str'>
>>>

Question 19.
How can we perform concatenation of Strings?
Answer:
Concatenation of Strings can be performed using the following techniques:

1. + operator

>>> string1 = "Welcome"
>>> string2 = " to the world of Python!!!"
>>> string3 = string1 + string2
>>> string3
'Welcome to the world of Python!!!'
>>>

2. Join ( ) function

The join( ) function is used to return a string that has string elements joined by a separator. The syntax for using join( ) function, string_name.j oin(sequence)

>>> string1 = "-"
>>> sequence = ( "1","2","3","4")
>>> print(string1.joint(sequence))
1-2-3-4
>>>

3. % operator

>>> string1 = "HI"
>>> string2 = "THERE"
>>> string3 = "%s %s" %(string1, string2)
>>> string3 ,
'HI THERE'
>>>

4. format( ) function

>>> string1 = "HI"
>>> string2 ="THERE"
>>> string3 = "{ } { }" . format (string1, string2)
>>> string3
'HI THERE'
>>>

5. f-string

>>> string1 ="HI"
>>> string2 = "THREE"
>>> string3 = f ' { string1} {string2} '
>>> string3
'HI THERE'
>>>

Question 20.
How can you repeat strings in Python?
Answer:
Strings can be repeated either using the multiplication sign or by using for loop.

  • operator for repeating strings
>>> string1 = "Happy Birthday!!!"
>>> string1*3
'Happy Birthday!!!Happy Birthday!!!Happy Birthday!!!' *
>>>
  • for loop for string repetition
for x in range (0,3)

>>> for x in range(0,3):
print("HAPPY BIRTHDAY! ! !")

Question 21.
What would be the output for the following lines of code?

>>> string1 = "HAPPY "
>>> string2 = "BIRTHDAY!!!"
>>> (string1 + string2)*3

Answer:

'HAPPY BIRTHDAY!!!HAPPY BIRTHDAY!!!HAPPY BIRTHDAY!!!'

Question 22.
What is the simplest way of unpacking single characters from string “HAPPY”?
Answer:
This can be done as shown in the following code:

>>> string1 = "HAPPY"
>>> a,b,c,d,e = string1
>>> a
'H'
>>> b
'A'
>>> c
'P'
>>> d
'P'
>>> e
'Y'
>>>

Question 23.
Look at the following piece of code:

>>> string1 = "HAPPY"
>>> a,b = string1

What would be the outcome for this?
Answer:
This code will generate an error stating too many values to unpack because the number of variables does not match the number of characters in the strings.

Question 24.
How can you access the fourth character of the string “HAPPY”?
Answer:
You can access any character of a string by using Python’s array-like indexing syntax. The first item has an index of 0. Therefore, the index of the fourth item will be 3.

>>> string1 = "HAPPY"
>>> string1[3]
'P'

Question 25.
If you want to start counting the characters of the string from the rightmost end, what index value will you use (assuming that you don’t know the length of the string)?
Answer:
If the length of the string is not known we can still access the rightmost character of the string using the index of -1.

>>> string1 = "Hello World!!!"
>>> string1[-1]
' ! '
>>>

Question 26.
By mistake, the programmer has created string string1 having the value “HAPPU”. He wants to change the value of the last character. How can that be done?
Answer:
Strings are immutable which means that once they are created they cannot be modified. If you try to modify the string it will generate an error.

>>> string1 = "HAPPU"
>>> string1 [-1] = "Y"
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
string1[-1] = "Y”
TypeError: fstr* object does not support item assignment

However, there is a way out for this problem. We can use the replace( ) function.

>>> string1 = "HAPPU"
>>> string1.replace('U'Y')
'HAPPY'

Here, in the case of replace ( ) function, a new string is created and the value is reassigned to string1. So, string1 is not modified but is actually replaced.

Question 27.
Which character of the string will exist at index -2?
Answer:
Index of -2 will provide second last character of the string:

>>> string1 = "HAPPY"
>>> string1 [-1]
' Y'
>>> string1[-2]
'P'
>>>

Question 28.
>>> str1 = “\t\tHi\n”
>>> print(str1 .strip ( ))
What will be the output?
Answer:
Hi

Question 29.
Explain slicing in strings.
Answer:
Python allows you to extract a chunk of characters from a string if you know the position and size. All we need to do is to specify the start and endpoint. The following example shows how this can be done. In this case, we try to retrieve a chunk of the string starting at index 4 and ending at index 7. The character at index 7 is not included.

>>> string1 = "HAPPY-BIRTHDAY!!!"
>>> string1 [4:7]
'Y-B'
>>>

If in the above example you omit the first index, then the default value of 0 is considered and the slicing of text chunks starts from the beginning of the string.

>>> String1 = "HAPPY-BIRTHDAY! ! ! "
>>> string1 [:7]
'HAPPY-B'
>>>

Same way if you don’t mention the second index then the chunk will be taken from the starting position till the end of the string.

>>> string1 = "HAPPY-BIRTHDAY!!!"
>>> string1 [4:]
'Y-BIRTHDAY!!!'

Value of string1 [:n]+string1[n:] will always be the same string.

>>> string1 [:4]+ string1 [4:]
'HAPPY-BIRTHDAY!!!'

The negative index can also be used with slicing but in that case, the counting would begin from the end.

>>>string1 = "HAPPY-BIRTHDAY ! ! !"
>>> string1[-5:-1]
'AY!!' ! ”
>>>

You can also provide three index values:

>>> string1 [1:7:2]
'AP- '
>>> string1 [1: 9 : 3]
'AYI'
>>>

Here, the first index is the starting point, the second index is the ending point and the character is not included and the third index is the stride or how many characters you would skip before retrieving the next character.

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

>>> string1 = "HAPPY-BIRTHDAY!!!"
>>> string1[-1:-9:-2]
Answer:
‘!!AH’

Question 31.
How does the split( ) function work with strings?
Answer:
We can retrieve a chunk of string based on the delimiters that we provide. The split( ) operation returns the substrings without the delimiters.

Example

>>> string1 = "Happy Birthday"
>>> string1.split ( )
['Happy', 'Birthday' ]

Example

>>> time_string = "17:06:56"
>>> hr_str,min_str,sec_str = time_string. split (":")
>>> hr_str
'17'
>>> min_str
'06'
>>> sec_str
'56'
>>>

You can also specify, how many times you want to split the string.

>>> date_string = "MM-DD-YYYY"
>>> date_string.split("-" , 1)
['MM', 'DD-YYYY']
>>>

In case you want Python to look for delimiters from the end and then split the string then you can use the rsplit( ) method.

>>> date_string = "MM-DD-YYYY"
>>> date_string.split("-" , 1)
['MM-DD', 'YYYY']
>>>

Question 32.
What is the difference between the splif() and partltion( ) function?
Answer:
The result of a partition function is a tup1e and it retains the delimiter.

>>> date_string = "MM-DD-YYYY"
>>> date_string.partition("-" , 1)
('MM', ' - ' , 'DD-YYYY')

The partition ( ) function on the other hand looks for the delimiter from the other end.

>>> date_string = "MM-DD-YYYY"
>>> date_string.rpartition("-")
('MM-DD', '-', 'YYYY')
>>>

Question 33.
Name the important escape sequence in Python.
Answer:
Some of the important escape sequences in Python are as follows:

  • \\: Backslash
  • \’: Single quote
  • \”: Double quote •
  • \f: ASCII form feed
  • \n: ASCII linefeed
  • \t: ASCII tab
  • \v: Vertical tab

String Methods

capitalize ( )
Will return a string that has first alphabet capital and the rest are in lower case, ‘

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.capitalize ( )
'Happy birthday'
>>>

casefold( )

Removes case distinction in string. Often used for caseless matching. ‘

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.casefold()
'happy birthday'
>>>

centre( )

The function takes two arguments: (1) length of the string with padded characters (2) padding character (this parameter is optional)

>>> string1 = "HAPPY BIRTHDAY"
>>> new_string = string1.center(24)
>>> print("Centered String: ", new_string)
Centered String: HAPPY BIRTHDAY
> >>

count( )

Counts the number of times a substring repeats itself in the string.
>>> string1 = "HAPPY BIRTHDAY"
>>> string1.count("P")
2
>>>

You can also provide the start index and ending index within the string where the search ends.

encode( )

Allows you to encode Unicode strings to encodings supported by python.

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.encode( )
b'HAPPY BIRTHDAY'

By default, python uses utf-8 encoding.
It can take two parameters:
encoding – type a string has to be encoded to and
error- response when encoding fails

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.endswith('Y')
True
>>> string1.endswith('i')
False

endswith( )

It returns true if a string ends with the substring provided else it will return false.

>>> string1 = "to be or not to be"
>>> string1.endswith("not to be")
True
>>>

find( )

Get the index of the first occurrence of a substring in the given string.

>>> string1 = "to be or not to be"
>>> string1 .find ('be' )
3
>>>

format( )

The format function allows you to substitute multiple values in a string. With the help of positional formatting, we can insert values within a string. The string must contain {} braces, these braces work as a placeholder. This is where the values will be inserted. The format) the function will insert the values.

Example

 >>> print("Happy Birthday { }".format("Alex"))
Happy Birthday Alex

Example

>>> print("Happy Birthday { }, have a { } day!!", format("Alex","Great"))
Happy Birthday Alex, have a Great day ! !
>>>

 

Values that exist in the format( ) are tup1e data types. A value can be called by referring to its index value.

Example

>>> print("Happy Birthday {0}, have a {l} day!!", format("Alex","Great"))
Happy Birthday Alex, have a Great day!!
>>>

 

More types of data can be added to the code using {index: conversion} format where the index is the index number of the argument and conversion is the conversion code of data type.

s- string
d- decimal
f- float
c- character
b- binary
o- octal
x- hexadecimal with lower case letters after 9
X-hexadecimal with upper case letters after 9
e-exponent

Example

>>> print("I scored {0:.2f}% in my exams" . format(86))
I scored 86.00% in my exams,

index( )
It provides the position of the first occurrence of the substring in the given string.

>>> string1 = "to be or not to be"
>>> string1.index('not')
9
>>>

isalnum( )

It returns true if a string is alphanumeric else it returns false.

>>> string1 = "12321$%%^&*"
>>> string1.isalnum( )
False
>>> string1 = "string1"
>>> string1.isalnum()
True
>>>

isalpha( )

It returns true if the whole string has characters or returns false.

>>> string1.isalpha( )
False
>>> string1 = "tobeornottobe"
>>> string1.isalpha( )
True
>>>

isdeimal( )

Returns true if the string has all decimal characters.

>>> string1 = "874873"
>>> string1.isdecimal()
True

isdigit( )

Returns true if all the characters of a string are digits:

>>> string1 = "874a873"
>>> string1.isdigit()
False
>>>

islower( )

>>> string1 = "tIger"
>>> string1.islower()
False
>>>

isnumeric( )

Returns true if the string is not empty characters of a string are numeric.

>>> string1 = "45.6"
>>> string1.isnumeric()
False
>>>

isspace( )

Returns true if the string only has space.

>>> string1 =" "
>>> string1.isspace()
True
>>>

lower( )

Converts upper case letters to lower case.

>>> string1 ="TIGER"
>>> string1.lower()
'tiger'
>>>

swapcase( )

Changes lower case letters in a string to upper case and vice-versa.

>>> string1 = "tiger"
>>> string1 = "tiger".swapcase()
>>> string1
'TiGER'
>>>

Question 34.
What are execution or escape sequence characters?
Answer:
Characters such as alphabets, numbers, or special characters can be printed easily. However, whitespaces such as line feed, tab, etc. cannot be displayed like other characters. In order to embed these characters, we have used execution characters. These characters start with a backslash character (\) followed by a character as shown in the following code:

1. \n stands for the end of the line.
>>> print(“Happy \nBirthday”)
Happy
Birthday
2. \\ prints backslash – ‘V
. >>> print(‘\\’)
\
3. \t prints a tab
>>> print(“Happy\tBirthday”)
Happy Birthday

Lists

  • • Lists are ordered and changeable collections of elements.
  • • Can be created by placing all elements inside a square bracket.
  • • All elements inside the list must be separated by a comma
  • • It can have any number of elements and the elements need not be of the same type.
  • • If a list is a referential structure which means that it actually stores references to the elements.
  • Lists are zero-indexed so if the length of a string is “n” then the first element will have an index of 0 and the last element will have an index of n-1.
  • Lists are widely used in Python programming.
  • Lists are mutable therefore they can be modified after creation.

Question 35.
What is a list?
Answer:
A list is an in-built Python data structure that can be changed. It is an ordered sequence of elements and every element inside the list may also be called an item. By ordered sequence, it is meant that every element of the list can be called individually by its index number. The elements of a list are enclosed in square brackets[ ].

>>> # Create empty list
>>> list1 = [ ] 
>>> # create a list with few elements
>>> list 2 = [12, "apple" , 90.6,]
>>> list1
[ ] 
>>>list2
[12 , 'apple' , 90.6]
>>>

Question 36.
How would you access the 3rd element of the following list?

list1= ["h","e","1","p"]

What would happen when you try to access list1 [4]?
Answer:
The third element of list1 will have an index of 2. Therefore, we can access it in the following manner:

>>> list1 = ["h","e","1","p"]
>>> list1 [2]
'1'
>>>

There are four elements in the list. Therefore, the last element has an index of 3. There is no element at index 4. On trying to access list1 [4] you will get an “IndexError: list index out of range”

Question 37.
list1 = [”h”,”e”,”I”,”p”]. What would be the output for list1 [-2] and list1 [-5]?
Answer:
list1 [-2] = T
list1 [-5] will generate IndexError: list index out of range
Similar to Strings, the slice operator can also be used on the list. So, if the range given is [a:b]. It would mean that all elements from index a to index b will be returned. [a:b:c] would mean all the elements from index a to index b, with stride c.

Question 38.
list1 = [“l”,”L”,”O”,”V”,”E”,”p”,”Y”,”T”,”H”,”O”,”N”]
What would be the value for the following?

  1. list1 [5]
  2. list1 [-5]
  3. list1 [3:6]
  4. list1 [:-3]
  5. list1[-3:]
  6. list1 [:]
  7. list1 [1:8:2]
  8. list1 [::2]
  9. list1[4::3]

Answer:

>>> list1 = ["I","L","O","V","E","p","Y","T","H","O","N"]
>>> list1 [5]
'p'
>>> list1 [-5]
'Y'
>>> list1 [3:6]
['V' , 'E' , 'P']
>>> list1 [:-3]
['I' , 'L' , 'O' ,'V' , 'E' , 'P' , 'Y' , 'T']
>>> list1 [-3:]
['H' , 'O' , 'N']
>>> list1 [:]
['I' , 'L' , 'O' ,'V' , 'E' , 'P' , 'Y' , 'T' , 'H' , 'O' , 'N' ]
>>> list1 [1:8:2]
['L' ,'V' , 'P' , 'T' ,]
>>> list1[: :2]
['I' , 'O' , 'E' , 'Y' , 'H' , 'N']
>>> list1 [4 : :3]
['E' , 'T' , 'N']
>>>

Question 39.
list1 = [“I”,”L”,”O”,”V”,”E”,”p”,”Y”,”T”,”H”,”O”,”N”]
list2 = [‘O’,’N’,’L’ , ‘Y’]
Concatenate the two strings.
Answer:

>>> list1 = list1+list2
>>> list1
['I' list1 , 'L' 'O' 'V' 'E' , 'P' , 'Y' , 'T' , 'H' , 'O' , 'N' , 'O' , 'N' , 'L' , 'Y' ]
>>>

Question 40.
How can you change or update the value of the element in a list?
Answer:
You can change the value of an element with the help of the assignment operator (=).

>>> list1 = [1,2,78,45,93,56,34,23,12,98,70]
>>> list1 = [1,2,78,45,93,56,34,23,12,98,70]
>>> list1 [3]
45
>>> list1[3]=67
>>> list1 [3]
67
>>> list1
[1,2,78,45,93,56,34,23,12,98,70]
>>>

Question 41.
list1 =[1,2,78,45,93,56,34,23,12,98,70]
list1[6:9]=[2,2,2]
What is the new value of list1?
Answer:
[1,2, 78, 45, 93, 56, 2, 2, 2, 98, 70]

Question 42.
What is the difference between append( ) and extend( ) function for lists?
Answer:
The append( ) function allows you to add one element to a list whereas extending ( ) allows you to add more than one element to the list.

>>> list1 = [1,2, 78,45,93,56,34,23,12,98,70]
>>> list1.append(65)
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]

>>> list1.extend([-3,- 5, - 7 , -5] )
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65, -3, -5, -7, -5]
>>>

Question 43.
list1 = [“h”,”e”,”l”,”p”]
What would be the value of list1 *2?
Answer:
[‘h’, ‘e’, T, ‘p’, ‘h’, ‘e’, ‘l’ , ‘p’]

Question 44.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
list1 +=[87]
What is the value of list1?
Answer:
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65, 87]

Question 45.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
list1 -=[65]
What will be the output?
Answer:
The output will be TypeError: unsupported operand type(s) for -=: ‘list’ and ‘list’

Question 46.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
How will you delete second element from the list?
Answer:
An element can be deleted from a list using the ‘del’ keyword.

>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> del(list1 [1])
>>> list1
[1, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>

Question 47.
list1 = [[1,4,5,9],[2,4,7,8,1]]
list1 has two elements, both are lists.
How will you delete the first element of the second list contained in the list1?
Answer:

>>> list1 = [ [1,4,5,9] , [2,4,7,8, 1] ]
>>> del(list1[1][0])
>>> list1
[[1, 4, 5, 9] , [4, 7, 8, 1] ]
>>>

Question 48.
How would you find the length of o list?
Answer:
The len( ) function is used to find the length of a string.

>>> list1 = [1, 2, ‘78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> len(list1)
12
>>>

Question 49.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Insert a value 86 at 5th position.
Answer:

>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>list1 . insert (4, 86)
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>

Question 50.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Remove the value 78 from list1.
Answer:
A specific element can be removed from a list by providing the value to remove( ) function.

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . remove (78)
>>> list1
[1,2,45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>

Question 51.
What does the pop( ) function do?
Answer:
The pop( ) function can be used to remove an element from a particular index and if no index value is provided, it will remove the last element. The function returns the value of the element removed.

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . pop(3)
45
>>> list1
[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . pop( )
65
>>> list1
[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70]
>>>

Question 52.
Is there a method to clear the contents of a list?
Answer:
Contents of a list can be cleared using the clear( ) function.

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . clear ( )
>>> list1
[ ]
>>>

Question 53.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Find the index of element having value 93.
Answer:
We can find the index of a value using the index( ) function.

>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1.index(93)
4
>>>

Question 54.
Write code to sort list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65].
Answer:
We can sort a list using sort( ) function.

>>> list1 = [1,2,78,45,93,56,34,23,12,98,70,65]
>>> list1 . sort ( )
>>> list1
[1,2,12,23,34,45,56,65,70,78,93,98]
>>>

Question 55.
Reverse elements of list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65].
Answer:

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . reverse ( )
>>> list1
[65,70,98,12,23,34,56,93,45,78,2,1]
>>>

Question 56.
How can we check if an element exists in a list or not?
Answer:
We can check if an element exists in a list or not by using ‘in’ keyword:

>>> list1 = [(1,2,4) , [18,5,4,6,2] , [4,6,5,7], 9, 23, [98, 56] ]
>>> 6 in list1
False
>>> member = [4,6,5,7]
>>> member in list1
True
>>>

tuples

  • tuples are sequences just like lists but are immutable.
  • Cannot be modified.
  • tuples may or may not be delimited by parenthesis ( ).
  • Elements in a tup1e are separated by a comma. If a tuple has only one element then a comma must be placed after that element. Without a trailing comma, a single value in simple parenthesis would not be considered as a tuple.
  • Both tup1es and lists can be used under the same situations.

Question 57.
When would you prefer to use a tup1e or a list?
Answer:
tup1es and lists can be used for similar situations but tup1es are generally preferred for the collection of heterogeneous data types whereas lists are considered for homogeneous data types. Iterating through a tup1e is faster than iterating through a list. tup1es are ideal for storing values that you don’t want to change. Since tup1es are immutable, the values within are write-protected.

Question 58.
How can you create a tup1e?
Answer:
A tup1e can be created in any of the following ways:

>>> tup1 =( )
>>> tup2=(4 , )
>>> tup3 = 9,8,6,5
>>> tup4= (7,9,5,4,3).
>>> type(tup1)
<class ' tup1e' >
>>> type(tup2)
<class 'tup1e'>
>>> type(tup3)
<class ' tup1e' >
>>> type(tup4)
<class 'tup1e'>

However, as mentioned before, the following is not a case of a tup1e:

>>> tup5 = (0)
>>> type(tup5)
1cclass 'int'>
>>>

Question 59.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
How would you retrieve the 7th element of this tup1e?
Answer:
Accessing an element of a tup1e is the same as accessing an element of a list.

>>> tup1 = (1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
>>> tup1 [6]
34
>>>

Question 60.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What would happen when we pass an instruction tup1[6]=6?
Answer:
A tup1e is immutable hence tup1 [6]=6 would generate an error.

Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
tup1[6]=6
TypeError: 'tup1e' object does not support item
assignment
>>>

Question 61.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What would happen if we try to access the 6th element using tup1 [5.0]?
Answer:
The index value should always be an integer value and not afloat. This would generate a type error. TypeError: ‘tup1e’ object does not support item assignment.

Question 62.
tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
What would be the value of tup1 [1 ][0]?
Answer:
8

Question 63.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What is the value of tup1 [-7] and tup1 [-15]?
Answer:

>>> tup1[-7]
56
>>> tup1[-15]
Traceback (most recent call last) :
File "<pyshell#2>", line 1, in <module> tup1 [-15]
IndexError: tup1e index out of range
>>>

Question 64.
tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
tup2 = (1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
Find the value of:

  1. tup1[2:9]
  2. tup2[:-l]
  3. tup2[-l:]
  4. tup1[3:9:2]
  5. tup2[3:9:2]

Answer:
1. tup1 [2:9]
((4, 6, 5, 7), 9, 23, [98, 56])
2. tup2[:-l]
(1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70)
3. tup2[-l:]
(65,)
4. tup1[3:9:2]
(9, [98, 56])
5. tup2[3:9:2]
(45, 56, 23)

Question 65.
tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
What will happen if tup1[l][0]=18 instruction is passed? What would happen if we pass an instruction tup1 [l].append(2)?
Answer:
tup 1 [ 1 ] is a list object and the list is mutable.
a tuple is immutable but if an element of a tup1e is mutable then its nested elements can be changed.

>>> tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
>>> tup1 [1] [0] = 18
>>> tup1 [1]
[18 , 5, 4, 6 ]
>>> tup1 [1] . append (2)
>>> tup1
((1,2,4) , [8,5,4,6],(4,6,5,7),9,23,[98,56] , 1,2,78,45, 93,56,34,23,12,98,70,65)
>>>

Question 66.
tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
tup2 =(1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What would be the output for tup1+tup2?
Answer:

>>> tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
>>> tup2 = (1,2,78,45,93,56,34,23,12,98,70,65)
>>> tup1+tup2
>>> tup1
( (1,2,4) , [18,5,4,6,2] , (4,6,57), 9,23,[98,56], 1,2,78,45, 93, 56, 34,23,12,98,70,65)
>>>

Question 67.
How can we delete a tup1e?
Answer:
A tup1e can be deleted using del command.

>>> tup1 = (1,2,4), [8,5,4,61 , (4,6,5,7) ,9,23, [98,56]
>>> del tup1
>>> tup1
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
tup1
NameError: name 'tup1' is not defined
>>>

Question 68.
tup1 = ((1, 2, 4), [18, 5, 4, 6, 2], (4, 6, 5, 7), 9, 23, [98, 56])
tup2 = 1,6,5,3,6,4,8,30,3,5,6,45,98
What is the value of:

  1. tup1.count(6)
  2. tup2.count(6)
  3. tup1.index(6)
  4. tup2.index(6)?

Answer:
1. tup1.count(6)
0
2. tup2.count(6)
3
3. tup1.index(6)
0
4. tup2.index(6)
1

Question 69.
How can we test if an element exists in a tup1e or not?
Answer:
We can check if an element exists in a tup1e or not by using in a keyword:

>>> tup1 = ((1, 2, 4), [18, 5, 4, 6, 2], (4, 6, 5, 7) , 9, 23, [98, 56] )
>>> 6 in tup1
False
>>> member = [4,6,5,7]
>>> member in tup1
False
>>> member2 = (4, 6, 5, 7)
>>> member2 in tup1
True
>>>

Question 70.
How can we get the largest and the smallest value in tup1e?
Answer:
We can use max( ) function to get the largest value and min() function to get the smallest value.

>>> tup1 = (4, 6, 5, 7)
>>> max(tup1)
7
>>> min(tup1)
1 4
>> >

Question 71.
How to sort all the elements of a tup1e?
Answer:

>>> tup1 =(1,5,3,7,2,6,8,9,5,0,3,4,6,8)
>>> sorted(tup1)
[0, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9]

Question 72.
How can we find the sum of all the elements in a tup1e?
Answer:
We can find some of all elements by using the sum( ) function.

>>> tup1 =(1,5,3,7,2,6,8,9,5,0,3,4,6,8)
>>> sum(tup1)
67

Enumerate function for tup1e and list in for loop section mentioned.

Dictionary

  • Unordered sets of objects.
  • Also known as maps, hashmaps, lookup tables, or associative array.
  • Data exists in key-value pair. Elements in a dictionary have a key and a corresponding value. The key and the value are separated from each other with a colon’: ’ and all elements are separated by a comma.
  • Elements of a dictionary are accessed by the “key” and not by index. Hence it is more or less like an associative array where every key is associated with a value .and elements exist in an unordered fashion as key-value pair.
  • Dictionary literals use curly brackets ‘ { } ’.

Question 73.
How can we create a dictionary object?
Answer:
A dictionary object can be created in any of the following ways:

>>> dictl = { }
>>> type(dict1)
<class 'dict'>

>>> dict2 = {'key1' :'value1', 'key2': 'value2', 'key3': 'value3', ' key4': ' value4'}
>>> dict2
{'key1': 'value1', 'key2': 'value2', 'key3' : 'value3', 'key4': 'value4' }
>>> type(dict2)
<class 'diet'>

>>> dict3 = diet({'key1': 'value1', 'key2':' value2', 'key3': 'value3', ' key4 ':' value4' })
>>> dict3
{'key1': 'value1', 'key2' : 'value2', 'key3': 'value3', 'key4':'value4'}
>>> type(dict3)
<class 'diet'>

>>> dict4 = diet(f('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3 ' ), ('key4','value4')])
>>> dict4 {'key1': 'value1' 'key2' : 'value2', 'key3': 'value3', 'key4':' value4'}
>>> type(dict4)
<class 'diet'>

Question 74.
How can you access the values of a dictionary?
Answer:
Values of a dictionary can be accessed by the help of the keys as shown in the following code:

>>> student_dict = {'name':'Mimoy', 'Age':12, 'Grade' :7, 'id' :'7102' }
>>> student_dict['name']
'Mimoy'

Keys are case-sensitive. If you give student diet [‘age’] instruction a key Error will be generated because the key actually has capital A in Age. The actual key is Age and not age.

>>> student_dict['age' ]
Traceback (most recent call last) -.
File "<pyshell#20>", line 1, in <module>
student_dict['age']
KeyError: 'age'
>>> student_dict['Age']
12
>>>

Question 75.
Can we change the value of an element of a dictionary?
Answer:
Yes, we can change the value of an element of a dictionary because dictionaries are mutable.

>>> dict1 = {'English literature':'67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'} .
>>> dict1['English literature'] = '78%'
>>> dict1
{'English literature': '78%', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%' }
>>>

Question 76.
Can a dictionary have a list as a key or a value?
Answer:
A dictionary can have a list as a value but not as a key.

>>> dict1 = {'English literature':'67%','Maths':'78% ','Social Science':'87%','Environmental Studies': 97%' }
>>> dictl['English literature' >>> dict1] = ['67% ,'78%']
{'English literature': ['67%', '78%'], Maths': '78%', 'Social Science': '87%' , 'Environmental Studies' : '97%' }
>>>

If you try to have a list as a key then an error will be generated:

>>> dict1 = {['67%', '78%']:'English literature', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%'}
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
dict1 = {['67%', '78%']:'English literature',
'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%'}
TypeError: unhashable type: 'list'
>>>

Question 77.
How are elements deleted or removed from a dictionary?
Answer:
Elements can be deleted or removed from a dictionary in any of the following ways:

>>> dict1 = {‘English literature’:’67%YMaths’:’78%’, ’Social Science’: ’ 87%’, ’Environmental Studies ’: ’ 97% ’}

I. The pop( ) can be used to remove a particular value from a dictionary. pop( ) requires a valid key-value as an argument or you will receive a key error. If you don’t pass any argument then you will receive a type error: “TypeError: descriptor ‘pop’ of ‘diet’ object needs an argument”

>>> dict1.pop('Maths' )
'78%'
>>> dict1
{'English literature' '67%', 'Social Science': '87%', 'Environmental Studies' : '97%'}

II. The pop item( ) can be used to remove any arbitrary item.

>>> dict1.popitem( )
('Environmental Studies', '97%')
>>> dict1
{'English literature': '67%', 'Social Science': '87%' }

III. Yod can delete a particular value from a dictionary using the ‘del’ keyword.

>>> del dict1['Social Science']
>>> dict1
{'English literature': '67%'}

IV. clear( ) function can be used to clear the contents of a dictionary.

>>> dict1.clear( )
>>> dict1
{ }

V. The del( ) function can also be used to delete the whole dictionary after which if you try to access the dictionary object, a Name Error will be generated as shown in the following code:

>>> del dict1
>>> dict1
Traceback (most recent call last):
File "<pyshell#ll>" , line 1, in <module>
dict1
NameError: name 'dict1' is not defined
>>>

Question 78.
What is the copy( ) method used for?
Answer:
A copy method creates a shallow copy of a dictionary and it does not modify the original dictionary object in any way.

>>> dict2 = dict1.copy()
>>> dict2
{'English literature': '67%', 'Maths': ' 78%', 'Social Science': '87%','Environmental Studies': ' 97%'}
>>>

Question 79.
Explain from Keys( ) method.
Answer:
The from keys( ) method returns a new dictionary that will have the same keys as the dictionary object passed as the argument. If you provide a value then all keys will be set to that value or else all keys will be set to ‘None.

I. Providing no value
>>> dict2 = diet.fromkeys(dict1)
>>> dict2
{‘English literature’: None, ‘Maths’: None, ‘Social Science’ : None, ‘Environmental Studies’ : None}
>>>

II. Providing a value
>>> dict3 = diet.fromkeys(dictl,’90%’)
>>> dict3
{‘English literature’: ‘90%’, ‘Maths’: ‘90%’,
‘Social Science’: ‘90%’, ‘Environmental Studies’: ‘90%’ }
>>>

Question 80.
What is the purpose of items( ) function?
Answer:
The items( ) function does not take any parameters. It returns a view object that shows the given dictionary’s key-value pairs.

>>> dict1 = {'English literature':'67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'}
>>> dictl.items()
dict_items([('English literature', '67%'),
('Maths', '78%'), ('Social Science', '87%'), ('Environmental Studies', '97%')])
>>>

Question 81.
dict1 = {(1,2,3):[‘1’,’2’,’3’]}
Is the instruction provided above, a valid command?
Answer:
dict1 = {(l,2,3):[‘r,’2’,’3’]} is a valid command. This instruction will create a dictionary object. In a dictionary, the key must always have an immutable value. Since the key is a tup1e which is immutable, this instruction is valid.

Question 82.
dict_items([(‘English literature’, ‘67%’), (‘Maths’, ‘78%’), (‘Social Science’, ‘87%’), (‘Environmental Studies’, ‘97%’)]).
Which function can be used to find the total number of key-value pairs in dict1?
Answer:
The len( ) function can be used to find the total number of key-value pairs.

>>> dictl = {'English literature' :' 67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'}
>>> len(dict1)
4
>>>

Question 83.
dict1 = {‘English literature’:’67%’,’ Maths’:’78%’,’ Social Science’:’87%’,’ Environmental Studies’:’97%’}
dict1 .keys( )
What would be the output?
Answer:
The keys( ) function is used to display a list of keys present in the given dictionary object.

>>> dict1 = {'English literature':'67%','Maths':'78%','Social Science' :'87%','Environmental Studies' :'97%'}
>>> dictl.keys( )
dict_keys(['English literature', 'Maths', 'Social Science', 'Environmental Studies'])
>>>

Question 84.
dict1 = {‘English literature’:’67%’,’ Maths’:’78%’,’ Social Science’:’87%’,’ Environmental Studies’:’97%’}
‘Maths’ in dict1
What would be the output?
Answer:
True

The ‘in’ operator is used to check if a particular key exists in the diet or not. If the key exists then it returns ‘True’ else it will return ‘False’.

Question 85.
dict1 = {‘English literature’:’67%’,’Maths’:’78%’,’Social Science’:’87%’,’Environmental Studies’:’97%’}
dict2 = {(1,2,3):[‘1’,’2’,’3’]}
dict3 = {‘Maths’: ‘78%’}
dict4= {‘Maths’: ‘98%’,’Biology’:’56%’}
What would be the output of the following:

  1. dict1.update(dict2)
  2. dict2={(l,2,3):[‘l\’2Y3’]}
  3. dict3 ,update(dict3)
  4. dict1.update(dict4)

Answer:
The update( ) method takes a dictionary object as an argument. If the keys already exist in the dictionary then the values are updated and if the key does not exist then the key-value pair is added to the dictionary.

>>> dict1 = { 'English literature':'67%','Maths':'78%','Social Science' :'87%','Environmental Studies' :'97%'}
>>> dict2 = { (1,2,3) : [ '1' , ' 2' , ' 3' ] }
>>> dict1.update(dict2)
>>> dict1
{'English literature': '67%', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%' , (1, 2, 3) : ['1' , '2' , '3' ] }
dict1 = {'English literature':'67%','Maths':'78%','Social Science' :'87%','Environmental Studies' :'97%'}
>>> dict3 = { 'Maths' : '78%' }
>>> dict1 .update (dict3)
>>> dict1
{'English literature': '67%', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%' }
dict3 = {'Maths' : '78%' }
>>> dict3.update(dict3)
>>> dict3 {'Maths' : '78%' }
dict1 = {'English
literature':'67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'} dict4 = {'Maths': '98%','Biology':'56%'}
dictl.update(dict4) dictl
{'English literature' '67%', 'Maths': '98%',
'Social Science': '87%', 'Environmental Studies':
'97%.', 'Biology': '56%'}

Question 86.
dictl = {‘English literature’:’67%\’Maths’:78%\’Social Science’:’87%’,‘Environmental Studies’:’97%’}
dictl.values( )
What will be the output?
Answer:

>>> dictl.values( )
diet values (['67%', ' 78%' ' 87%' '97%'])
>>>

Sets

  • An unordered collection of items
  • Every element is unique and immutable
  • Set itself is mutable
  • Used for performing set operations in Math
  • Can be created by placing all the items in curly brackets {}, separated by ‘ , ‘
  • Set can also be created using the inbuilt set() function
>>> set1 ={8,9,10}
>>> set1
{8, 9, 10}
>>>
  • Since sets are unordered, indexing does not work for it

Question 87.
How can we create an empty set?
Answer:
The inbuilt function set( ) is used to create an empty set. Empty curly braces cannot be used for this task as it will create an empty dictionary object.

Question 88.
How can we add a single element to a set?
Answer:
We can add a single element with the help of add() function.

>>> set1 ={12,34,43,2}
>>> set1 . add(32)
>>> set1
(32, 2, 34, 43, 12}
>>>

Question 89.
How can we add multiple values to a set?
Answer:
Multiple values can be added using update( ) function.

>>> set1 ={12,34,43,2}
>>> set1.update( [76,84,14,56])
>>> set1
{2, 34, 43, 12, 76, 14, 84, 56}
>>>

Question 90.
What methods are used to remove value from sets?
Answer:
(1) discard( )
(2) remove ( )

Question 91.
What is the purpose of pop() method?
Answer:
The pop( ) function randomly removes an element from a set.

Question 92.
How can we remove all elements from a set?
Answer:
All elements from a set can be removed using the

>>> set1 = {2, 34, 43, 12, 76, 14, 84, 56}
>>> set1.clear( )
>>> set1
set ( )

Question 93.
What are various set operations?
Answer:

>>> #Union of two sets
>>> setl = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> setl | set2
{1, 3, 4, 5, 6, 7, 10, 12, 15}
>>> #Intersection of two sets
>>> set1 = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> setl & set2 {10, 3, 7}
>>> #Set difference
>>> setl = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> setl - set2
{1, 4, 5, 6} .
>>> #Set symmetric difference
>>> setl = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> set1∧set2
{1, 4, 5, 6, 12, 15}
>>>

Python Data Types

Question 94.
What are some of the built-in data types available in Python?
Answer:

  • Integer,
  • float,
  • long integer,
  • octal integer,
  • hexadecimal integer,
  • complex,
  • string,
  • list,
  • dictionary,
  • tuple,
  • file.

Question 95.
What is the difference between a tuple and a list?
Answer:
A tuple is immutable, it cannot be added to, rearranged, nor have items removed. It is faster to access and use than a list but it cannot be manipulated.

Question 96.
What are some of the specialized container types that are new in Python since 2.4?
Answer:
Namedtuple( ), deque, Counter, OrderedDict and defaultdict.

Question 97.
Illustrate defining a list.
Answer:
myList = [1, 2, “three”, 4] or myList = [ “I”, “Love”, “Python”] etc.

Question 98.
Write a code fragment that illustrates accessing a list by index.
Answer:
mylndex = 0
while mylndex < len(myList): print mylndex, ‘, myListlmylndex] mylndex++

Question 99.
What exception is raised when a negative index is used to access a list?
Answer:
Tricky question: Negative indexes are allowed in Python, it accesses the list from the bottom rather than the top. An index of -1 accesses the last item in the list, -2 the second to last, and so on.

Question 100.
Can a list contain other lists?
Answer:
Yes. A list can contain objects of any type.

Question 101.
How is a sublist accessed?
Answer:
The form is listname[listindex][sublistindex]. For example, myList[0][5] would retrieve the fifth item from the first sublist in myList.

Question 102.
How is a list sliced? Provide an example.
Answer:
By using the start, colon, end syntax. myList[5:10] This would return a list containing the 6th through 11th items in my list.

Question 103.
How would you add an item to an unsorted list?
Answer:
Using the append method. myList.append(theNexuItem)

Question 104.
How would you add an item to a sorted list in a specific position?
Answer:
Using the list insert method. myList.insert(index, theNewItem)

Question 105.
How would you remove an item from the list, if you know its index?
Answer:
Using the .pop list method. myList.pop(2) would remove the third item in my list.

Question 106.
How would you combine one list with another?
Answer:
Using the extend list method. myList.extend(theOtherList)

question 107.
How would you alphabetize a simple list of strings?
Answer:
Using the built-in sort method. myList.sort( )

Question 108.
How is a tuple created?
Answer:
myTuple = (“First item”, “Second Item”)

Question 109.
How is a tuple converted to a list, and a list to a tuple?
Answer:
Using the built-in functions list and tuple. myTuple = tuple(myList) and myList = list(myTuple) a

Question 110.
What is a dictionary and how is it constructed?
Answer:
A dictionary is a list containing name / value pairs.
myDict = {firstKey: firstValue, secondKey : secondValue } a

Question 111.
How is dictionary value retrieved?
Answer:
The usual method is to specify the key value in brackets. myDict[myKey] will return the value associated with myKey in the dictionary.

Question 112.
How are values added to a dictionary? Illustrate with an example.
Answer:
By creating a new key, and assigning a value to it.
myDict[myNewKey] = myNewValue

Question 113.
Can a dictionary contain lists or other dictionaries?
Answer:
Yes. The values assigned in a dictionary can be any valid Python object.

Python Interview Questions on Data Types and Their in-built Functions Read More »

Python Interview Questions on Introduction to Python

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

Python Interview Questions on Introduction to Python

Python

  • Python is a very popular programming language. It is known for being an interactive and object-oriented programming language.
  • Free software, an open-source language with a huge number of volunteers who are working hard to improve it. This is the main reason why the language is current with the newest trends.
  • It has several libraries which help build powerful code in a short span of time.
  • It is a very simple, powerful, and general-purpose computer programming language.
  • Python is easy to leam and easy to implement.
  • Well-known corporations are using Python to build their site. Some of the wells know websites built-in Python are as follows:
  1. Google
  2. Quora
  3. Yahoo!
  4. Instagram
  5. Survey Monkey
  6. You Tube
  7. Dropbox
  8. Reddit
  9. Spotify
  10. Bitly
  • The main reason for the popularity of the Python programming language is the simplicity of the code.
  • You require no skills to leam Python.

Question 1.
What can you do with python?
Answer:
There is no limit to what can be achieved with the help of Python Programming:

  • Python can be used for small or large, online or offline applications.
  • Developers can code using fewer lines of code compared to other languages.
  • Python is widely used for developing web applications as it has a dynamic system and automatic memory management is one of its strongest points.
  • Some of the very well-known Python frameworks are Pyramid, Django, and Flask.
  • Python is also used for a simple scripting and scientific modeling and big data applications:
  • It is the number one choice for several data scientists.
  • Its libraries such as NumPy, Pandas data visualization libraries such as Matplotlib and Seaborn have made Python very popular in this field.
  • Python also has some interesting libraries such as Scikit-Leam, NLTK, and TensorFlow that implement Machine learning Algorithms.
  • Video Games can be created using the PyGame module. Such applications can run on Android devices.
  • Python can be used for web scrapping.
  • Selenium with Python can be used for things like opening a browser or posting a status on Facebook.
  • Modules such a Tkinter and PyQt allow you to build a GUI desktop application.

Question 2.
Why is Python considered to be a highly versatile programming language?
Answer:
Python is considered to be a highly versatile programming language because it supports multiple models of programming such as:

  • OOP
  • Functional
  • Imperative
  • Procedural

Question 3.
What are the advantages of choosing Python over any other programming language?
Answer:
The advantages of selecting Python over other programming languages are as follows:

  • Extensible in C and C++.
  • It is dynamic in nature.
  • Easy to learn and easy to implement.
  • Third-party operating modules are present: As the name suggests a third party module is written by a third party which means neither you nor the python writers have developed it. However, you can make use of these modules to add functionality to your code.

Question 4.
What do you mean when you say that Python is an interpreted language?
Answer:
When we say that Python is an interpreted language it means that python code is not compiled before execution. Code written in compiled languages such as Java can be executed directly on the processor because it is compiled before runtime and at the time of execution it is available in the form of machine language that the computer can understand. This is not the case with Python. It does not provide code in machine language before runtime. The translation of code to machine language occurs while the program is being executed.

Question 5.
Are there any other interpreted languages that you have heard of?
Answer:
Some frequently used interpreted programming languages are as follows:

  • Python
  • Pearl
  • JavaScript
  • PostScript
  • PHP
  • PowerShell

Question 6.
Is Python dynamically typed?
Answer:
Yes, Python is dynamically typed because in a code we need not specify the type of variables while declaring them. The type of a variable is not known until the code is ‘executed.

Question 7.
Python is a high-level programming language? What is a need for high-level programming languages?
Answer:
High-level programming languages act as a bridge between the machine and humans. Coding directly in machine language can be a very time-consuming and cumbersome process and it would definitely restrict coders from achieving their goals. High-level programming languages like Python, JAVA, C++, etc are easy to understand. They are tools that programmers can use for advanced-level programming. High-level languages allow developers to code complex code that is then translated to machine language so that the computer can understand what needs to be done.

Question 8.
Is it true that Python can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java?
Answer:
Yes

Question 9.
What are the different modes of programming in Python?
Answer:
There are two modes of programming in Python:
1. Interactive Mode Programming:
In this, we invoke the interpreter without passing any script or python file. We can start the Python command-line interpreter or the Python shell in IDLE and start passing instructions and get instant results.
2. Script Mode of Programming:
Saving code in a Python file. When the script is executed the interpreter is invoked and it is active as long as the script is running. Once all the instructions of the script are executed the interpreter is no longer active.

Question 10.
Draw a comparison between Java and Python.
Answer:

1. Java is compiled and Python is interpreted:
Both Java and Python are compiled down to the byte code on the virtual machine. However, in the case of Python, this happens automatically during runtime whereas Java has a separate program – javac to accomplish this task. This also means that if speed is the major concern in your project then Java may have an edge over Python but you cannot deny that Python allows faster development (as you will leam in the next point).

2. Java is Statistically typed and Python is dynamically typed:
While coding in Python, it is not required to declare the type of the variable. This makes Python easy to write and read but it can be difficult to analyze. The developer is able to code faster and the task can be accomplished in fewer lines of code. Developing applications in Python can be much faster Python than Java. However, Java’s static type system makes it less prone to bugs.

3. Writing style:
Both Java and Python follow different writing styles. Java encloses everything in braces whereas Python follows indentation that makes the code neat and readable. Indentation also determines the code execution.

4. Both Java and Python are efficient languages:
Both Java and Python are being widely used for web development frameworks. Developers are able to create complex applications that can handle high traffic.

5. Both Java and Python have a strong community and library support:
Both are open source languages having communities that are offering support and contribution to the language. You can easily find a library for almost anything.

6. Python can be more budget-friendly:
Since Python is dynamically typed, it makes development a fast process as a result of which developers can expect to develop an application in a record time thereby lowering down the cost of development.

7. Java is the more preferred language in mobile development:
Android app development is mostly done using Java and XML. However, there are libraries like Kivy which can be used along with Python code in order to make it compatible with android development.

8. Python is preferred for Machine learning, the Internet of things, ethical hacking, data analysis, and artificial intelligence:
Python has very specialized libraries and general flexibility and hence it has become the number one choice for projects that have a bias towards deep learning, machine learning, and image recognition.

9. Java and Python both support OOP:

10. LOC in Java is more than in Python: Let’s have a look at how we would go about printing simple Hello World in Java:

public class HelloWorld 
{ 
  public static void main(String [ ] args) 
{ 
  System.out.println("Hello World"); 
} 
  } 
Whereas in python we just write one line of code: print("Hello World")

11. Java is more difficult to learn as compared to Python:
Python was developed with the main focus on making it easy to learn.

12. Java is stronger when it comes to connectivity with database:
The database access layer of Java is very strong and is compatible with almost any database. Python database connectivity is not as strong as Java.

13. Security:
Java gives high priority to security which is why it is a preferred language for applications that require security but a good developer can code a secure application in Python also.

Question 11.
Once Python is installed, how can we start working on code?
Answer:
After Python is installed there are three ways to start working on code:

1. You can start an interactive interpreter from the command line and start writing the instructions after the »> prompt.

2. If you intend to write a code of several lines then it would be a wise decision to save your file or script with the .py extension and you can execute these files from the command line. Multiline programs can be executed on an interactive interpreter, also but it does not save the work.

3. Python also has its own GUI environment known as Integrated Development Environment (IDLE). IDLE helps programmers write code faster as it helps with automatic indenting and highlights different keywords in different colors. It also provides an interactive environment. It has two windows: the shell provides an interactive environment whereas the editor allows you to save your scripts before executing the code written in it.

Question 12.
What is the function of the interactive shell?
Answer:
The interactive shell stands between the commands given by the user and the execution done by the operating system. It allows users to use easy shell commands and the user need not be bothered about the complicated basic functions of the Operating System. This also protects the operating system from incorrect usage of system functions.

Question 13.
How to exit interactive mode?
Answer:
Ctrl+D or exit( ) can be used to quit interactive mode.

Question 14.
Which character set does Python use?
Answer:
Python uses a traditional ASCII character set.

Question 15.
What is the purpose of indentation in Python?
Answer:
Indentation is one of the most distinctive features of Python. While in other programming languages, developers use indentation to keep their code neat but in the case of Python, indentation is required to mark the beginning of a block or to understand which block the code belongs to. No braces are used to mark blocks of code in Python. Blocks in code are required to define functions, conditional statements, or loops. These blocks are created simply by the correct usage of spaces. All statements that are the same distance from the right belong to the same block.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 1

Remember:

  • The first line of the block always ends with a semicolon (:).
  • Code under the first line of the block is indented. The preceding diagram depicts a scenario of indented blocks.
  • Developers generally use four spaces for the first level and eight spaces for a nested block, and so on.

Question 16.
Explain Memory Management in Python.
Answer:
Memory management is required so that a partial or complete section of the computer’s memory can be reserved for executing programs and processes. This method of providing memory is called memory allocation. Also, when data is no longer required, it must be removed. Knowledge of memory management helps developers develop efficient code.

Python makes use of its private heap space for memory management. All object structures in Python are located in this private heap (which is not accessible by the programmer). Python’s memory manager ensures that this heap space is allocated judiciously to the objects and data structures. An in-built garbage collector in Python recycles the unused memory so that it is available in heap space.

Everything in Python is an object. Python has different types of objects, such as simple objects which consist of numbers and strings, and container objects such as diet, list, and user-defined classes. These objects can be accessed by an identifier- name. Now, let’s have a look at how things work.
Suppose, we assign the value of 5 to a variable a:
a = 5
Here, ‘5’ is an integer object in memory, and ‘a’ has reference to this integer object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 2

In the above illustration, the id( ) function provides a unique identification number of an object. This unique identification number is an integer value that will remain unique and constant for the object during its lifetime. Two objects with non-overlapping lifetimes can have the same id( ) value.

The id for integer object 5 is 140718128935888. Now we assign the same value 5 to variable b. You can see in the following diagram that both a and b have to refer to the same object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 3

Now, let us say:
c = b.
This means, c too will have reference to the same object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 4

Now, suppose we perform the following operation: a =a+1

This means that a is now equal to 6 and now refers to a different object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 5

Some amount of memory organization is done for every instruction. The underlying operating system allocates some amount of memory for every operation. The Python interpreter gets its share of memory depending on various factors such as version, platform, and environment.

The memory assigned to the interpreter is divided into the following:

1. Stack:
a. Here all methods are executed.
b. References to objects in the heap memory are created in stack memory.
2. Heap:
a. The objects are created in Heap memory.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 6

Now let’s have a look at how things work with the help of an example. Look at the following piece of the code:

def function1(x): 
    value1 = (x + 5)* 2 
    value2 = function2(value1) 
      return value2 
def function2(x): 
   x = (x*10)+5 
   return x 
   x = 5 
final_value = function1 (x) 
print ("Final value = ", final_value)

Now, let’s see how this works. The program’s execution starts from the main which in this case is:

x = 5 
final_value = function1 (x) 
print ("Final value = ", final_value)

Step 1: execute x =5
This creates integer object 5 in the heap and reference to this object i.e. x is created in the main stack memory.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 7

Step 2: is to execute final_value = function1(x)
This statement calls function1( ).

def function1 (x):
value1 = (x + 5)* 2
value2 = function2(value1)
return value2

In order to execute function1 ( ) a new stack frame is added to the memory. Till the time function1( ) is being executed the lower stack frame of x referencing to 5 is put on hold. The integer value 5 is passed as a parameter to this function.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 8

Now, value1 = (x+5)* 2 = (5+5)*2 = 10*2 = 20

Python Interview Questions and Answers on Introduction to Python chapter 1 img 9

function1( ) assigns the value of 50 to value1.
The next step is: value2 = function2(value1)

Here function2( ) is called to evaluate a value that needs to be passed on to value2. In order to accomplish this, another memory stack is created. The integer object value1 having a value of 20 is passed as a reference to function2.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 10

def function2 (x) : 
x = (x*10)+5 
return x

The function function2( ) evaluates the following expression and returns the value:

x = (x*10)+5
x = (20*10)+5 = (200)+5 = 205

 

Python Interview Questions and Answers on Introduction to Python chapter 1 img 11

The function function2( ) is fully executed and value 205 is assigned to value2 in function 1. So, now the stack for function(2) is removed.

 

Python Interview Questions and Answers on Introduction to Python chapter 1 img 12

Now, function1( ) will return the value 205 and it will be assigned to the final_value in the main stack.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 13

Here it is important to note that you would see that x exists in the main as well as in different functions but the values don’t interfere with each other as each x is in a different memory stick.

Question 17.
Explain Reference counting and Garbage collection in Python.
Answer:
Unlike languages like C/ C++, the process of allocation and deallocation of memory in Python is automatic. This is achieved with the help of reference counting and garbage collection.

As the name suggests, reference counting counts the number of times an object is referred to by other objects in a program. Every time a reference to an object is eliminated, the reference count decreases by 1. As soon as the reference count becomes zero, the object is deallocated. An object’s reference count decreases when an object is deleted, the reference is reassigned or the object goes out of scope. The reference count increases when an object is assigned a name or placed in a container.

Garbage collection on the other hand allows Python to free and reclaim blocks of memory that are no longer of any use. This process is carried out periodically. The garbage collector runs while the program is being executed and the moment the reference count of an object reaches zero, the garbage collector is triggered.

Question 18.
What are multi-line statements?
Answer:
All the statements in Python end with a newline. If there is a long statement, then it is a good idea to extend it over multiple lines. This can be achieved using the continuation character (\).

Explicit line continuation is when we try to split a statement into multiple lines whereas in the case of implicit line continuation we try to split parentheses, brackets, and braces into multiple lines.
Example for multiple line statements:

Explicit:

>>> first_num = 54
>>> second_num = 879
>>> third__num = 8 76
>>> total = first_num +\
               second_num+\
               third_num
>>> total
1809
>>>
Implicit:
>>> weeks=['Sunday' ,
                      'Monday',
                      'Tuesday',
                      'Wednesday',
                      'Thursday' ,
                      'Friday',
                      'Saturday']
>>> weeks
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursdy', 'Friday', 'Saturday']
>>>

Question 19.
What are the types of error messages in Python?
Answer:
While working with Python you can come across:

1. Syntax-error
2. Run-time errors

Syntax errors are static errors that are encountered when the interpreter is reading the program. If there is any mistake in the code then the interpreter will display a syntax error message and the program will not be executed.
Run time errors as the name suggests are dynamic errors. They are detected while the program is executing. Such errors are bugs in the program that may require design change such as running out of memory, dividing a number by zero, and so on.

Question 20.
What are the advantages of Python’s IDLE environment?
Answer:
The Python IDLE environment has the following:

  • Python’s interactive mode
  • Tools for writing and running programs
  • It comes along with the text editors which can be used for working on scripts

Question 21.
What is a comment?
Answer:
A comment is one or more statements used to provide documentation or information about a piece of code in a program. In Python one-line comments start with ‘#’.

Question 22.
Is Python a case-sensitive programming language?
Answer:
Yes

General Python Concepts

Question 23.
How is Python executed?
Answer:
Python files are compiled to bytecode, which is then executed by the host.
Alternate Answer: Type python <sourcefile>.py at the command line.

Question 24.
What is the difference between .py and .pyc files?
Answer:
.py files are Python source files, .pyc files are the compiled bytecode files that are generated by the Python compiler

Question 25.
How do you invoke the Python interpreter for interactive use?
Answer:
python or pythonx.y where x.y is the version of the Python interpreter desired.

Question 26.
How are Python blocks defined?
Answer:
By indents or tabs. This is different from most other languages which use symbols to define blocks. Indents in Python are significant.

Question 27.
What is the Python interpreter prompt?
Answer:
Three greater-than signsQuestion>>> Also, when the interpreter is waiting for more input the prompt changes to three periods …

Question 28.
How do you execute a Python Script?
Answer:
From the command line, type python <scriptname>.py or pythonx.y <scriptname>.py where the x.y is the version of the Python interpreter desired.

Question 29.
Explain the use of tryQuestionexceptQuestionraise, and finally:
Answer:
Try, except and finally blocks are used in Python error handling. Code is executed in the try block until an error occurs. One can use a generic except block, which will receive control after all errors, or one can use specific exception handling blocks for various error types. Control is transferred to the appropriate except block. In all cases, the final block is executed. Raise may be used to raise your own exceptions.

Question 30.
Illustrate the proper use of Python error handling.
Answer:
Code Example
try:
… # This can he any code
except:
… # error handling code goes here
finally:
… # code that will be executed regardless of exception handling goes here.

Question 31.
What happens if an error occurs that is not handled in the except block?
Answer:
The program terminates, and an execution trace is sent to sys. stderr.

Question 32.
How are modules used in a Python program?
Answer:
Modules are brought in via the import statement.

Question 33.
How do you create a Python function?
Answer:
Functions are defined using the def statement. An example might be deffoo(bar):

Question 34.
How is a Python class created?
Answer:
Classes are created using the class statement. An example might be class aardvark(foobar):

Question 35.
How is a Python class instantiated?
Answer:
The class is instantiated by calling it directly. An example might be myclass=aardvark(5)

Question 36.
In a class definition, what do the init ( ) functions do?
Answer:
It overrides any initialization from an inherited class and is called when the class is instantiated.

Question 37.
How does a function return values?
Answer:
Functions return values using the return statement.

Question 38.
What happens when a function doesn’t have a return statement? Is this valid?
Answer:
Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code is executed (i.e., the indenting) not by any explicit keyword.

Question 39.
What is the lambda operator?
Answer:
The lambda operator is used to create anonymous functions. It is mostly used in cases where one wishes to pass functions as parameters or assign them to variable names.

Question 40.
Explain the difference between local and global namespaces.
Answer:
Local namespaces are created within a function when that function is called. Global namespaces are created when the program starts.

Question 41.
Name the four main types of namespaces in Python? Answer:

  • Global,
  • Local,
  • Module and
  • Class namespaces.

Question 42.
When would you use triple quotes as a delimiter? Answer:
Triple quotes ” ” ” or are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained therein.

Python Interview Questions on Introduction to Python Read More »

Python Programming – Class Example

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

Python Programming – Class Example

Class example

Till now, some basic concepts of class has been discussed. The following example “ClassExample.py” defines’a class Person, which handles name and age of multiple individuals.

class Person: 
          " " "The program handles individual's data" " "
population=0

def ___init____ ( self , Name , Age ) : 
           " " "Initializes the data." " "
          self.name=Name
          self.age=Age
          Person.population+=1

def ___del___ ( self ) : 
         " " "Deleting the data." " "
        print ( ' Record of {0} is being removed'.format(self.name)) Person.population-=1

def AgeDetails ( self ) :
         ' ' 'Age details : ' ' ' 
       print ( ' { 0 } is { 1 } years old ' . format ( self . name , self . age ) )

def Records ( cls) : 
           " " "Print number of records." " "
          print ( ' There are {0} records ' . format ( cls.population ) )

records=classmethod ( Records )

print Person . ___doc___ 
record1=Person ( ' Ram ' , 26 )
print Person.AgeDetails. ___doc___ 
record1 . AgeDetails ( )
Person.records ( ) 
record2-Person ( ' Ahmed ' , 20 )
print record2 . AgeDetails. ___doc___ 
record2 . AgeDetails ( ) 
record2 . records ( ) 
record3=Person ( ' John ' , 22 )
print Person . AgeDetails. ___doc___ 
record3 . AgeDetails ( )
Person . records ( ) 
del recordl,record2 
Person . records ( )

The output is:

The program handles individual's data 
Age details :
Ram is 26 years old 
There are 1 records 
Age details :
Ahmed is 20 years old 
There are 2 records 
Age details : 
John ih 22 years old
There are 3 records 
Record of Ram is being removed 
Record of Ahmed is being removed 
There are 1 records

Variables defined in the class definition are class variables (population is a class variable); they are shared by all instances. To create instance variables (name and age are instance variables), they can be initialized in a method, e.g. self. name=value. Both class and instance variables are accessible through the notation self. name and an instance variable hide a class variable with the same name when accessed in this way. Therefore, the class variable population is better referred to as Person. population, and not-self. population. The instance variables name and age are referred to as self. name and self. age, respectively.

The Records is a method that belongs to the class and not to the instance. This is done by using classmethod ( ) built-in function. A class method receives the class as an implicit first argument, just like an instance method receives the instance. The class method can be called either on the class (Person. records ( )) or on an instance (record2 . records ( )). The instance is ignored except for its class.

The ___doc___ attribute is used to access docstrings of class (Person. ___doc___ ) and methods (record2 . AgeDetails . __doc___).

The ___del___ ( ) method is called when an instance is about to be destroyed. This is also called a destructor.

Python Programming – Class Example Read More »

Python Object Oriented Programming

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

Python Programming – Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm that represents concepts as “objects”, that have attributes that describe the object in the form of data attributes and associated procedures known as methods. As mentioned in chapter 1, Python is an OOP language. In Python, class form the basis of OOP. Some of the features of OOP language are:

  • Inheritance
  • Polymorphism
  • Encapsulation

Some of the advantages of the OOP approach are:

– Reusability: A part of a code can be reused for accommodating new functionalities with little or no changes.
– Maintenance: If some modification is made in the base class, the effect gets reflected automatically into the derived class, thus, the code maintenance is significantly less hectic.
– Faster output: With organized and methodical coding, there is little room for error, and as a result programmer can work comfortably, resulting in fast and efficient output.

Method object

In the MyClass example, x. f is a method object and x. f ( ) returns the string ‘hello world’. The call x. f ( ) is exactly equivalent to MyClass . f (x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument

>>> x . f ( )
' hello world '
>>> x . f ( )==MyClass . f ( x )
True

The method object can be stored and can be called later.

>>> xf=x . f 
>>> print xf ( )
hello world
>>> type ( xf )
<type ' instancemethod ' >

Python Programming OOP

Python Object Oriented Programming Read More »

Python Programming – Customizing Attribute Access

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

Python Programming – Customizing Attribute Access

Customizing attribute access

The following are some methods that can be defined to customize the meaning of attribute access for class instance.

object.___getattr____ ( self , name )
Called when an attribute lookup does not find the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception. Note that, if the attribute is found through the normal mechanism, ___getattr___ ( ) is not called.

>>> class HiddenMembers:
. . .        def ___getattr___ ( self , name ) :
. . .               return "You don't get to see "+name
. . . 
>>> h=HiddenMembers ( )
>>> h . anything
" You don't get to see anything "

object . setattr ( self , name , value )
Called when an attribute assignment is attempted. The name is the attribute name and value is the value to be assigned to if. Each class, of course, comes with a default ___setattr___ , which simply set the value of the variable, but that can be overridden.

>>> class Unchangable: 
. . .         def ___setattr____ ( self , name , value ) :
. . .                print " Nice try "
. . . 
>>> u=Unchangable ( )
>>> u . x=9 
Nice try 
>>> u . x
Traceback ( most recent call last ) :
    File "<stdin>", line 1, in ?
AttributeError: Unchangable instance has no attribute 'x' ;

object.___delattr___ ( self , name )
Like ____setattr___ ( ), but for attribute deletion instead of assignment. This should only be implemented if del ob j . name is meaningful for the object.

>>> Class Permanent :
. . . def ___delattr____ ( self , name ) :
. . . print name , " cannot be deleted "
. . .
>>> p=Permanent ( )
>>> p . x=9 
>>> del p . x 
x cannot be deleted 
>>> p . x
9

Python Programming – Customizing Attribute Access Read More »

Python Programming – Pre-Defined Attributes

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

Python Programming – Pre-Defined Attributes

Pre-defined attributes

Class and class instance objects has some pre-defined attributes:

Class object

Some pre-defined attributes of class object are:

__name__
This attribute give the class name.

>>> MYClass . __name__
' MYClass '

__module__
This attribute give the module name.in which the class was defined.

>>> MYClass . ___module___
' ___main___ '

___dict___
A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., MyClass . i is translated to MyClass .___dict___ [ ” i ” ].

>>> MyClass.___dict___
{ ' i ' : 12345 , '___module___' : '___main___ ' , '___doc___ ': ' A simple example class ' , ' f ' : <function f at 0x0640A070>}

___bases___
This attribute give the tuple (possibly empty or a singleton) containing the base classes.

>>> MyClass.___bases___.
( )

___doc___
This attribute give the class documentation string, or None, if not defined.

>>> MyClass.___doc___ 
' A simple example class '

Class instance object
Some pre-defined attributes of class instance object are:

___dict___
This give attribute dictionary of class instance.

>>> x. ___dict___ 
{ }

___class___
This give the instance’s class.

>>> x. ___class____ 
<class ___main___ .MyClass at 0x063DA880>

Python Programming – Pre-Defined Attributes Read More »

Python Programming – Instance Object

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

Python Programming – Instance Object

Instance object

The only operation that done using class instance object x is attribute references. There are two kinds of valid attribute names: “data attribute” and “method”.

Data attribute corresponds to a variable of a class instance. Data attributes need not be declared; like local variables, they, spring into existence when they are first assigned to. For example, if x is the instance of MyClass (created, before), the following piece of code will print the value 16, without leaving a trace:

>>> x . counter=1
>>> while x . counter<10:
. . . x . counter=x. counter*2
. . .
>>> print x . counter 
16 
>>> del x . counter

The other kind of instance attribute reference is a method. Any function object that is a class attribute defines a method for instances of that class. So, x. f is a valid method reference, since MyClass. f is a function.

Python Programming – Instance Object Read More »

Python Programming – Class Object

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

Python Programming – Class Object

Class object

When a class definition is created, a “class object” is also created. The class object is basically a wrapper around the contents of the namespace created by the class definition. Class object support two kinds of operations: “attribute reference” and “instantiation”.

Attribute reference

Attribute references use the standard syntax used for all attribute references in Python: obj .name. Valid attribute names are all the names that were in the class’s namespace, when the class object was created. So, if the class definition looked like this:

>>> class MyClass: 
. . .            " " "A simple example class " " " 
. . .           i=12345
. . .           def f ( self ) : 
. . .                 return ' hello world ' :
. . . 
>>> MyClass . i 
12345
>>> MyClass.___doc___
' A simple example class '

then MyClass . i and MyClass . f are valid attribute references, returning an integer and a method object, respectively. The value of MyClass.i can also be change by assignment. The attribute ___doc___is also a valid attribute, returning the docstring belonging to the class.

>>> type ( MyClass )
<type ' classobj ' >

From the above expression, it can be noticed that MyClass is a class object.

Instantiation

A class object can be called to yield a class instance. Class instantiation uses function notation. For example (assuming the above class MyClass):

x=MyCiass ( )

creates a new instance of the class MyClass, and assigns this object to the local variable x.

>>> type ( MyClass( ) )
<bype ' instance' > 
>>> type (x) 
<type 'instance'>

Many classes like to create objects with instances customized to a specific initial state. Therefore, a class may define a special method named ___init___( ), like this:

def __init__ ( self ) :
self.data=[ ]

When a class defines an __init__ ( ) method, class instantiation automatically invokes __init__( ) for the newly created class instance. So in this example, a new, initialized instance can be obtained by:

x=MyClass ( )

Of course, the ___init___ ( ) method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to ___init___ ( ). For example,

>>> class Complex:
. . .          def __init___ ( self , realpart , imagpart ) :
. . .              self . r=realpart
. . .              self . i=imagpart
>>> x=Complex ( 3 . 0, -4 . 5 )
>>> x . r , x . i
( 3 . 0 , -4 . 5 )

Python Programming – Class Object Read More »

Python Programming – Method

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

Python Programming – Method

Method

A method is a function that belongs to an object. In Python, the term “method” is not unique to class instance, other object types can have methods as well. For example, list objects have methods, namely, append, insert, remove, sort, and so on.

Usually in a class, the method is defined inside its body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). Self is merely a conventional name for the first argument of a method. For example, a method defined as meth (self, a, b, c) should be called as x.meth (a, b, c) for an instance x of the class in which the definition occurs; the called method will think it is called as meth (x, a, b, c). The idea of self was borrowed from “Modula-3” programming language.

It is not necessary that the function definition is textually enclosed in the class definition; assigning a function object to a local variable in the class is also fine. For example:

>>> def f 1 ( self , x , y ) :
. . .            return min ( x , x+y )
. . . 
>>> class test_class :
. . .        aa=f1
. . .        def bb ( self ) : 
. . .              return ' hello world '
. . .       cc=bb
. . . 
>>>

Here aa, bb and cc are all attributes of class test_class that refer to function objects, and consequently, they are all methods of instances of class test_class; cc being exactly equivalent to bb. Note that this practice usually confuses the reader of the program.

Usually, Python use methods for some functionality (e.g. list. index ()), but functions for other (e.g. len (list)). The major reason is history; functions were used for those operations that were generic for a group of types and which were intended to work even for objects that did not have methods at all (e.g. tuples). In fact, implementing len ( ), max ( ), min ( ) etc.

as built-in functions has actually less code than implementing them as methods for each type. One can quibble about individual cases, but it is part of Python, and it is too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage.

Python Programming – Method Read More »