In the functions I've written so far, I've explained the case where the argument is a variable of a numerical value or a character string. Now consider passing a variable in the list. It's not particularly difficult, just create the list as before and pass the variables in the list.
This time, we will create a program with the following requirements.
Enter the test scores for Japanese, math, and English, combine them into one list, and create a program to find the average score in the function. Please do not output the average score in the function.
Create a file with the file name samp06-04-01.py </ font> in chap06 </ font>, and use the following code Please write.
samp06-04-01.py
def test_clac_func(test_data_ls):
#Output the contents of the list once.
print(test_data_ls)
#You can add all the numbers in the list with the sum function. The following is the average.
avg = sum(test_data_ls) / len(test_data_ls)
return avg #Return the calculated average to the calling function
##Enter the score for each subject
jpn = int(input('National language score:'))
math = int(input('Math score:'))
eng = int(input('English score:'))
##List points
test_data_ls = [jpn, math, eng]
##Call a function with a list as an actual argument
avg = test_clac_func(test_data_ls)
print(f'Average score:{avg}')
[Execution result] </ font> National language score: 75 Math score: 80 English score: 72 [75, 80, 72] Average score: 75.66666666666667
This time, after inputting 3 subjects, those values are ** listed ** as a variable ** test_data_ls **. The function is called with this list as the actual argument of the ** test_clac_func function **. I think there is no problem with the processing inside the function, but you can add all the numbers in the list with the ** sum function **.
You can see that the function that is called even if you pass the list receives the list as a formal argument.
We have prepared exercises. Please try to solve it. Create the program in chap06 </ font>. You can specify any variable name you like. [1] Enter two numerical values a and b and create a program that outputs a large value. However, please use the function.
[Execution result] </ font> Enter the number a: 2 Enter the number b: 4 4 is larger.
Lists come up so often that you often actually apply them to a function. In particular, the treatment is the same as the character strings and numerical variables that I have learned so far, so I think I didn't get lost in particular. Keep in mind that you can also pass a list as an argument.