4 Going on a picnic: Working with lists

 

Writing code makes me hungry! Let’s write a program to consider some tasty foods we’d like to eat. So far we’ve handled one of something like a name to say "hello" to or a nautical-themed object to point out. In this program, we want to eat one or more foods which we will store in a list, a variable that can hold any number of items. We use lists all the time in life. Maybe it’s your top-five favorite songs, your birthday wish-list, or a bucket list of the best types of buckets.

In this exercise, we’re going on a picnic, and we want to print a list of items to bring. You will learn to:

  • Write a program that accepts multiple positional arguments.
  • Use if, elif, and else to handle conditional branching with three or more options.
  • Find and alter items in a list.
  • Sort and reverse lists.
  • Format a list into a new string.

The items will be passed as positional arguments. When there is only one item, you’ll print that:

$ ./picnic.py salad
You are bringing salad.
salad
salad and chips

What? Who just brings salad on a picnic? When there are two items, you’ll put "and" in between them:

$ ./picnic.py salad chips
You are bringing salad and chips.

Hmm, chips. That’s an improvement. When there are three or more items, you will separate the items with commas:

$ ./picnic.py salad chips cupcakes
You are bringing salad, chips, and cupcakes.
salad chips and cupcakes

4.1  Starting the program