Python Lists and For Loops

If you've followed on from Python Functions and If Statements, you might recall I asked you to "Write a Python script that prints the days of the week".

Did you do it?

You should have ended up with something that (roughly) looks like this:

days_of_the_week_easy.py

def print_days_of_week():
  print 'Monday'
  print 'Tuesday'
  print 'Wednesday'
  print 'Thursday'
  print 'Friday'
  print 'Saturday'
  print 'Sunday'

def main():
  print_days_of_week()

if __name__ == '__main__':
  main()

Don't worry if yours isn't the same. There's various ways you could have completed the task. For example, you might have just dumped all the print statements in main.

The main point is, did it work?

You should have run this at the cmd line, and got output similar to the following:

Smashing, lets move on.

Stop Repeating Things

Nobody likes repetitive tasks. So copying and pasting (or typing in) all of those print statements and changing the day was a bit naff.

Lets see a different way of doing it.

days_of_week.py

def print_days_of_week():
  days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
	
  for day in days_of_week:
    print day

def main():
  print_days_of_week()

if __name__ == '__main__':
  main()

The above script does exactly the same thing as the one at the begginning of this chapter. It does however use 2 components you haven't seen before.

Python Lists

A list is just a collection of items.

In this script our list is a collection of the days_of_week .

Python For Loops

A loop just repeats itself until its told to stop.

In this script we just repeat ourselves until we've seen every day in the day_of_week list.

Each time the loop repeats day is given a different value.

So the first time it has the value 'Monday', the second time 'Tuesday' and so on..

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 your existing program to look like the one above.

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

Python Function Arguments

Please Share

If you found this useful, please share with friends.

comments powered by Disqus

Subscribe