4 Some Python Basics

A Quick Summary

  1. Use # to write comments.
  2. Python is case sensitive.
  3. x is not the same as ‘x’.
  4. = is not the same as ==.
  5. Be careful about indentaions at the start of a line.
  6. Add functionalit by using packages.
    • E.g. import numpy as np
  7. . indicates ownership.
    • E.g. np.sum() means the sum() function belonging to numpy.
  8. You can store data as list or numpy arrays.
  9. Access elements of a list using [2:3].
  10. Get help by using ?.

4.1 Before the Workshop

This chapter will quickly introduce you to some basic of Python. You need to:

  1. Watch the two videos (4 mins and 12 mins) videos in below.
    • We have also shared Colab notebook relevant to the video.
  2. Work on the short exercises shown below on Colab.
    • The solution to the exercises can also be found below.
    • This should take you about 20 minutes.

4.2 Exercises & Video File

Videos

Getting started with Colab (3.5 mins)

Some Python Basics (12 mins)

Video (Colab file)

Basic Exercises

Create a new notebook in Colab and use it to answer the following questions.

  1. Predict the output of the following code blocks? Run them in Colab to check if your predictions were correct?

    Note: You might have to look on the internet for the meaning of some symbols (such as / and %)

    1.    7 / 3 == 7 / 3.0
    2. 'nesia' in 'Indonesia'
    3. (2 + 3) == 5
    4.  2 + 3 == 5
    5.  "2" + "3" == "5"
    6.  11 % 3
    7.  1 < 2 and 11 >= 9
    8.  2 > 5 or (1 < 2 and 11 >= 9)
  2. Hello Batman & Robin

    name = 'Batman'
    
    if name == 'Batman':
       print('Hello Batman!')
    else:
       print('Hello World!')
    1. Modify the above code to print ‘Hello Hello Hello Hello Batman’ when the name is ‘Batman.’
    2. Modify the code to respond to Robin instead of Batman.
  3. The following code has a few bugs; fix them!

    x,y = 3,4
        z = sqrt(x**2 + y**2)
        print(x,y,z)
  4. Use the following lists and numpy arrays to answer the following questions

    my_np_list = np.array([0182, 0269, 0341, 0410, 0523,
                           0697, 0728, 0856, 0948, 101,
                           1120, 1272, 1312, 1460, 1564,
                           1642, 1717, 1816, 1923, 2087])               
    1. What is the number in the 4th position in the array?
    2. What is the last number in the array?
    3. What are the first 3 values?
    4. What are the values from the 4th to the 10th position? (This should include the numbers at the 4th and 10th positions.)
    5. What are the values in the list greater than 500?
    6. Use the ‘hidden’ numpy functions max(), min(), mean() and std() to find the maximum, minimum, mean and standard deviation of the values of the numpy array.
    7. Make all the numbers less than 500 equal to zero!
    8. What are the values in the list greater than 500 and less than 1000?

Basic Exercises (Solution)