Output of Python Programs | Second Set

Difficulty Level: Intermediate
Predict the output of the following Python program.

Procedure one:

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

acc = Acc(111)
print acc.id

output:

111

Explanation: The instantiation of class "Acc" automatically calls the method __init__ and passes the object as the self parameter. 111 is assigned to the data property of the object called id. The value "555" is not preserved in the object because it has no data property assigned to the class/object. So, the output of the program is "111" \

Procedure two:

a = "haiyong "

b = 13

print (a + b)

output:

An error is shown

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

Procedure three:

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 in the list value, which returns True when passed to the function "checknums". "checknums" will check if the value is in the set. Since all numbers in the set come from the list of values, all primitive values ​​in the list will return True.

Procedure four:

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 the "len" function is to return the number of keys in the dictionary. Here 3 keys are added to the dictionary "country" using the "addToCounter" function. 
Note - dictionary keys are case sensitive.

Try it yourself: what happens if the same key is passed twice?

If you find anything incorrect, you can tell me in the comment area below, learn from each other and make progress together!

Guess you like

Origin blog.csdn.net/qq_44273429/article/details/123352029