498 Home Syllabus Schedule Mikecz Home Tutorials

Python Basics: Working with Data 1 (Variables, Control Flows, and Lists)

Notes: view the previous lesson if you still need to install Python through the Miniconda package.

Setup

You should create a folder where you will save all your Python programs for this class.

Basic Math, Strings, Lists

First we will learn how to use Python to work with numbers, strings, and variables. For these exercises, you can enter code in the console (usually on the lower right corner of Spyder) or you can enter several lines of code into the editor where you can run several lines of code at the same time.

For further information review: python.org Lesson 3

  1. Working with variables:

    1. 1 equal sign assigns a value. Thus, in the code below, we are assigning the variable x the value of 18.

      
      x=18
      
    2. test this by entering the following code in your Python console:

      
      x=18
      print(x)
      type(x)
      x+12
      x+'abc'
      
    3. Run the following code. Can you figure out the difference between the following operands (*, **, /, //, %)?

      
      18+4
      18*4
      18**4
      18/4
      18//4
      18%4
      
    4. As x is an integer (type ‘int’), note how you can add other integers to it (or perform any mathematical calculation). However, you can not add it to a string (type ‘str’). Now try entering this in your console.

      
      y='fire'
      z='fighter'
      y+13
      y+z
      a=y+z
      print(a)
      len(a)
      
    5. With strings you can also retrieve substrings. Can you figure out what the following lines of code are doing?

      
      sent=" This is a particularly normal sentence.\n"
      
      sent[0]
      sent[0:5]
      sent[10:17]
      sent[:3]
      sent[3:]
      sent[-3:]
      sent[-6:-3]
      
      
    6. Let’s strip out the excess whitespace at the start and end of this sentence (‘’ indicates a line break).

      
      sent.strip()
      
    7. However, that just showed us the result. To save the new sentence, you need to assign it to a variable:

      
      sent2=sent.strip()
      print(sent)
      print(sent2)
      
    8. Now, let us split the sentence into words. We can use the split() function for that.

      
      words=sent2.split()
      print(words)
      
    9. Now, let us retrieve only the first four words:

      
      importantWords=words[0:4]
      print(importantWords)
      

exercise

  1. Store the following paragraph in a variable (you can copy and paste it in Python). Alternatively, you may copy a different paragraph from a text of your own choosing:

    
    "Latin America is at peace.  Civil wars have ended.  Insurgencies have been pushed back.  Old border disputes have been resolved.  In Colombia, great sacrifices by citizens and security forces have restored a level of security not seen in decades."
    
  2. Now, write code that extracts only the first 20 characters of the paragraph.

  3. Add a new sentence to the end of this new string.

if and for statements

If, else if (‘elif’ in Python), and else statements allow you to apply particular actions only under specific circumstances that you specify. For example, you can write a program that applies a tax to a product only if it costs more than $20.

For loops allows you to run a program repeatedly over a list or series of data.

These if statements and for loops are called control flows. For documentation on control flows, see: python.org Lesson 4

if statements

exercise

Write a similar program as the one above, but this time identifying all numbers that are odd.

Ways to store data

If you want to work with data in Python, you need to learn the different structures Python provides for the storing - and, therefore, analysis - of data. These include:

To learn more about data structures, see Python.org

Variables

  1. create the following variables

    
    x="Peru"
    y=1532
    
  2. check types

    type(x)
    type(y)
  3. combine “Peru” and “1532” into one string:

    ##try
    y+100
    x+y ##should receive an error
    
    # convert y to a string
    y=str(y)
    x+y
    

Lists

For more on Python lists, click here

  1. create a blank list

    
    l=[]
    
  2. create a populated list:

    
    k=[5,3,22,17,7]
    
  3. iterate over list:

    
    sum=0
    for i in k:
        sum+=i
    print(sum)
    
  4. sort list

    
    sorted(k)
    sorted(-k)
    k=sorted(k)
    
  5. get length of list

    
    len(k)
    
  6. add one item to a list

    
    k.append(16)
    k=sorted(k)
    
  7. create new list. Combine lists

    
    j=[77,83,4,62,41,77,77,33,6]
    
    l=j+k
    
    l2=j.extend(k)
    
    if l1==l2:
        print(True)
    
  8. reverse order of list

    
    l=l.reverse()
    

exercise

Complete the following tasks with Python lists. Write this code as a program in the editor. After each task, print the results. An example for numbers one and two are provided.

  1. create a list of your top 5 favorite tv shows (or you can do movies, books, video games, etc.)

    tvfavs=['Mork and Mindy','Laverne and Shirley','Murder, She Wrote','The Fresh Prince of Bel-Air','Miami Vice']
    print(tvfavs)
  2. Now print the list, one item at a time:

    for fav in tvfavs:
        print(fav) ##note you need to indent within a for loop
  3. add a 6th tv show to the end of your list. Review the examples above and the link here if you forget how to do any of this.

  4. Rethink your list. Replace one of the items with a show that you may prefer.

  5. Add 4 more shows you enjoyed as a child.

  6. sort the list alphabetically. Use Python’s sorted() function.

  7. create a copy of the list

  8. for the copy list:

    1. remove the last show

    2. remove the third show in the list

  9. Extra Credit: Write a for loop that creates a new list, but this time truncating each show’s name to a maximum of 10 characters.