0% found this document useful (0 votes)
7 views

Code Reusability

The document discusses code reusability through functions in programming. It covers defining and using built-in functions as well as creating custom functions. Functions allow storing reusable code that can be called from different parts of a program to reduce repetition and improve maintainability.

Uploaded by

divyagoyal891
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Code Reusability

The document discusses code reusability through functions in programming. It covers defining and using built-in functions as well as creating custom functions. Functions allow storing reusable code that can be called from different parts of a program to reduce repetition and improve maintainability.

Uploaded by

divyagoyal891
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

1 May 2024

CT4029
Principles of Programming

Week 3
Code Reusability, Functions
Learning Outcomes

 Code reusability through functions


 Using built-in functions
 Creating and using new functions
 Passing arguments in functions

2
Today’s Agenda!

• Functions
• Built-In Functions
• Type conversion (int, float)
• Math functions (sin, sqrt)
• Build Your Own Function
• Arguments & Parameters

3
Functions

4
Functions

“A function is a unit of code that is often defined by its role within a greater
code structure. Specifically, a function contains a unit of code that works on
various inputs, many of which are variables, and produces concrete results
involving changes to variable values or actual operations based on the inputs.”
- Techopedia

5
Functions - Operation

• If you have operations that are performed in various different parts of the program,
then it makes sense to remove the repeated code and create a separate function or
procedure that can be called from those places instead.
• Not only will this reduce the size of your program, but it will make the code easier to
maintain, and it will remove the possibility that some of the code segments are
updated, but not others.
• Functions eliminate the code repetition
• Encourage code reusability

6
Stored (and reused) Steps
def hello(): Program:
print Output:
(“Hello”) def thing():
print (“Fun”) print (“Hello”)
print (“Fun”) Hello
hello() Fun
thing()
Print(“Zip”) Zip
print (“Zip”) thing()
Hello
Fun
hello()

We call these reusable pieces of code “functions”


7
Python Functions

• There are two kinds of functions in Python.


• Built-in functions that are provided as part of Python - input(), type(),
float(), int() ...
• Functions that we define ourselves and then use
• We treat the of the built-in function names as reserved words (i.e. we
avoid them as variable names)

8
Built-in Functions

9
Function Definition (1/2)

• In Python a function is some reusable code that takes arguments(s) as input


does some computation and then returns a result or results
• We define a function using the def reserved word
• We call/invoke the function by using the function name, parenthesis and
arguments in an expression

10
Function Definition (2/2)

Argument

big = max(“Hello world”)

Assignment 'w'
Result
>>> big = max(“Hello world”)
>>> print (big)
>>> small = min(“Hello world”)
>>> print (small)>>>

11
Max Function (1/2)

A function is some stored code that


we use. A function takes some input
>>> big = max(“Hello world”) and produces an output.
>>> print (big)

“Hello world” max() ‘w’


(a string)
(a string) function

12
Max Function (2/2)

A function is some stored code that


we use. A function takes some input
>>> big = max(“Hello world”) and produces an output.
>>> print (big)

def max(inp):
blah
“Hello world” blah ‘w’
(a string) for x in y: (a string)
blah
blah

13
Type Conversions
>>> print (float(99) / 100)
0.99
• When you put an integer and floating >>> i = 42
point in an expression the integer is >>> type(i)
<type 'int'>
implicitly converted to a float >>> f = float(i)
• You can control this with the built in >>> print (f)
42.0
functions int() and float() >>> type(f)
<type 'float'>
>>> print (1 + 2 * float(3) / 4 – 5)
-2.5

14
String Conversions >>> sval = '123'
>>> type(sval)
<type 'str'>
• You can also use int() and float() >>> print (sval + 1)
Traceback (most recent call last):
to convert between strings and File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int'
integers >>> ival = int(sval)
>>> type(ival)
• You will get an error if the string <type 'int'>
>>> print (ival + 1)
does not contain numeric 124
>>> nsv = 'hello bob'
characters >>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
15
Functions - Operation
>>> num1 = 4 num1 = 4
>>> num2 = 6 num2 = 6
>>> total = num1 + num2
>>> print (total) def add():
sum = num1 + num2
print (sum)
add() add()

Output: Output:
10 10

16
Functions - Operation
>>> num1 = 4 num1 = 4
>>> num2 = 6 num2 = 6
>>> total = num1 + num2
>>> print (total) def add():
sum = num1 + num2
>>> num1 = 5 print (sum)
>>> num2 = 10 add() add()
>>> total = num1 + num2
>>> print (total) num1 = 5
num2 = 10
add()

Output: Output:
15 15

17
Build Your Own Functions

18
Building our Own Functions

• We create a new function using the def keyword followed by optional


parameters in parenthesis.
• We indent the body of the function
• This defines the function but does not execute the body of the function

def print_lyrics():
print ("I'm a lumberjack, and I'm okay.”)
print (“I sleep all night and I work all day.”)

19
Example

x=5
print (“Hello”)

def print_lyrics(): Output:


print ("I'm a lumberjack, and I’m okay.”)
print (“I sleep all night and I work all day.”) Hello
Yo
print (“Yo”) 7
x=x+2
print (x)

20
Definitions and Uses

• Once we have defined a function, we can call (or invoke) it as many times
as we like
• This is the store and reuse pattern

21
Example
x=5
print (“Hello”)

def print_lyrics():
Output:
print ("I'm a lumberjack, and I’m okay.”) Hello
print (“I sleep all night and I work all day.”) Yo
7
print (“Yo”) I'm a lumberjack, and I'm okay.
x=x+2
I sleep all night and I work all day.
print (x)
print_lyrics()

22
Arguments and Parameters

23
Arguments

• An argument is a value we pass into the function as its input when we call
the function
• We use arguments so we can direct the function to do different kinds of
work when we call it at different times
• We put the arguments in parenthesis after the name of the function

big = max(“Hello world”)


Argument
24
Parameters >>> def greet(lang):
if lang == 'es’:
print (“Hola”)
A parameter is a variable which we use elif lang == ‘fr’:
in the function definition that is a print (“Bonjour”)
“handle” that allows the code in the else:
function to access the arguments for a print (“Hello”)
particular function invocation.
>>> greet('en’)
Hello
>>> greet('es’)
Hola
>>> greet('fr’)
Bonjour

25
Return Values

• Often a function will take its arguments, do some computation and return a
value to be used as the value of the function call in the calling expression.
The return keyword is used for this.

Output:
def greet():
return "Hello” Hello Sam
Hello Becky
print (greet(), ”Sam”)
print (greet(), ”Becky”)

26
Return Value >>> def greet(lang):
if lang == 'es’:
return 'Hola’
• A “fruitful” function is one that produces elif lang == 'fr’:
a result (or return value) return 'Bonjour’
else:
• The return statement ends the function return 'Hello’
>>> print (greet('en’),”Glenn”)
execution and “sends back” the result of
Hello Glenn
the function >>> print (greet('es’),”Sally”)
Hola Sally
>>> print (greet('fr’),”Michael”)
Bonjour Michael

27
Arguments, Parameters, and Results

>>> big = max(“Hello world”) Parameter


>>> print (big)
def max(inp):
blah
“Hello world” blah ‘w’
for x in y:
Argument blah
Result
blah
return ‘w’

28
Multiple Parameters / Arguments

• We can define more than one parameter in the function definition


• We simply add more arguments when we call the function
• We match the number and order of arguments and parameters

def addtwo(a, b):


added = a + b Output:
return added 8
x = addtwo(3, 5)
print (x)

29
Void (non-fruitful) Functions

• When a function does not return a value, we call it a "void" function


• Functions that return values are "fruitful" functions
• Void functions are "not fruitful"

30
To function or not to function...

• Organize your code into “paragraphs” - capture a complete thought and


“name it”
• Don’t repeat yourself - make it work once and then reuse it
• If something gets too long or complex, break up logical chunks and put
those chunks in functions
• Make a library of common stuff that you do over and over - perhaps share
this with your friends...

31
Next Session!

• Basics of Graphical User Interface in Python


• We will be focusing on Tkinter

32
33

You might also like