Sample Code
food = ["Sausage", "eggs", "Bacon", "Beans"]
pupils = ["John", "Jill", "Emily", "Satpal"]
scores = [5,3,6,7,9,1,2]
days = ["Sunday","Monday","Tuesday","Wednesday","Thursday", "Friday","Saturday"]
# Print all the days
for day in days:
print(day)
#print eggs
print(food[1])
#print Emily, Satpal
print(pupils[2:])
#print Tuesday, Wednesday
print (days[2:4])
#print John, Jill
print(pupils[:2])
#print Friday
print(days[-2])
print(len(days))
print(max(scores))
print(min(scores))
if "John" in pupils:
print("Pupil is present")
else:
print ("Pupil absent")
pupils = pupils + ["Arthur"]
print(pupils)
Exercises
The following questions refer to the sample code. You can type the code into IDLE and run it to help you figure out the answer
- Look at the print(food[ 1 ]) line. What does the [ 1] do?
- How would you print the first item in the list?
- If a python list has seven items, what would number would the seventh item be?
- Look at the print(pupils[2:]) line. What does [2:] mean?
- Look at the print(days[2:4])line. What does [2:4] mean?
- Look at the print(days[-2]) line. What does [-2] mean?
- What does len do?
- What do max and min do?
Now write your own modules to do the following
- Create a list called months, containing the months in the year.
- Print out all the months, one after the other
- Use slicing (e.g. days[2:4]) to print out the spring months: March, April, May
- Print out the summer months: June, July, August
- Print out the first and last months of the year
- Print out the winter months: December, January and February
Extension: Research
Use a search engine and online manuals to find out how to get Python to do the following
- Reverse the following list: [“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”, “Friday”,”Saturday”] i.e. print out “Saturday”,”Friday”,”Thursday”,… etc
- Remove “eggs” from this list food = [“Sausage”, “eggs”, “Bacon”, “Beans”]
- Sort the following list into ascending order scores = [5,3,6,7,9,1,2]
- Insert “Mushrooms” into this list, just after “eggs”
- Count how many times “blue” appears in this list [“red”,”blue”,”blue”,”blue”,”red”,”blue”]