4 Some Python Basics
A Quick Summary
- Use
#
to write comments. - Python is case sensitive.
-
x
is not the same as‘x’
. -
=
is not the same as==
. - Be careful about indentaions at the start of a line.
- Add functionalit by using packages.
- E.g.
import numpy as np
- E.g.
-
.
indicates ownership.- E.g.
np.sum()
means thesum()
function belonging to numpy.
- E.g.
- You can store data as list or numpy arrays.
- Access elements of a list using
[2:3]
. - Get help by using
?
.
4.1 Before the Workshop
This chapter will quickly introduce you to some basic of Python. You need to:
- Watch the two videos (4 mins and 12 mins) videos in below.
- We have also shared Colab notebook relevant to the video.
- 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
Basic Exercises
Create a new notebook in Colab and use it to answer the following questions.
-
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%
)7 / 3 == 7 / 3.0
'nesia' in 'Indonesia'
(2 + 3) == 5
2 + 3 == 5
"2" + "3" == "5"
11 % 3
1 < 2 and 11 >= 9
2 > 5 or (1 < 2 and 11 >= 9)
-
Hello Batman & Robin
= 'Batman' name if name == 'Batman': print('Hello Batman!') else: print('Hello World!')
- Modify the above code to print ‘
Hello Hello Hello Hello Batman
’ when thename
is ‘Batman
.’ - Modify the code to respond to
Robin
instead ofBatman
.
- Modify the above code to print ‘
-
The following code has a few bugs; fix them!
= 3,4 x,y = sqrt(x**2 + y**2) z print(x,y,z)
-
Use the following lists and numpy arrays to answer the following questions
= np.array([0182, 0269, 0341, 0410, 0523, my_np_list 0697, 0728, 0856, 0948, 101, 1120, 1272, 1312, 1460, 1564, 1642, 1717, 1816, 1923, 2087])
- What is the number in the 4th position in the array?
- What is the last number in the array?
- What are the first 3 values?
- What are the values from the 4th to the 10th position? (This should include the numbers at the 4th and 10th positions.)
- What are the values in the list greater than 500?
- Use the ‘hidden’ numpy functions
max()
,min()
,mean()
andstd()
to find the maximum, minimum, mean and standard deviation of the values of the numpy array. - Make all the numbers less than 500 equal to zero!
- What are the values in the list greater than 500 and less than 1000?