portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/cs1201_week1_1_201… · web viewget...

19
CSX3001 Fundamentals of Computer Programming, semester 1/2019 Week 1 Compiler vs. Interpreter Throughout this course, Jupyter notebook shall be used as a main programming environment. However, you welcome to use other IDEs, Get started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right side) and choose Python 3 option. A new browser tap is created as shown in the example below.

Upload: others

Post on 10-Oct-2019

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

Week 1

Compiler vs. Interpreter

Throughout this course, Jupyter notebook shall be used as a main programming environment. However, you welcome to use other IDEs,

Get started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right side) and choose Python 3 option.

A new browser tap is created as shown in the example below.

Page 2: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

Try rename your notebook and use the following naming convention.

Yourid_1_2019_week_X

For example,

In the Jupyter notebook cell, type print(“Hello IT students!!!!”) and click run button . The output will immediately be shown below the cell (where you put your code). For example,

Note: Python supports various types of variables such as integer (int), floating point (float), string (str), list, etc. We will gradually investigate each individual variable type.

Complete the following exercises.1)At your screen (Jupyter notebook) cell, try the

followings (enter in the cell and click “run”, one line per cell, and click “run”) and see the results.

Page 3: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

x = 2 * 2 – 3print(x)

y = 50 – 5 * 6) / 4 print(y)

What is a data type of two variables, namely x and y? _______________________________________________

2)Try the following line of codes in each cell, and run19 / 3 # classic division returns a float19 // 3 # floor division discards the fractional part19 % 3 # the % operator returns the remainder of the division6 * 3 + 1 # result * divider + remainder

3)Try (all three lines of code in one Jupyter cell).tax = 12.5 / 100 # float typeprice = 200 # integer typenet = tax * price # this returns a float

String is a list of characters. Anything inside quotes is considered a string in Python, and you can use single or double quotes around your sting like the followings:

message1 = ‘This is a string’message2 = “This is a string”

This flexibility allows you to use quotes and apostrophes within your strings.

Page 4: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

4)Try each of the followings in different cells:message1 = “It isn’t” # string using double quotes.print(message)

message2 = ‘It isn’t’ # string with single quote. This one should get you error message.print(message2)

You can deal with the above error by placing a symbol \ before apostrophes appeared in the string. For example

message2 = ‘It isn\’t’

Adding Whitespace to Strings with Tables or Newlines

In programming, whitespace refers to any nonprinting character, such as spaces, tabs, and end-of-line symbols. You can use whitespace to organize your output so it is easier for users to read. \t to add a tab \n to add a new line

Use \ to tell Python to ignore \t or \n

5)Tryprint(‘My name is John’)print(‘My name is \tJohn’)

print(‘This is the first line.)print(‘This is the second line.’)

Page 5: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

print(‘This is the third line. \nThis is the fourth line.)

print(‘Computer \\n Programming.’)

Stripping Whitespace

Extra whitespace can be confusing in your programs. To programmers ‘Python’ and ‘Python ’ look pretty much the same. But to a program, there are two different strings. This may cause as issue when you want to compare two strings (Same string with and without white space.

Python has .rstrip() method to remove all whitespaces appeared on the right of a string.

.lstrip() # remove all whitespaces appeared on the left side of a string..strip() # remove all whitespaces on both sides.

6)Trymy_language = ' Thai 'print(my_language.rstrip())print(my_language.lstrip())print(my_language.strip())

Merging Strings

In Python, you can simply concatenate strings using +

Page 6: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

symbol.

7)Tryprefix = 'Hell' # prefix is a variable with string type. You can merge/join two strings using +word = prefix + 'o'print(word)

You can also refer to each individual character or a serie of characters in a string by specifying a range (using [start:end]). First character in a string starts at position 0.

print(word[0])print(word[2])

print(word[:2]) # start at position 0 until 1 (2-1, off-by-one principle)print(word[2:5]) # start at position 2 until 4 (5-1)

print(word[:2] + word[2:5])

print('J' + word[1:])

Formatting Your Outputs

You may want to use a variable’s value inside a string

Page 7: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

and print it on the screen. There are a couple of ways you can format your string outputs. For example

You can observe that if you want to add two hero names in a string (line 3), strings (texts) and variables are to be separated by commas. A whitespace is added automatically between strings and variable’s values. That is why you see a whitespace between Thor and . in the first output.

f-strings is introduced in Python 3.6. It makes your output formatting nice and clean. Simply place a variable in { } in your string. Once again you can use either f’ ‘ or f” “ (single or double quotes).

Constants

A constant is like a variable whose value stays the same throughout the life of a program. Python does not have built-in constant types, but in practice Python programmers use all capital letters to indicate a variable should be treated as a constant and never be changed. For example,

PI = 3.14

Page 8: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

MAX_STUDENTS = 30

Introducing Lists

A list is a collection of items in a particular order. A list can includes the letters of the alphabet, the digits from 0 – 9, or strings (e.g., names of all students in a class)

In Python, square brackets ( [ ] ) indicates a list, and individual elements in the list are separated by commas. You can refer to each element in the list by using [ ] with the right index.

From the above code, we formatted two messages using f-strings. Note that double quotes is used in the second message because there is apostrophes in the string. Python will interpret that as a single quote and you will end up getting error message.

In Python, there are methods that is an action performed on a piece of data. In the above example, our piece of data is hero_list[1] (which refers to ‘hulk’ in the list, then we use .title( ) to change letters to title case. That is why you get Hulk for the output.

Page 9: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

.upper() – change all letters to uppercase letters

.lower() – change all letters to lowercase letters

Don’t worry, you will learn over time about other Python methods.

8)Try and observe the resultsnum_list = [3,20,41,710,-92,108] # num_list is a list of integer values print (x)  # print an entire listprint (x[0]) # print the first elementprint (x[1], x[3], x[5]) # print the second, fourth and sixth elements

Based on the list in exercise 8, fill in the blank: x[__] = 710 x[1:] = ______________ x[:4] = ______________ x[__:__] = [20,41] 

Note: x[1: ] # integers from position 1 (included) to the end

x[:4 ] # integer from the beginning to position 4 (excluded)

9)Trywords_list = ['hello', 'good', 'morning', 'bye', 'hi', 'afternoon'] print(words_list[4].title())print (words_list[1].title(), words_list[5])print(words_list[1:4])

Page 10: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

Based on the above list, fill in the blanky[2:] = _________________                                          y[:4] = _________________                                           y[_:_] = ['good', 'morning', 'bye']

Changing, Adding and Removing Elements in a List

A list you create will be dynamic. You can modify, add or remove elements in the list.

To change or modify an element, consider the following example

You can assign a new value to the third item (index = 2) in the list. The output shows that the third element has indeed been changed from ironman to Vision.

To add a new element to the end of a list, we use .append( ). For example, try

hero_list.append(‘Dr. Strange’)print(hero_list)

To add a new element to a specific location, we use .insert(index, value). For example, try

hero_list.insert(2, 'Quicksilver')print(hero_list)

Page 11: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

10) Add two more heroes (of your choice) at the end of the hero_list. Then add two heroes at position 2 and 4 in the list.

To remove an item from a list, you can use

del hero_list[2] # remove an item at a position 2

or

hero_list.pop(2)

The difference is that using del function disallows you to use the removed element. By using pop() method, you can assign the removed element to anther variable. For example,

dead_hero = hero_list.pop(2)print(f”{dead_hero} is dead.”)

Note that .pop() without an index will remove the last item in a list.

11) Create with a list of two heroes from DC Comics Universe (Goggle for DC heroes’ name) 1) Add one hero at the end of the list. 2) Add one more hero at the front of a list. 3) Remove the second hero from a list and 4) modify the first hero to ‘Aquaman’. 5) Print a list.

You can also remove an element from a list by value.

Page 12: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

For example,

Note that the remove() method deletes only the first occurrence of the value you specify. If there is a possibility that value appears more than once in the list, you will need to use loop to make sure all occurrences of the value are removed. We will come back to this when we study about Loop in Python.

Making Numerical Lists

You can define a list containing a range of integer values using a combination of list[] and range() function. For example,

This code creates a list of integer values start from 0 to 9 (off-by-one principle). You if want to start from and end at specific values, you can also do that. For

Page 13: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

example,

You may observe that each element in the list is automatically increased by one. If you want an increment value to be 2 or more, you can also do that by

12) Fill in the blanklist(range(10)), and click runlist(range(0,10,2)), and click run

Fill in the blanklist(range(10)) = _________________________________________ list(range(2,9)) = ________________________________________ list(range(2,15,3)) = ______________________________________ list(range(__,__,__)) = [1,3,5,7,9,11,13] list(range(__,__)) = [11,12,13,14,15] list(range(__,__,__)) = [9,11,13,15,17,19,21,23] list(range(5,0,-2)) = ____________________________________list(range(__,__,__)) = [15, 14, 13, 12, 11, 10]

Defining Range of Values in Python

Page 14: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

From the above exercise, an entire list is printed in one go. If you want to print each individual element, you can apply for-loop such as,

In the first one, we define a list and we use a for-loop to go through the list. Note that end = ‘,’ is to tell Python that each printed output is to be followed by comma.

print() is to print a new line.

In the second one, we define a range in for loop and then print each value out of that range.

Input Formatting

In certain scenarios, you need to take inputs from a user (via keyboard or other I/O). In Python, taking inputs can be easily done by using input() function. For example, try the following in one cell and run.

a = input('a = ') b = input('b = ') print (a, b)print (a+b) # statement 1

a = int(input('a = ')) 

Page 15: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

b = int(input('b = ')) print (a, b)print (a+b) # statement 2

If you simply use just input() function, Python will take a value and interpret it as a string. When you use + sign between 2 strings, you simply concatenate them together.

If you want your inputs to be specific types such as int, float, you must tell Python. For example, to convert string to integer, you need to use int() function.

13) Write a Python code that takes numbers a and b. Then print every number from a to b. Hint: use for-loop with range(a,b).

14) Write a Python code that takes numbers a and b. Then print every number squared from a to b. (for powering, use ** operator) 

15) Write a Python code that takes numbers a and b. Then print every odd number from a to b. 

16) Write a Python that takes your name and your student ID. Also takes the number of times you want to print your name and your student ID. Then

17) Write a Python code that takes numbers a and b. The value of a must be greater than that of b. Then print every number from a down to b. 

Page 16: portal.scitech.au.eduportal.scitech.au.edu/.../uploads/2019/07/CS1201_Week1_1_201… · Web viewGet started with Jupyter Notebook. 1) Run Jupyter notebook and 2) click New (right

CSX3001 Fundamentals of Computer Programming, semester 1/2019

The following Python code prints all even numbers in a range of 0 and 9. Inside the loop, there is a simple if-else condition to check if num % 2 == 0. If the condition is True, then print num’s value on the screen.

18) Write a Python code that prints every number from 0 to 50 that is a multiple of 5.