Advertisement
jspill

webinar-functions-2020-06-12.py

Jun 12th, 2021
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.31 KB | None | 0 0
  1. # webinar functions and methods in Python
  2.  
  3. # You'll start getting to know functions in Ch 7
  4.  
  5. # functions should be modular and reusable
  6. # we define a function once and call it as many times as needed
  7.  
  8. # defining a function
  9. def myFunction(parameter1, parameter2):
  10.     # indented block for my function
  11.     # print() a value..
  12.     print(parameter1, parameter2)
  13.     # or return someValue instead, we'll do that next time
  14.  
  15. myFunction("Hey", "There")
  16. myFunction("Goodbye", "... now")
  17. print(myFunction("Hey", "There")) # this will also output "None", b/c I printed a call to a function with no return
  18.  
  19. # function definition, Gallant
  20. def squareThis(num):
  21.     return num * num # RETURN means the function calls evaluate to and give back this new value
  22.  
  23. # ... but you don't SEE a returned value, unless you print() the call itself
  24. print(squareThis(5)) # 25
  25. # because we returned this time, we can use calls to this function in assignment statements
  26. x = squareThis(6) # 36... but not until I print it
  27. print(x)
  28. x = 10 + squareThis(7) # 59
  29. print(x)
  30.  
  31. # Note that if the function prints instead of returning, you can't use that for assignment or other expressions
  32. # Related: printing a call to a function with no return statement will show NONE in output
  33.  
  34. # bad function from Goofus
  35. def squareSomething(num):
  36.     num = 5 # don't do this!
  37.     return num * num
  38.  
  39. print("Gallant vs Goofus: ")
  40. print(squareThis(8)) # 64
  41. print(squareSomething(8)) # 64? Nope it's value is 25
  42. print(squareThis(3)) # 9
  43. print(squareSomething(3)) # 9? Nope it's value is still 25
  44.  
  45. # Don't overwrite your parameters like Goofus!
  46.  
  47. # Pay close attention on the exam to whether a question asks you
  48. # to RETURN or to PRINT() a value from the function.
  49.  
  50. # If you see "None" in your output, you called print() when you should have returned!
  51.  
  52. # You'll be getting to know various methods of common data types in Ch 8 and beyond
  53. # METHODS of a data type or "class" are just functions that belong to that type
  54. myList = [1, 2, 3, 4, 5, 3]
  55. # nameOfObject.method()
  56. count = myList.count(3) # this .count() is a list method, other types don't have it!
  57. print(count) # 2
  58. print(myList.count(3)) # or I can print the call, because .count() returns something
  59. # help(list) # the built-in function help() will show me a help doc on a data type, including its methods
  60.  
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement