GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing pythonprogramming.net — Python Programming Tutorials Args and KwargsWelcome to part 25 of the intermediate Python programming tutorial series. In this tutorial, we're going to cover The idea behind blog_1 = 'I am so awesome' blog_2 = 'Cars are cool.' blog_3 = 'Aww look at my cat.' Now, you can have a function that iterates through them and just prints them: def blog_posts(*args):
for post in args:
print(post)
It's very similar to if you were to pass a list as a parameter, then iterated through that list. We can do: blog_posts(blog_1) Output: I am so awesome We can also do: blog_posts(blog_1,blog_2,blog_3) Output: I am so awesome Cars are cool. Aww look at my cat. We can also use def blog_posts_2(regular_arg, *args):
print(regular_arg)
for post in args:
print(post)
blog_posts_2('My blogs:',blog_1,blog_2,blog_3)
Output: My blogs: I am so awesome Cars are cool. Aww look at my cat. Now, there will be many times where you want args that are still assigned to some sort of name, which is where keyword arguments, def blog_posts_3(**kwargs):
for title, post in kwargs.items():
print(title,post)
blog_posts_3(blog_1 = 'I am so awesome',
blog_2 = 'Cars are cool.',
blog_3 = 'Aww look at my cat.')
Output: blog_2 Cars are cool. blog_1 I am so awesome blog_3 Aww look at my cat. Interestingly, you can also use def graph_operation(x, y):
print('function that graphs {} and {}'.format(x, y))
Rather than passing x and y explicitly, we can pass it as args, like: def graph_operation(x, y):
print('function that graphs {} and {}'.format(x, y))
x = [1,2,3]
y = [2,3,1]
graph_me = [x,y]
graph_operation(*graph_me)
Output: function that graphs [1, 2, 3] and [2, 3, 1] If you have matplotlib installed, we can actually graph it: import matplotlib.pyplot as plt
def graph_operation(x, y):
print('function that graphs {} and {}'.format(x, y))
plt.plot(x,y)
plt.show()
x = [1,2,3]
y = [2,3,1]
graph_me = [x,y]
graph_operation(*graph_me)
Output:
|
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |