SlideShare une entreprise Scribd logo
1  sur  18
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.

Contenu connexe

Similaire à powerpoint 2-7.pptx

Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional ProgrammingSartaj Singh
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu 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.pdfSudhanshiBakre1
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like PythonistaChiyoung Song
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
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 tuplesMalligaarjunanN
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and commentMalligaarjunanN
 
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_argumentsRuth Marvin
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
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.pdfzafar578075
 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionJeongbae Oh
 

Similaire à 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
 

Dernier

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Dernier (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 

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.