Monday, 16 June 2014

Lists and for loops

Learning aims

To be able to use lists in a program.

Introduction


lists are declared using square brackets '[]' and assigned to a variable.

A 'for loop' iterates over a sequence.  A sequence can be a list, range or string. iterating means it works through each member of the list and does the same thing to it.

Task 1

code 1
Type in the above code.  Save and run after each print command - Explain what is happening after each print command.

Questions

  1. What is the command to add something to a list?
Look at https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range. Read down to, but not including section 4.6.2. 
  1. Write the line that would return True if 'm' was in 'yourlist'
  2. Write the line that would return True is m was not in 'yourlist'
  3. What would [2] + [2] be?
  4. What is the index of the a in alphabetlist? (alphabetlist.index('a'))
  5. What does index mean in a list? 

Task 2

The for command also works over a range.



Write and run the above program, save and run after each print command - Explain what is happening after each print command.

Questions

  1. When there is a single number given as the argument in a range function - what does it mean?
  2. When two numbers are given as the arguments to the range function what does each do?
  3. When 3 numbers are given as arguments to the range functioon what does each do?
  4. Write the Range command that would give the output [3,6,9,12,15,18]
  5. Write the Range command that would give the output [5,4,3,2,1]
  6. In the program above i stands for 'iterator'  as the loop 'iterates' accross the range.  What does iterate mean?
  7. Replace all instances of 'i' in lines 5,6,7 with 'randomWord'  What happens?  What is i?

No comments:

Post a Comment