Skip to content

Instantly share code, notes, and snippets.

@AKST
Created September 5, 2019 03:16
Show Gist options
  • Save AKST/c4fe5c9c8af37cb5f419cec8956db2b0 to your computer and use it in GitHub Desktop.
Save AKST/c4fe5c9c8af37cb5f419cec8956db2b0 to your computer and use it in GitHub Desktop.
def example_function(x, y, z):
return (x + y) * z
print(example_function(1, 2, 3)) # prints 9
print(example_function(1, 2, z=3)) # prints 9
print(example_function(x=1, y=2, z=3)) # prints 9
# will break your program, because positional arguments are
# used after keyword arguments.
#
# > Positional arguments are function arguments/parameters
# specified based on the order passed to the function.
# Basically normal function arguments.
print(example_function(x=1, y=2, 3))
def greeting(name, times=1):
for i in range(0, times):
print("Hello %s" % name)
# all prints
# > "Hello Jeff"
# > "Hello Jeff"
greeting("Jeff", 2)
greeting("Jeff", times=2)
greeting(name="Jeff", times=2)
greeting(times=2, name="Jeff")
# these will all print
# > "Hello Jeff"
greeting("Jeff")
greeting("Jeff", times=1)
greeting(name="Jeff", times=1)
greeting(times=1, name="Jeff")
# this will cause an error since greeting
# doesn't have a named parameter for language
greeting("Jeff", 2, language="en")
# you can define functions that allows any
# keyword argument like this.
def greeting_2(name, **options):
# note that options will be a dictionary, like this:
# https://docs.python.org/3/tutorial/datastructures.html#dictionaries
for i in range(0, options.get('times', 1)):
print("Hello %s" % name)
# this will not break but, the argument for language
# will be ignored. However in the function, options
# will be dictionary that will look like this.
#
# options = { "times": 2, "langauge": "en" }
greeting_2("Jeff", times=2, language="en")
# however this will no longer work, since
# times cannot be provided as a positional
# argument.
greeting_2("Jeff", 2)
# a neat thing with a function that has the keyword
# arguments is you can pass in a dictionary like this
greeting_options = { "times": 2, "language": "en" }
greeting_2("Jeff", **greeting_options)
# or even like this, since there is a function called
# name, it be give the value "Jeff", the rest of the
# values will be give to the options argument.
greeting_options = { "name": "Jeff", "times": 2 }
greeting_2(**greeting_options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment