SlideShare a Scribd company logo
WELCOME TO SI
SI LEADER: CALEB PEACOCK
HOW ARE YOU FEELINGS SO FAR?
• You just completed your first test, and are roughly 1/4th to 1/3rd through the semester. Congratulations,
how are you feeling? Not feeling on solid footing is normal. I once asked the professor towards the end
of the semester “When did it click for you?” and she replied at the end of her second semester in CSC.
Meaning, keep going. If you don’t have command, don’t feel bad. It’s really hard, just keep practing
and learning, and it will come.
• This powerpoint will be about functions. It is a very basic introduction to get you comfortable with the
idea, and give you comfortability with the topic as you tackle the reading, quiz, and labs. As always,
reach out to me, or the professor, with questions about the topic.
FUNCTIONS
• A function is a block of code which only runs when it is called.
• You “call” variables all the time when you reference them later on in your code. A function is similarly called, but it’s a block
of code rather than a single value.
• You can pass data, known as parameters, into a function.
• print() is a built in function of python. You call it by referencing it and passing your own data through it. print(“I am passing
data through the print function”)
• A function can return data as a result. In the print function’s case, it’s returns the data you see on screen. There’s many
types of functions that serves many different roles.
• Lets jus think about what we know about functions in math. You put something into a function, and you get an output. In
python we can design our own functions. They’re extremely useful, and like variables can be called upon effortlessly.
CREATING A FUNCTION
• In Python a function is defined using the def keyword:
• For example:
• def my_function():
print(“This is my function")
• def is like if for decisions or while for loops, it is the header. Notice how it also ends with a colon :
• In our example we name our function my_function. Functions, like variables, have the exact same
naming requirements.
• Just like if/else, or loops, INDENT AFTER THE HEADER. The statements below your function header
belong to that function and only that function. Unless you call the function by referencing it, the code
will not execute.
CALLING FUNCTIONS
• To call a function, use the function name followed by parenthesis:
• For example,
• def my_function():
• print(“This is my function")
my_function()
As you can see, it does not execute unless we call it. This is incredibly useful. If you have complex
calculations in your code, or a giant block of code, it can be called with just the name of a function. This
saves space, time, and speed. Again, its like a variable in which its values can be easily called, but It can
store a lot more values.
PARAMETER VARIABLES
• An parameter variable is any information that can be passed through a function.
• Paramter variables are specified after the function name, inside the parentheses. You can add as many
parameter variables as you want, just separate them with a comma.
• The following example has a function with one paramater (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 + " Peacock")
• my_function(“Colson")
• my_function(“Zachary")
• my_function(“Brittany")
Again, the argument is fname(first name). Then we pass along our values after for that argument. Then
the print function takes what we passed through for fname, and concatenates that with the string
“peacock”.
# OF PARAMETER VARIABLES
• 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. We saw in the second slide, there does not have to be an argument. And
theoretically, there can be an unlimited amount. It just has to match up.
• Example
• This function expects 3 arguments, and gets 3arguments:
• def my_function(fname, lname, eyeColor):
• print(fname + " " + lname+” “+eyeColor)
• my_function(“Caleb", “Peacock“, “has blue eyes”)
• If you try to call the function with 1 or 2 arguments, you will get an error.
ARBITRARY ARGUMENTS
• 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:
def my_function(*sibling):
print("The youngest sibling is " + sibling[3])
my_function(“Brittany", “Zachary", “Colson“, “Caleb”)
Delete the star(*) from the argument “sibling”. What happens? Why?
When not sure how many arguments are going to be passed through your function, * is a good bet.
DEFAULT PARAMETER VALUE
• The following example shows how to use a default parameter value.
• If we call the function without argument, it uses the default value:
• For example,
• def my_function(country = "Norway"):
• print("I am from " + country)
• my_function("Sweden")
• my_function("India")
• my_function()
• my_function("Brazil")
As you can see, we can pass whatever values we want through the argument or parameter variable. It’s only expecting one value, and we can put
whatever country we want. If we leave empty (), it defaults to the default value to the parameter, “Norway”.
RETURN VALUES
• Arithmetic!!! Let’s get into it. I think this is the really cool part of functions and why they are so useful. Let’s say we want to calculate the trajectory of a rocket, but
multiple times with different launching angles, fuel capacity, weight of the rocket, etc. These are all parameter variables we could pass through the function of
determining a rockets trajectory. Now, I am not a rocket scientist and do not know how to calculate that, but if I were, I could easily write the equation once at the
beginning of my code, and then just call that equation using a function passing different variables such as angle and weight and I will get an answer immediately.
• To let a function return a value, use the return statement:
• def my_function(x):
• return 5 * x
• print(my_function(3))
• print(my_function(5))
• print(my_function(9))
Output? You will be using return A LOT, so memorize it! It returns whatever you pass through the arguments. So it’s returning 5* 3(what you passed through the x
argument).
LETS WRITE A FUNCTION TOGETHER
• Lets write a function. Keep it simple. Lets just calculate the sum of two integers. How would we do
that?
• We need the start the function with a key word def, followed by the function name, parameters(if any),
and then a colon.
• def calculate_sum(x,y):
• We start off with def, name our function to something that can tell a general user what the function
does, and then we name our two parameter variables, x and y
WRITING A FUNCTION TOGETHER
• def calculate_sum(x,y):
Now what? Well we need to write the code for the function. How do you calculate sum? Lets take the
two parameter variables, x and y, and incorporate them to calculate our sum.
def calculate_sum(x,y):
return (x+y)
Now, our function is complete!!! We just need to call our function. How do we do that?
AVERAGE FUNCTION
• How would we write a function that takes 3 values, and finds the average of the values?
Create the function definition starting off with def
Def average_function(x,y,z):
We named our function something easily recognizable, we created our 3 parameter variables x,y,z, and
ended with a :
AVERAGE FUNCTION
• def average_function(x,y,z):
Next we have to write our code! What would be the equation for finding the average of 3 numbers?
Return that equation back to the function.
Lets take a look at it in eclipse.
MAIN FUNCTION
• When defining and using functions in Python, it is good programming practice to place all statements
into functions, and to specify one function as the starting point
• • Any legal name can be used for the starting point, but we chose ‘main’ since it is the required function
name used by other common languages
• • Of course, we must have one statement in the program that calls the main function
MAIN FUNCTION
• def main():
• answer=average_function(2,5,8)
• print("The average is %.1f" % answer)
• def average_function(x,y,z):
• return (x+y+z)
Without the main function this would not execute because I have not yet defined the average function.
The main function allows the program to keep running until it defines the average function, thus executing
the block of code at the top.
Q&A
• Any questions about this chapter, powerpoint, previous lessons, or anything coding related, please ask!
If I do not know, or if one of us is not satisfied with our answer, I will consult with the professor and get
back to you.
• Remember, please give yourself multiple,multiple hours to do the zylabs. You need time to work on
them, you need time to work through being stuck for hours as well. Remember, we are learning, and
they are meant to be hard.
• You may be tempted to cheat, but if you are actually taking this class as your major, just think about
your future and what cheating on a lab will do for your career. Nothing. At. All. The labs are hard,
Computer Science is really hard. It gets easier. Find solace in the fact everyone is struggling with you,
and learning with you, and that while struggling now, 6 months from now you will look at some of these
labs and think they’re a piece of cake.

More Related Content

Similar to powerpoint 2-7.pptx

Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
Sartaj Singh
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
Raghu Kumar
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
Michael Heron
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
Mohammad Hassan
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
arvdexamsection
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
Chiyoung Song
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
MalligaarjunanN
 
Function
FunctionFunction
CPP07 - Scope
CPP07 - ScopeCPP07 - Scope
CPP07 - Scope
Michael Heron
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki304759
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 
ACM init()- Day 4
ACM init()- Day 4ACM init()- Day 4
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdf
zafar578075
 
python.pdf
python.pdfpython.pdf
python.pdf
BurugollaRavi1
 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
Jeongbae Oh
 
PYTHON PROGRAMMING (2).pptx
PYTHON PROGRAMMING (2).pptxPYTHON PROGRAMMING (2).pptx
PYTHON PROGRAMMING (2).pptx
SoundariyaSathish
 

Similar to powerpoint 2-7.pptx (20)

Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
 
Function
FunctionFunction
Function
 
CPP07 - Scope
CPP07 - ScopeCPP07 - Scope
CPP07 - Scope
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
ACM init()- Day 4
ACM init()- Day 4ACM init()- Day 4
ACM init()- Day 4
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdf
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
 
PYTHON PROGRAMMING (2).pptx
PYTHON PROGRAMMING (2).pptxPYTHON PROGRAMMING (2).pptx
PYTHON PROGRAMMING (2).pptx
 

Recently uploaded

Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 

Recently uploaded (20)

Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 

powerpoint 2-7.pptx

  • 1. WELCOME TO SI SI LEADER: CALEB PEACOCK
  • 2. HOW ARE YOU FEELINGS SO FAR? • You just completed your first test, and are roughly 1/4th to 1/3rd through the semester. Congratulations, how are you feeling? Not feeling on solid footing is normal. I once asked the professor towards the end of the semester “When did it click for you?” and she replied at the end of her second semester in CSC. Meaning, keep going. If you don’t have command, don’t feel bad. It’s really hard, just keep practing and learning, and it will come. • This powerpoint will be about functions. It is a very basic introduction to get you comfortable with the idea, and give you comfortability with the topic as you tackle the reading, quiz, and labs. As always, reach out to me, or the professor, with questions about the topic.
  • 3. FUNCTIONS • A function is a block of code which only runs when it is called. • You “call” variables all the time when you reference them later on in your code. A function is similarly called, but it’s a block of code rather than a single value. • You can pass data, known as parameters, into a function. • print() is a built in function of python. You call it by referencing it and passing your own data through it. print(“I am passing data through the print function”) • A function can return data as a result. In the print function’s case, it’s returns the data you see on screen. There’s many types of functions that serves many different roles. • Lets jus think about what we know about functions in math. You put something into a function, and you get an output. In python we can design our own functions. They’re extremely useful, and like variables can be called upon effortlessly.
  • 4. CREATING A FUNCTION • In Python a function is defined using the def keyword: • For example: • def my_function(): print(“This is my function") • def is like if for decisions or while for loops, it is the header. Notice how it also ends with a colon : • In our example we name our function my_function. Functions, like variables, have the exact same naming requirements. • Just like if/else, or loops, INDENT AFTER THE HEADER. The statements below your function header belong to that function and only that function. Unless you call the function by referencing it, the code will not execute.
  • 5. CALLING FUNCTIONS • To call a function, use the function name followed by parenthesis: • For example, • def my_function(): • print(“This is my function") my_function() As you can see, it does not execute unless we call it. This is incredibly useful. If you have complex calculations in your code, or a giant block of code, it can be called with just the name of a function. This saves space, time, and speed. Again, its like a variable in which its values can be easily called, but It can store a lot more values.
  • 6. PARAMETER VARIABLES • An parameter variable is any information that can be passed through a function. • Paramter variables are specified after the function name, inside the parentheses. You can add as many parameter variables as you want, just separate them with a comma. • The following example has a function with one paramater (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
  • 7. • def my_function(fname): • print(fname + " Peacock") • my_function(“Colson") • my_function(“Zachary") • my_function(“Brittany") Again, the argument is fname(first name). Then we pass along our values after for that argument. Then the print function takes what we passed through for fname, and concatenates that with the string “peacock”.
  • 8. # OF PARAMETER VARIABLES • 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. We saw in the second slide, there does not have to be an argument. And theoretically, there can be an unlimited amount. It just has to match up. • Example • This function expects 3 arguments, and gets 3arguments: • def my_function(fname, lname, eyeColor): • print(fname + " " + lname+” “+eyeColor) • my_function(“Caleb", “Peacock“, “has blue eyes”) • If you try to call the function with 1 or 2 arguments, you will get an error.
  • 9. ARBITRARY ARGUMENTS • 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: def my_function(*sibling): print("The youngest sibling is " + sibling[3]) my_function(“Brittany", “Zachary", “Colson“, “Caleb”) Delete the star(*) from the argument “sibling”. What happens? Why? When not sure how many arguments are going to be passed through your function, * is a good bet.
  • 10. DEFAULT PARAMETER VALUE • The following example shows how to use a default parameter value. • If we call the function without argument, it uses the default value: • For example, • def my_function(country = "Norway"): • print("I am from " + country) • my_function("Sweden") • my_function("India") • my_function() • my_function("Brazil") As you can see, we can pass whatever values we want through the argument or parameter variable. It’s only expecting one value, and we can put whatever country we want. If we leave empty (), it defaults to the default value to the parameter, “Norway”.
  • 11. RETURN VALUES • Arithmetic!!! Let’s get into it. I think this is the really cool part of functions and why they are so useful. Let’s say we want to calculate the trajectory of a rocket, but multiple times with different launching angles, fuel capacity, weight of the rocket, etc. These are all parameter variables we could pass through the function of determining a rockets trajectory. Now, I am not a rocket scientist and do not know how to calculate that, but if I were, I could easily write the equation once at the beginning of my code, and then just call that equation using a function passing different variables such as angle and weight and I will get an answer immediately. • To let a function return a value, use the return statement: • def my_function(x): • return 5 * x • print(my_function(3)) • print(my_function(5)) • print(my_function(9)) Output? You will be using return A LOT, so memorize it! It returns whatever you pass through the arguments. So it’s returning 5* 3(what you passed through the x argument).
  • 12. LETS WRITE A FUNCTION TOGETHER • Lets write a function. Keep it simple. Lets just calculate the sum of two integers. How would we do that? • We need the start the function with a key word def, followed by the function name, parameters(if any), and then a colon. • def calculate_sum(x,y): • We start off with def, name our function to something that can tell a general user what the function does, and then we name our two parameter variables, x and y
  • 13. WRITING A FUNCTION TOGETHER • def calculate_sum(x,y): Now what? Well we need to write the code for the function. How do you calculate sum? Lets take the two parameter variables, x and y, and incorporate them to calculate our sum. def calculate_sum(x,y): return (x+y) Now, our function is complete!!! We just need to call our function. How do we do that?
  • 14. AVERAGE FUNCTION • How would we write a function that takes 3 values, and finds the average of the values? Create the function definition starting off with def Def average_function(x,y,z): We named our function something easily recognizable, we created our 3 parameter variables x,y,z, and ended with a :
  • 15. AVERAGE FUNCTION • def average_function(x,y,z): Next we have to write our code! What would be the equation for finding the average of 3 numbers? Return that equation back to the function. Lets take a look at it in eclipse.
  • 16. MAIN FUNCTION • When defining and using functions in Python, it is good programming practice to place all statements into functions, and to specify one function as the starting point • • Any legal name can be used for the starting point, but we chose ‘main’ since it is the required function name used by other common languages • • Of course, we must have one statement in the program that calls the main function
  • 17. MAIN FUNCTION • def main(): • answer=average_function(2,5,8) • print("The average is %.1f" % answer) • def average_function(x,y,z): • return (x+y+z) Without the main function this would not execute because I have not yet defined the average function. The main function allows the program to keep running until it defines the average function, thus executing the block of code at the top.
  • 18. Q&A • Any questions about this chapter, powerpoint, previous lessons, or anything coding related, please ask! If I do not know, or if one of us is not satisfied with our answer, I will consult with the professor and get back to you. • Remember, please give yourself multiple,multiple hours to do the zylabs. You need time to work on them, you need time to work through being stuck for hours as well. Remember, we are learning, and they are meant to be hard. • You may be tempted to cheat, but if you are actually taking this class as your major, just think about your future and what cheating on a lab will do for your career. Nothing. At. All. The labs are hard, Computer Science is really hard. It gets easier. Find solace in the fact everyone is struggling with you, and learning with you, and that while struggling now, 6 months from now you will look at some of these labs and think they’re a piece of cake.