0% found this document useful (0 votes)
20 views30 pages

Pertemuan Ke 6

The document discusses functions in Python, explaining that functions allow you to organize your code into reusable blocks and simplify repetitive tasks. It provides examples of built-in functions, user-defined functions, and parameterized functions that accept arguments. Functions can make code more modular, readable, and maintainable by isolating different tasks and logic into well-defined units.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views30 pages

Pertemuan Ke 6

The document discusses functions in Python, explaining that functions allow you to organize your code into reusable blocks and simplify repetitive tasks. It provides examples of built-in functions, user-defined functions, and parameterized functions that accept arguments. Functions can make code more modular, readable, and maintainable by isolating different tasks and logic into well-defined units.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Pemrograman

Sistem Jaringan
Pertemuan 6 – 31 Oktober 2020
Functions
Agenda
• Defining and using functions;
• Different ways of passing arguments;
Why do we need functions?
• You've come across functions many times so far, but the view on their merits that we have given you has
been rather one-sided. You've only invoked the functions by using them as tools to make life easier, and to
simplify time-consuming and tedious tasks.

• When you want some data to be printed on the console, you use print(). When you want to read the value of
a variable, you use input(), coupled with either int() or float().

• You've also made use of some methods, which are in fact functions, but declared in a very specific way.

• Now you'll learn how to write your own functions, and how to use them. We'll write several functions together,
from the very simple to the rather complex, which will require your focus and attention.

• It often happens that a particular piece of code is repeated many times in your program. It's repeated either
literally, or with only a few minor modifications, consisting of the use of other variables in the same algorithm. It
also happens that a programmer cannot resist simplifying the work, and begins to clone such pieces of code
using the clipboard and copy-paste operations.

• It could end up as greatly frustrating when suddenly it turns out that there was an error in the cloned code.
The programmer will have a lot of drudgery to find all the places that need corrections. There's also a high risk
of the corrections causing errors.

• We can now define the first condition which can help you decide when to start writing your own functions: if
a particular fragment of the code begins to appear in more than one place, consider the possibility of
isolating it in the form of a function invoked from the points where the original code was placed before.
• You can try to cope with the issue by commenting the code extensively,
but soon you find that this dramatically worsens your situation - too many
comments make the code larger and harder to read. Some say that
a well-written function should be viewed entirely in one glance.
• A good and attentive developer divides the code (or more accurately:
the problem) into well-isolated pieces, and encodes each of them in the
form of a function.
• This considerably simplifies the work of the program, because each
piece of code can be encoded separately, and tested separately. The
process described here is often called decomposition.
Where do the functions come from?
• In general, functions come from at least three places:
• from Python itself - numerous functions (like print()) are an integral part of Python,
and are always available without any additional effort on behalf of the
programmer; we call these functions built-in functions;
• from Python's preinstalled modules - a lot of functions, very useful ones, but used
significantly less often than built-in ones, are available in a number of modules
installed together with Python; the use of these functions requires some additional
steps from the programmer in order to make them fully accessible (we'll tell you
about this in a while);
• directly from your code - you can write your own functions, place them inside
your code, and use them freely;
• there is one other possibility, but it's connected with classes, so we'll omit it for
now.
Your first function
• It's rather simple, but we only want it to be an example of transforming a repeating part
of a code into a function.
• The messages sent to the console by the print() function are always the same. Of course,
there's nothing really bad in such a code, but try to imagine what you would have to do if
your boss asked you to change the message to make it more polite, e.g., to start it with
the phrase "Please,".
• It seems that you'd have to spend some time changing all the occurrences of the
message (you'd use a clipboard, of course, but it wouldn't make your life much easier). It's
obvious that you'd probably make some mistakes during the amendment process, and
you (and your boss) would get a bit frustrated.
• Is it possible to separate such a repeatable part of the code, name it and make it
reusable? It would mean that a change made once in one place would be propagated
to all the places where it's used.
• Of course, such a code should work only when it's explicitly launched.
• Yes, it's possible. This is exactly what functions are for.
Your first function - Continue
Take a look at the snippet in the editor.
print("Enter a value: ")
a = int(input())
print("Enter a value: ") def message():
b = int(input()) print("Enter a value: ")
print("Enter a value: ") message()
c = int(input()) a = int(input())
message()
b = int(input())
message()
c = int(input())
Summary
1. A function is a block of code that performs a specific task when the function
is called (invoked). You can use functions to make your code reusable,
better organized, and more readable. Functions can have parameters and
return values.
2. There are at least four basic types of functions in Python:
– built-in functions which are an integral part of Python (such as the print() function). You
can see a complete list of Python built-in functions at
https://docs.python.org/3/library/functions.html.
– the ones that come from pre-installed modules (you'll learn about them in Module 5 of
this course)
– user-defined functions which are written by users for users - you can write your own
functions and use them freely in your code,
– the lambda functions (you'll learn about them in Module 6 of this course.)

• 3. You can define your own function using the def keyword and the following
syntax:
Summary - 2
3. You can define your own function using the def keyword and the following
syntax:
def yourFunction(optional parameters):
# the body of the function

You can define a function which doesn't take any arguments, e.g.:
def message(): # defining a function
print("Hello") # body of the function
message() # calling the function

You can define a function which takes arguments, too, just like the one-parameter
function below:
def hello(name): # defining a function
print("Hello,", name) # body of the function
name = input("Enter your name: ")
hello(name) # calling the function
Exercise
1. The input() function is an example of a:
a) user-defined function
b) built-in function

2. What happens when you try to invoke a function before you define it?
Example:
hi()
def hi():
print("hi!")
Exercise
1. The input() function is an example of a:
a) user-defined function
b) built-in function
b - it's a built-in function

2. What happens when you try to invoke a function before you define it? Example:
hi()
def hi():
print("hi!")

An exception is thrown (the NameError exception to be more precise)


Exercise
3. What will happen when you run the code below?
def hi():
print("hi")
hi(5)
Exercise
3. What will happen when you run the code below?
def hi():
print("hi")
hi(5)

An exception will be thrown (the TypeError exception to be more


precise) - the hi() function doesn't take any arguments
Parametrized functions
• The function's full power reveals itself when it can be equipped with an
interface that is able to accept data provided by the invoker. Such data
can modify the function's behavior, making it more flexible and
adaptable to changing conditions.
• A parameter is actually a variable, but there are two important factors
that make parameters different and special:
– parameters exist only inside functions in which they have been defined, and the only
place where the parameter can be defined is a space between a pair of
parentheses in the def statement;
– assigning a value to the parameter is done at the time of the function's invocation,
by specifying the corresponding argument.
– def function(parameter):
###
Parametrized functions
• The definition specifies that our function operates on just one parameter
named number. You can use it as an ordinary variable, but only inside the
function - it isn't visible anywhere else.
• Let's now improve the function's body:
def message(number):
print("Enter a number:", number)

• A value for the parameter will arrive from the function's environment.
• Remember: specifying one or more parameters in a function's definition is
also a requirement, and you have to fulfil it during invocation. You
must provide as many arguments as there are defined parameters.
• Failure to do so will cause an error.
Parametrized functions
def message(number):
print("Enter a number:", number)
message()

Traceback (most recent call last):


File "main.py", line 4, in <module>
message()
TypeError: message() missing 1 required positional argument: 'number'
Parametrized functions
def message(number):
print("Enter a number:", number)
number = 1234
message(1)
It's legal, and possible, to have a variable
print(number) named the same as a function's
parameter.
Output: The parameter named number is a
Enter a number: 1 completely different entity from the
variable named number.
1234
Parametrized functions
A function can have as many parameters as you want, but the more parameters
you have, the harder it is to memorize their roles and purposes.
def message(what, number):
print("Enter", what, "number", number)
Example:
def message(what, number):
print("Enter", what, "number", number)
message("telephone", 11) Output:
Enter telephone number 11
message("price", 5)
Enter price number 5
message("number", "number") Enter number number number
Positional parameter passing
• A technique which assigns the ith (first, second, and so on) argument to the
ith (first, second, and so on) function parameter is called positional
parameter passing, while arguments passed in this way are named
positional arguments.

• You've used it already, but Python can offer a lot more. We're going to tell
you about it now.
def myFunction(a, b, c):
print(a, b, c)
myFunction(1, 2, 3)
Positional parameter passing
def introduction(firstName, lastName):
print("Hello, my name is", firstName, lastName)

introduction("Luke", "Skywalker")
introduction("James", “Bond")
introduction("Clark", "Kent")

Output:
Hello, my name is Luke Skywalker
Hello, my name is James Bond
Hello, my name is Clark Kent
Keyword argument passing
def introduction(firstName, lastName):
print("Hello, my name is", firstName, lastName)

introduction(firstName = "James", lastName = "Bond")


introduction(lastName = "Skywalker", firstName = "Luke")
Positional and Keyword Arguments
def adding(a, b, c):
print(a, "+", b, "+", c, "=", a + b + c)
adding(1, 2, 3)
Output: 1 + 2 + 3 = 6
adding(3, c = 1, b = 2)
Output: 3 + 2 + 1 = 6
adding(3, a = 1, b = 2)
TypeError: adding() got multiple values for argument 'a'
Tebak Output - 1
def intro(a="James Bond", b="Bond"):
print("My name is", b + ".", a + ".")
intro()
Tebak Output - 1
def intro(a="James Bond", b="Bond"):
print("My name is", b + ".", a + ".")
intro()

Output:
My name is Bond. James Bond.
Tebak Output - 2
def intro(a="James Bond", b="Bond"):
print("My name is", b + ".", a + ".")

intro(b="Sean Connery")
Tebak Output - 2
def intro(a="James Bond", b="Bond"):
print("My name is", b + ".", a + ".")

intro(b="Sean Connery")

Output:
My name is Sean Connery. James Bond.
Tebak Output - 3
def intro(a, b="Bond"):
print("My name is", b + ".", a + ".")

intro("Susan")
Tebak Output - 3
def intro(a, b="Bond"):
print("My name is", b + ".", a + ".")

intro("Susan")

Output:
My name is Bond. Susan.
Tebak Output - 4
def sum(a, b=2, c):
print(a + b + c)

sum(a=1, c=3)
Tebak Output - 4
def sum(a, b=2, c):
print(a + b + c)

sum(a=1, c=3)

Output:
SyntaxError - a non-default argument (c) follows a default
argument (b=2)

You might also like