module 3

Cards (44)

  • Data structure
    Allows multiple pieces of data to be stored in some form of organised structure
  • Data structures
    • The structure may be as simple as a "collection of values", but can be much more complex (ordering, names, hierarchy...)
    • Like a data type, a data structure defines what the language can do with it - adding/removing items, sorting them, etc.
    • A variable can refer to a data structure, i.e. a variable can contain many values, implementing a data structure the language knows
  • Array
    An ordered collection of values
  • Arrays
    • The items in the array have a set position - "the third item in the array" will always refer to the same value
    • The values themselves are not necessarily ordered - the first item could contain a value of 5 and the second could contain a value of 2
    • The number or value of items may be fixed ("immutable"), or may be able to change ("mutable")
    • The data types of items in an array may need to all be the same type, or can be different
  • Storing multiple values in a data structure (e.g. an array)

    • You can sort the values, count them or identify duplicate values
    • Determine the maximum or minimum value
    • Determine if a certain value exists in the array
  • Referring to an item in an array
    • By its index, i.e. the position of the item in the array, using "[]" after the variable
    • The index starts at 0, so an array of 5 values has indexes 0-4
  • Why did the programmer quit his job? Because he didn't get arrays.
  • Lists
    • An ordered data structure in Python, created with []
    • Mutable, i.e. you can add, remove or change items
  • Tuples
    • An ordered data structure in Python, created with ()
    • Immutable, i.e. you cannot add, remove or change items
  • Referring to items in lists and tuples
    • Using variable[index] to refer to an item
    • Negative indexes refer to items from the end
    • You can refer to multiple items at once (known as "slicing")
    • You can do this (except changing values) on strings, since strings are essentially just sequences of characters - a tuple of characters
  • List methods
    • len(my_list) - count how many items are in the list
    • my_list.append(42) - add an item of 42 to the end of the list
    • my_list.count(42) - count how many items in the list are equal to 42
    • my_list.insert(2, 18) - insert an item of 18 at index 2 of the list
    • my_list.index(42) - return the index of first item with a value of 42
    • my_list.remove(42) - remove the first item with a value of 42
    • del my_list[1] - remove the item with an index of 1 from the list
    • my_list.sort() - sort the items in the list
  • The "in" comparison operator
    • Allows you to check if a value exists in a data structure (e.g. a list or tuple - or even a string)
    • You can use "not in" to check if a value is not in a data structure
  • Data structures allow you to store multiple pieces of data as items in a single unit, in an organised way
  • Strings share a number of similarities with data structures like lists and tuples
  • Iteration (Loops)
    • Statements that allow the program to repeatedly run a block of code
    • The code that is repeatedly run is known as the "body" of the loop
    • Loops are typically controlled by either a counter or a condition - they run a certain number of times, or while a condition is met
  • While loop
    • A condition-controlled loop that repeats the loop body while the loop condition is True
    • The condition is checked before each repetition of the body
    • If the condition is False, the body is not run and the loop ends
  • The loop body should do something that will eventually make the condition False, otherwise the loop will never end
  • Common loop errors include "off by one" errors in the loop condition, incorrect statements in or out the loop body, and repeating something that only needs to run once or vice-versa
  • Why did the programmer get stuck in the shower? Because the instructions on the shampoo bottle said "Lather, Rinse, Repeat"
  • While loop example 1: Repeatedly prompt for numbers to add until 0 is entered
    1. Initialise number with None and total with 0
    2. While number is not 0:
    Get a number from the user
    Add the number to the total
    3. Print the total
  • While loop example 2: Repeatedly prompt for text and concatenate it until the length of the concatenated text exceeds 10 characters
    Create an empty string variable called 'text'
    While the length of 'text' is less than or equal to 10:
    Prompt the user for some text
    Concatenate the user's input to 'text'
    Print the current 'text' and its length
  • Break
    Ends the loop right away, moving on to the next statement after the loop
  • Continue
    Skips the rest of the loop body and then continues with the next iteration (check the condition, run loop body if True...)
  • Break example 1: Rewriting the previous example using break and an infinite loop
    Initialise total to 0
    While True (infinite loop):
    Get a number from the user
    If the number is 0, break out of the loop
    Add the number to the total
    Print the total
  • Break example 2: Using break to control an infinite loop, exiting when a condition is met
    While True (infinite loop):
    Get a value in pounds from the user (or 'x' to exit)
    If the value is 'x', break out of the loop
    Convert the value to kilograms and print the result
  • Continue example 1: Enhancing the previous example to ignore invalid input
    While True (infinite loop):
    Get a value in pounds from the user (or 'x' to exit)
    If the value is 'x', break out of the loop
    If the value is not a number, print an error message and continue to the next iteration
    Convert the value to kilograms and print the result
  • number
    Variable initialised to None to leave it empty
  • total
    Variable initialised to 0 so we can add to it later
  • While loop
    1. Enter a number (0 to exit)
    2. Add the entered number to the total
    3. Print the total
  • Break
    Used to exit an infinite loop when a condition is met
  • Break Example 2
    1. Prompt user for value in pounds (x to exit)
    2. If value is 'x', break out of loop
    3. Multiply the value by 0.454
    4. Show the result on the screen
  • Continue Example 1
    1. Prompt user for value in pounds (x to exit)
    2. If value is 'x', break out of loop
    3. If value is not a number, print 'Invalid input - Try again' and continue to next iteration
    4. Multiply the value by 0.454
    5. Show the result on the screen
  • Try/Except
    Try to execute a statement, do this if an error occurs
  • Do-While loop
    Checks the condition after the loop body, so the body is run at least once
  • Do-While Example
    1. Generate a random number between 1 and 5
    2. Prompt user for a guess
    3. Repeat until guess matches the number
    4. Congratulate user
  • Python does not provide a do-while loop
  • While vs. Do-While
    1. While loop: Check condition before loop body
    2. Do-While loop: Check condition after loop body
  • For loop
    Typically used when the number of iterations is known in advance
  • Counter-controlled For loop
    Iterates through a sequence, assigning each item to a variable
  • Python For Loop Examples
    • Looping through a list
    • Looping through a tuple
    • Looping through a string