Advertisement
woootiness

functions in python

Jan 23rd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. ################
  2. ## Functions
  3. ################
  4.  
  5. # Use "def" to create new functions
  6. def add(x, y):
  7.     print("x is {} and y is {}".format(x, y))
  8.     return x + y  # Return values with a return statement
  9.  
  10. # Calling functions with parameters
  11. add(5, 6)  # => prints out "x is 5 and y is 6" and returns 11
  12.  
  13. # Another way to call functions is with keyword arguments
  14. add(y=6, x=5)  # Keyword arguments can arrive in any order.
  15.  
  16. # You can define functions that take a variable number of
  17. # positional arguments
  18. def varargs(*args):
  19.     return args
  20.  
  21. varargs(1, 2, 3)  # => (1, 2, 3)
  22.  
  23. # You can define functions that take a variable number of
  24. # keyword arguments, as well
  25. def keyword_args(**kwargs):
  26.     return kwargs
  27.  
  28. # Let's call it to see what happens
  29. keyword_args(big="foot", loch="ness")  # => {"big": "foot", "loch": "ness"}
  30.  
  31.  
  32. # You can do both at once, if you like
  33. def all_the_args(*args, **kwargs):
  34.     print(args)
  35.     print(kwargs)
  36. """
  37. all_the_args(1, 2, a=3, b=4) prints:
  38.    (1, 2)
  39.    {"a": 3, "b": 4}
  40. """
  41.  
  42. # When calling functions, you can do the opposite of args/kwargs!
  43. # Use * to expand tuples and use ** to expand kwargs.
  44. args = (1, 2, 3, 4)
  45. kwargs = {"a": 3, "b": 4}
  46. all_the_args(*args)            # equivalent to foo(1, 2, 3, 4)
  47. all_the_args(**kwargs)         # equivalent to foo(a=3, b=4)
  48. all_the_args(*args, **kwargs)  # equivalent to foo(1, 2, 3, 4, a=3, b=4)
  49.  
  50. # Returning multiple values (with tuple assignments)
  51. def swap(x, y):
  52.     return y, x  # Return multiple values as a tuple without the parenthesis.
  53.                  # (Note: parenthesis have been excluded but can be included)
  54.  
  55. x = 1
  56. y = 2
  57. x, y = swap(x, y)     # => x = 2, y = 1
  58. # (x, y) = swap(x,y)  # Again parenthesis have been excluded but can be included.
  59.  
  60. # Function Scope
  61. x = 5
  62.  
  63. def set_x(num):
  64.     # Local var x not the same as global variable x
  65.     x = num    # => 43
  66.     print (x)  # => 43
  67.  
  68. def set_global_x(num):
  69.     global x
  70.     print (x)  # => 5
  71.     x = num    # global var x is now set to 6
  72.     print (x)  # => 6
  73.  
  74. set_x(43)
  75. set_global_x(6)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement