Python Program Output | Set 3

Python Methods and Functions

Predict the output of the following Python programs.

Program 1:

class Geeks:

def __ init __ ( self , id ):

self . id = id

 

manager = Geeks ( 100 )

 

manag er .__ dict __ [ 'life' ] = 49

 

print manager.life + len (manager .__ dict__)

Exit:

 51 

Explanation: In the above program, we create a member variable named & # 39; life & # 39; by adding it directly to the dictionary of the & # 39; manager & # 39; class & # 39; Geeks & # 39 ;. The total number of elements in the dictionary is 2, the variables "life" and "identifier". Therefore, the size or length of the dictionary is 2, and the variable "life" is assigned the value "49". Thus, the sum of the variable & # 39; life & # 39; and the dictionary size is 49 + 2 = 51.

Program 2:

a = "GeeksforGeeks"

 

b = 13

 

print a + b

Output:

 An error is shown. 

Explanation: As you can see, the variable & # 39; b & # 39; is of type integer, and the variable & # 39; a & # 39; is of type string. Also, since Python is a strongly typed language, we cannot just concatenate an integer with a string. First, you need to convert an integer variable to a string of type in order to concatenate it with a string variable. Therefore, when trying to concatenate an integer variable into a string variable, an exception of type "TypeError" is thrown.

Program 3:

dictionary = {}

dictionary [ 1 ] = 1

dictionary [ '1' ] = 2

dictionary [ 1 ] + = 1

 

sum  = 0

for k in dictionary:

sum + = dictionary [k]

 

print sum

Output:

 4 

Explanation: In the above dictionary, key 1, enclosed in single quotes and only 1, represents two different keys, one being an integer and the other — string. So, the output of the program — 4.

Program 4:

dictionary = { 1 : '1' , 2 : '2' , 3 : '3' }

del dictionary [ 1 ]

dictionary [ 1 ] = ' 10'

del dictionary [ 2 ]

print len ​​(dictionary)

Exit d:

 2 

Explanation: The purpose of the function & # 39; del & # 39; consists in removing key-value pairs from the dictionary. The original size of this dictionary was 3. Then the key value pair for key 1 is first removed and then added back with the new value. Then the key-value pair for key 2 is removed. So finally the dictionary size is 2.

This article is provided by Agarwal . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.





Tutorials