Python Function Arguments

At the end of Python Lists and For Loops, we had a small script that printed out the days of the week to the cmd prompt.

Printing the days of the week is a lot like printing the colours of the rainbow, or the lyrics of a song. The process, or algorithm, is the same.

Step through each item in the list, and print it to the cmd prompt.

The only part of our function that is 'days of the week' specific at the moment is the days_of_week list

Ok, the function name is quite 'days of the week' like, but that's no biggie.

Refactoring and Accepting a Parameter

Lets update, or refactor, our printing function to make it more generic. By updating the existing code, we could create a function that prints any list.

What is that weird (my_list) bit between the function name, print_my_list, and the colon?

You might remember I said that a function does something. Often, a function does something to something. In our script our function prints my_list.

Passing a Parameter

What's my_list though........?

Whatever we want it to be!

We get to decide when we call the print_my_list function.

In our script we've chosen to give the print_my_list function the days_of_week list.

We could have given it any list.

Go Do Something

You won't learn Python, or programming in general, by just reading tutorials. You actually need to get your hands dirty.

So...the task for this chapter is to update the above script to print the colours of the rainbow!

Here's a hint, you only need to update (at most) 2 lines of code. Remember to run your script and check the output.

Have a coffee first though. What's the rush?

Python Comments and Reading Files

Please Share

If you found this useful, please share with friends.

comments powered by Disqus