Open In App
Related Articles

Output of python program | Set 2

Improve Article
Improve
Save Article
Save
Like Article
Like

Difficulty level : Intermediate
Predict the output of following Python Programs. 
Program 1: 
 

Python3




class Acc:
    def __init__(self, id):
        self.id = id
        id = 555 
  
acc = Acc(111)
print (acc.id)

Output:

111

Explanation: Instantiation of the class “Acc” automatically calls the method __init__ and passes the object as the self parameter. 111 is assigned to data attribute of the object called id. 
The value “555” is not retained in the object as it is not assigned to a data attribute of the class/object. So, the output of the program is “111” 
 
Program 2: 
 

Python3




for i in  range(2):
    print (i)
  
for i in range(4,6):
    print (i)

Output: 
 

0
1
4
5

Explanation: If only single argument is passed to the range method, Python considers this argument as the end of the range and the default start value of range is 0. So, it will print all the numbers starting from 0 and before the supplied argument. 
For the second for loop the starting value is explicitly supplied as 4 and ending is 5.
  
Program 3: 
 

Python3




values = [1, 2, 3, 4]
numbers = set(values)
  
def checknums(num):
    if num in numbers:
        return True
    else:
        return False
  
for i in  filter(checknums, values):
    print (i)

Output: 
 

1
2
3
4

Explanation: The function “filter” will return all items from list values which return True when passed to the function “checknums”. “checknums” will check if the value is in the set. Since all the numbers in the set come from the values list, all of the original values in the list will return True.
 
Program 4: 
 

Python3




counter = {}
  
def addToCounter(country):
    if country in  counter:
        counter[country] += 1
    else:
        counter[country] = 1
  
addToCounter('China')
addToCounter('Japan')
addToCounter('china')
  
print (len(counter))

Output: 
 

3

Explanation: The task of “len” function is to return number of keys in a dictionary. Here 3 keys are added to the dictionary “country” using the “addToCounter” function. 
Please note carefully – The keys to a dictionary are case sensitive. 
Try yourself: What happens If same key is passed twice??
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


Last Updated : 11 Sep, 2023
Like Article
Save Article
Similar Reads