Functions in Python: Difference between revisions

From Computer Science Wiki
 
(45 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[File:220px-Function machine2.svg.png|right|frame|A function f takes an input x, and returns a single output f(x). One metaphor describes the function as a "machine" or "black box" that for each input returns a corresponding output.<ref>https://en.wikipedia.org/wiki/Function_(mathematics)</ref>]]
==Introduction==
==Introduction==


Line 4: Line 6:


Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks. <ref>http://www.webopedia.com/TERM/F/function.html</ref>
Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks. <ref>http://www.webopedia.com/TERM/F/function.html</ref>
We use function so we don't need to repeat ourselves. Please watch the video below and remember the content.
<html>
<iframe width="560" height="315" src="https://www.youtube.com/embed/Pi0Yf-jn7O8" frameborder="0" allowfullscreen></iframe>
</html>
Content gratefully used with permission :  <ref>http://cs50.tv/2015/fall/#license,psets</ref>
== The difference between returning and printing ==
Students often print from within a function. Please understand the difference between printing a result from a function and returning a result from a function.
<code>print</code>: gives the value to the user as an output string. print(3) would give a string '3' to the screen for the user to view. The program would lose the value.
<code>return</code>: gives the value to the program. Callers of the function then have the actual data and data type (bool, int, etc...) return 3 would have the value 3 put in place of where the function was called.<ref>http://stackoverflow.com/questions/3881434/difference-between-returns-and-printing-in-python</ref>


==Example of a function==
==Example of a function==
Line 12: Line 29:
#
#


def welcome(name):
def likes_burger(name):
     if name == "Alisher":
     if name == "Alisher":
         likes_hamburgers ="yes"
         likes_hamburgers ="yes"
Line 19: Line 36:
     return likes_hamburgers
     return likes_hamburgers
      
      
print welcome("Bill")
print likes_burger("Bill")
print welcome("Alisher")     
print likes_burger("Alisher")     
print welcome("foo")
print likes_burger("foo")
</syntaxhighlight>
 
==Another classic example of a function==
 
<syntaxhighlight lang="python">
#
# this is a simple function
#
 
def calculator(number1, number2):
    answer = number1 + number2
    return answer
   
print calculator(12,43)
print calculator(91,673)
print calculator(1,3)
print calculator(87,1098)
 
</syntaxhighlight>
 
== Some decent videos about functions in Python ==
In the video to the left, the programmer uses a different [[IDE]] than we do (we use canopy). The programmer also uses [[tests]] in this video, which we haven't covered yet. The video on the right is pretty good example of what a function is, and also discusses [[variable scope]]
 
<html>
<iframe width="560" height="315" src="https://www.youtube.com/embed/Qa5DDqzHh3g" frameborder="0" allowfullscreen></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/qO4ZN5uZSVg" frameborder="0" allowfullscreen></iframe>
</html>
 
== Do you understand functions? ==
 
=== Beginning level functions ===
 
# Write a function which accepts one parameter (a string) and returns the parameter (string) in uppercase
# Write a function which accepts a string and returns the string capitalized
# Write a function that accepts 2 numbers and returns the sum
# Write a function that accepts 2 numbers and returns the quotient
# Write a function that accepts 2 numbers and returns the product
# Write a function that accepts 2 numbers and returns the difference
 
=== Average level difficulty ===
 
1. Write a function that accepts two arguments. A name (as string) and a nice greeting (as a string). Your function should return a full sentence.
for example print my_function("joe","happy birthday")
returns -> Joe, I'd like to wish you a very happy birthday!
 
2. write a function that returns an ascii-art number ([http://patorjk.com/software/taag/#p=testall&f=Graffiti&t=1234567890 please click here to get the ascii numbers])
  for example: print my_number(132)
  would return:
 
                                       
                        .--,-``-.   
      ,---,      ,----,  /  /    '. 
  ,`--.' |    .'  .' \/ ../        ; 
  /    /  :  ,----,'    \ ``\  .`-    '
:    |.' '  |    :  .  ;\___\/  \  :
`----':  |  ;    |.'  /      \  :  |
    '  ' ;  `----'/  ;      /  /  / 
    |  | |    /  ;  /        \  \  \ 
    '  : ;  ;  /  /-,  ___ /  :  |
    |  | '  /  /  /.`|  /  /\  /  :
    '  : |./__;      : / ,,/  ',-    .
    ;  |.'|  :    .'  \ ''\        ; 
    '---'  ;  | .'      \  \    .' 
          `---'          `--`-,,-'
 
3. Write a function that takes a string and returns the letters shifted 2 spaces to the right.
  for example: encode("abcdefg")
  would return: cdefghi
 
 
4. Write a function that takes an integer and RETURNS a word which corresponds to that integer.
  for example description_of_monster(1)
  would return: Fluffy
 
<syntaxhighlight lang="python">
def description_of_monster(value):
    if value == 1:
        return "fluffy"
    elif value == 2:
        return "spikey"
    elif value == 3:
        return "slimy"
    else:
        return "scary"
       
                   
print("One day, as I was walking along, I saw a " + description_of_monster(2) + " monster!")
print("As you peek around the dark corner, you see a  " + description_of_monster(6) + " monster!")
print("I don't really like " + description_of_monster(1) + " monsters.")
</syntaxhighlight>
</syntaxhighlight>
=== Expert level difficulty ===
A common mechanic in computer games is to simulate a dice roll. [[:media:Dice.jpeg|Click here to request an image of commonly used dice]]. Please write a function that rolls dice for you and RETURNS the result.
  for example: roll_dice(d6,3) <-- would roll a six sided die 3 times and return the result
  for example: roll_dice(d12,1) <-- would roll a 12 sided dice 1 and return the result
  for example: roll_dice(d20,4)  <-- would roll a 20 sided die 4 times and return the result.
  You should model a 4 sided, 6 sided, 10 sided, 12 sided, and 20 sided die.
  As extra-credit, you might want to return the result of each roll and then the final total.
  for example: roll_dice(d6,3) <-- might return 6 3 1 10


==References==
==References==


<references />
<references />
[[Category:Python]]
[[Category:Functions]]
[[Category:Basic Programming]]

Latest revision as of 07:46, 19 September 2021

A function f takes an input x, and returns a single output f(x). One metaphor describes the function as a "machine" or "black box" that for each input returns a corresponding output.[1]

Introduction[edit]

In programming, a named section of a program that performs a specific task. In this sense, a function is a type of procedure or routine. Some programming languages make a distinction between a function, which returns a value, and a procedure, which performs some operation but does not return a value.

Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks. [2]

We use function so we don't need to repeat ourselves. Please watch the video below and remember the content.


Content gratefully used with permission : [3]

The difference between returning and printing[edit]

Students often print from within a function. Please understand the difference between printing a result from a function and returning a result from a function.

print: gives the value to the user as an output string. print(3) would give a string '3' to the screen for the user to view. The program would lose the value.

return: gives the value to the program. Callers of the function then have the actual data and data type (bool, int, etc...) return 3 would have the value 3 put in place of where the function was called.[4]

Example of a function[edit]

#
# this is a simple function
#

def likes_burger(name):
    if name == "Alisher":
        likes_hamburgers ="yes"
    else:
        likes_hamburgers="no"
    return likes_hamburgers
    
print likes_burger("Bill")
print likes_burger("Alisher")    
print likes_burger("foo")

Another classic example of a function[edit]

#
# this is a simple function
#

def calculator(number1, number2):
    answer = number1 + number2
    return answer
    
print calculator(12,43)
print calculator(91,673)
print calculator(1,3)
print calculator(87,1098)

Some decent videos about functions in Python[edit]

In the video to the left, the programmer uses a different IDE than we do (we use canopy). The programmer also uses tests in this video, which we haven't covered yet. The video on the right is pretty good example of what a function is, and also discusses variable scope

Do you understand functions?[edit]

Beginning level functions[edit]

  1. Write a function which accepts one parameter (a string) and returns the parameter (string) in uppercase
  2. Write a function which accepts a string and returns the string capitalized
  3. Write a function that accepts 2 numbers and returns the sum
  4. Write a function that accepts 2 numbers and returns the quotient
  5. Write a function that accepts 2 numbers and returns the product
  6. Write a function that accepts 2 numbers and returns the difference

Average level difficulty[edit]

1. Write a function that accepts two arguments. A name (as string) and a nice greeting (as a string). Your function should return a full sentence.

for example print my_function("joe","happy birthday")
returns -> Joe, I'd like to wish you a very happy birthday!

2. write a function that returns an ascii-art number (please click here to get the ascii numbers)

 for example: print my_number(132)
 would return: 


                        .--,-``-.     
     ,---,      ,----,  /   /     '.   
  ,`--.' |    .'   .' \/ ../        ;  
 /    /  :  ,----,'    \ ``\  .`-    ' 
:    |.' '  |    :  .  ;\___\/   \   : 
`----':  |  ;    |.'  /      \   :   | 
   '   ' ;  `----'/  ;       /  /   /  
   |   | |    /  ;  /        \  \   \  
   '   : ;   ;  /  /-,   ___ /   :   | 
   |   | '  /  /  /.`|  /   /\   /   : 
   '   : |./__;      : / ,,/  ',-    . 
   ;   |.'|   :    .'  \ \        ;  
   '---'  ;   | .'      \   \     .'   
          `---'          `--`-,,-'

3. Write a function that takes a string and returns the letters shifted 2 spaces to the right.

 for example: encode("abcdefg")
 would return: cdefghi


4. Write a function that takes an integer and RETURNS a word which corresponds to that integer.

 for example description_of_monster(1)
 would return: Fluffy
def description_of_monster(value):
    if value == 1:
        return "fluffy"
    elif value == 2:
        return "spikey"
    elif value == 3:
        return "slimy"
    else:
         return "scary"
         
                     
print("One day, as I was walking along, I saw a " + description_of_monster(2) + " monster!") 
print("As you peek around the dark corner, you see a  " + description_of_monster(6) + " monster!") 
print("I don't really like " + description_of_monster(1) + " monsters.")

Expert level difficulty[edit]

A common mechanic in computer games is to simulate a dice roll. Click here to request an image of commonly used dice. Please write a function that rolls dice for you and RETURNS the result.

 for example: roll_dice(d6,3) <-- would roll a six sided die 3 times and return the result
 for example: roll_dice(d12,1) <-- would roll a 12 sided dice 1 and return the result
 for example: roll_dice(d20,4)  <-- would roll a 20 sided die 4 times and return the result. 
  You should model a 4 sided, 6 sided, 10 sided, 12 sided, and 20 sided die. 
 As extra-credit, you might want to return the result of each roll and then the final total. 
 for example: roll_dice(d6,3) <-- might return 6 3 1 10

References[edit]