Computer Science-Lesson9
Computer Science-Lesson9
LESSON9
LESSON 9
QUIZ
Create a code for entering the exam scores for students of a subject, as it will be
shown in the output the marks of students who only passed the exam.
ANSWER
# using the for loop through the list to filter out the scores:
• for x in marks_list:
• if x>=60:
• print(x)
ANSWER
Now Create a new list containing only the scores of students who passed the exam:
Creating a Function
• In Python a function is defined using the def keyword:
Example:
• def my_function():
• print("Hello from a function")
9- FUNCTIONS
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
• def my_function():
• print("Hello from a function")
• my_function()
9-FUNCTIONS
Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You can add as many arguments as
you want, just separate them with a comma.
• The following example has a function with one argument (fname). When the function is called, we pass along
a first name, which is used inside the function to print the full name:
• def my_function(fname):
• print(fname+" Taha")
• my_function("Omar")
9-FUNCTIONS
Parameters or Arguments?
• The terms parameter and argument can be used for the same thing: information that is passed into a
function.
Number of Arguments
• By default, a function must be called with the correct number of arguments. Meaning that if your function
expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
Example:
• This function expects 2 arguments, and gets 2 arguments:
If you try to call the function with 1 or 3 arguments, you will get an error:
Example:
This function expects 2 arguments, but gets only 1:
• my_function("Emil")
9-FUNCTIONS
Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your function, add a * before the parameter
name in the function definition.
• This way the function will receive a tuple of arguments, and can access the items accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
• def my_function(*kids):
• print("The youngest child is " + kids[2])
Example:
• def my_function(country = "Norway"):
• print("I am from " + country)
• my_function("Sweden")
• my_function("India")
• my_function()
• my_function("Brazil")
9-FUNCTIONS
• You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.
• E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example:
• def my_function(food):
• for x in food:
• print(x)
• my_function(fruits)
9-FUNCTIONS
Return Values
To let a function return a value, use the return statement:
Example
• def my_function(x):
• return 5 * x
• print(my_function(3))
• print(my_function(5))
• print(my_function(9))