Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit series activities – click on the task to see the details of the activities.

Difficulty level: Intermediate Predicts the output of the following Python programs.

A program:

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

acc = Acc(111)
print acc.id
Copy the code

Output:

111
Copy the code

Explanation: An instantiation of class “Acc” automatically calls the method __init__ and passes the object as the self argument. 111 Data attributes assigned to the object called ID. The value “555” is not retained in the object because it has no data attributes assigned to the class/object. So, the output of the program is 111.

Program 2:

for i in range(2) :print i

for i in range(4.6) :print i
Copy the code

Output:

0
1
4
5
Copy the code

Note: If you pass only a single argument to the range method, Python treats that argument as the end of the range, and the default starting value of the range is 0. Therefore, it prints all numbers from 0 up to the supplied parameters. For the second for loop, the start value is explicitly provided as 4 and the end value as 5.

Three procedures:

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
Copy the code

Output:

1
2
3
4
Copy the code

Note: The function “filter” returns all items in the list value, which returns True when passed to the function “checknums”. Checknums checks if the value is in the collection. Since all numbers in the collection come from the list of values, all raw values in the list will return True.

Four procedures:

counter = {}

def addToCounter(country) :
	if country in counter:
		counter[country] += 1
	else:
		counter[country] = 1

addToCounter('China')
addToCounter('Japan')
addToCounter('china')

print len(counter)
Copy the code

Output:

3
Copy the code

Explanation: The “len” function returns the number of keys in the dictionary. Here we use the “addToCounter” function to add the three keys to the dictionary “country”. Note – dictionary keys are case sensitive.

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

If you find anything wrong, let me know in the comments section below, learn from each other and make progress together!