I am fairly new to Python and do not understand the explanation given by the course I am doing. I cannot follow why width gets 2.
To my understanding the print(combine(1)[2]) appoints the value to to position one. But I thought is_3D is in position 0, hence height would be in position 2.
So I do not understand what is going on here.
def combine(width, height=2, depth=0, is_3D=False):
return[is_3D, width, height, depth]
print(combine(1)[2])
>Solution :
Here’s a code answering your question, see below.
Short answer – return[is_3D, width, height, depth] reorders the input parameters of this function inside the list. At the end, you are asking to print an element in position [2], which is ‘height’. Height has a default value of 2 and is a keyword argument with a default value of 2. Which results in the output of 2.
I added logging to the code, which is best practice and can be useful.
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def combine(width, height=2, depth=0, is_3D=False):
logging.info(f'width = {width}')
logging.info(f'height = {height}')
logging.info(f'height = {depth}')
logging.info(f'is_3D = {is_3D}')
return [is_3D, width, height, depth]
returned_list = combine(1)
logging.info(f'return of the function is {returned_list}')
print(returned_list[2])
2023-02-03 13:24:52,069 - root - INFO - width = 1
2023-02-03 13:24:52,069 - root - INFO - height = 2
2023-02-03 13:24:52,069 - root - INFO - height = 0
2023-02-03 13:24:52,069 - root - INFO - is_3D = False
2023-02-03 13:24:52,069 - root - INFO - return of the function is [False, 1, 2, 0]
2
