Copy of CITS2401_Lab2

.pdf

School

The University of Western Australia *

*We aren’t endorsed by this school

Course

2401

Subject

Computer Science

Date

Apr 3, 2024

Type

pdf

Pages

5

Uploaded by EarlManateeMaster1057

Report
02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 1/17 Before you edit something, Please select 'File' above, and click 'Save a copy in Drive' CITS2401 Lab2 NOTE: Please refer to the FAQ Q2.4 Q2.4: Can I ask questions (via Email or Discord) before the Lab? We would like to ask Not to do it before the lab. We always thank you for sharing good questions, but those questions can be answered during the lab class. The reason why we share those lectures and labs (on Sunday) is for you to skim through the topic we will cover. So, please attend the lab ±rst and ask those questions during/after the lab to the teacher. So your question can be easily answered as the teacher will go through with you. We do understand you would like to know some content as soon as you can. But we have more than 350 students in this unit and it will be really di²cult to manage all questions posted on Discord if students start asking questions before attending actual lab sessions. Thanks for your understanding! Lab 2 Checklist 02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 2/17 Play with Floor Divide and Modulo (refer Lecture 1, page 17) 0.[Recap] Floor divide and Modulo We have learned the following seven operators: + , - , * , / , ** , // , % Among those operators, we will go through the following: // Floor divide. (Divide and round down) % Modulo. (Divide and return the remainder) Try running the following code. Make sure you understand this! height = 183 print("You are " + str(height // 100) + "m and " + str(height % 100) + " cm tall.") 1 2 height = 183 print("You are " + str(height // 100) + "m and " + str(height % 100) + " cm tal You are 1m and 83 cm tall. Let's try: Task 1 : Write a program that performs exactly like the following: 1 2 3 4 5 day = int(input('Enter a number of days: ')) weeks = int(day) // 7 days = int(day) % 7 print('That is {} weeks and {} days!'.format(weeks, days)) Enter a number of days: -5 That is -1 weeks and 2 days! Task 2: Guess what would be the output of the following (not executing the program): 1. What is -5 // 7 ? 2. What is -5 % 7 ? 02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 3/17 1. -1 2. 2 Lists, Tuples, Sets, and Dictionary (Lecture 2, page 5 - 51) 1.Python Collections There are four collection data types in the Python: List, Tuple, Set, and Dictionary. Those are used to store multiple items in a single variable. The table can be also found in the Lecture 2, page 34 . Lists (Lecture 2, page 6 - 32) 1-1.Lists Lists are created using square brackets [ ] . Each object is called an element or item of the list and each element/item can be accessed using an index, starting from 0 . We can store multiple different data types in a single list. Lists are mutable objects. This means that we can change their elements by accessing them directly in an assignment statement. We can also add, change or remove elements from the list. Since lists are indexed, we can store multiple items with the same value. The len() function is one of the commonly used methods and it can check the number of items in the list. Part 1 02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 4/17 Try out the following piece of code. colour = ["red", "orange", "yellow", "green", "blue", "pink"] print(colour[0]) Note: Don't name your variable list since it is a built-in function in Python! 1. Change the index to 1 or 2 to print out other elements. 2. Add a new item "purple" to the list by using the append() method. Print out your list to check that it worked correctly. 3. What happens if you try print(colour[-1]) ? What about other negative numbers, like -2 or -4? 4. Change "pink" to "indigo" so that you get a proper rainbow! 5. What happens if we print the element with index 7? red yellow ['red', 'orange', 'yellow', 'green', 'blue', 'pink', 'purple'] pink ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple'] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-14-84d903ef2ad0> in <cell line: 14> () 12 print ( colour ) 13 ---> 14 print ( colour [ 7 ]) IndexError : list index out of range SEARCH STACK OVERFLOW 1 2 3 4 5 6 7 8 9 10 11 12 13 14 colour = ["red", "orange", "yellow", "green", "blue", "pink"] print(colour[0]) print(colour[2]) colour.append("purple") print(colour) print(colour[-2]) colour[5] = 'indigo' print(colour) Part 2
02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 5/17 Try out the following piece of code. word = ["n", "a", "n", "a"] print(word) 1. Extract the second to fourth items in the word list by using the print() method. 2. Insert "b" and "a" at the beginning of the list so you can make it banana. 1 2 3 4 5 6 7 8 9 word = ["n", "a", "n", "a"] print(word) print(word[1: ]) word.insert(0, 'b') word.insert(1, 'a') print(word) ['n', 'a', 'n', 'a'] ['a', 'n', 'a'] ['b', 'a', 'n', 'a', 'n', 'a'] Tuples (Lecture 2, page 33 - 39) 1-2.Tuples Tuples are written with round brackets ( ) . Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the ±rst item has index [0] , the second item has index [1] etc. Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. Since tuples are indexed, they can have items with the same value. You can check the number of items by using len() . Part 1 Try out the following piece of code. myfamily = ("mother", "father", "sister", "brother", "sister") print(myfamily) 02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 6/17 1. Use type() to check the type of the object myfamily . 2. Access tuple items sister by using index numbers. 3. Check whether we can add an item me by using the append() method. 4. Check whether we can remove the item brother by using the pop() method. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 myfamily = ("mother", "father", "sister", "brother", "sister") print(myfamily) print(type(myfamily)) print(myfamily[4]) x = list(myfamily) x.append('me') print(x) x.pop(3) y = tuple(x) print(y) ('mother', 'father', 'sister', 'brother', 'sister') <class 'tuple'> sister ['mother', 'father', 'sister', 'brother', 'sister', 'me'] ('mother', 'father', 'sister', 'sister', 'me') Sets (Lecture 2, page 40 - 44) 1-3.Sets Sets are written with curly brackets { } . Set items are unordered, unchangeable (but mutable), and do NOT allow duplicate values. Unordered means that the items in a set do not have a de±ned order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key. Sets are unchangeable but mutable, meaning that we cannot change the items after the set has been created. Once a set is created, you cannot change its items, but you can add new items or remove items. Part 1 02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 7/17 Try out the following piece of code. fruit = {"apple", "pineapple", "grape", "apple"} 1. Use print() to print all items in the set. Can you see all four items? or three items only? Why? 2. Use type() and check the type of the object fruit . Is that what you expected? 3. Add a new item "grapefruit" using the add() method. 4. Remove all items from the set fruit . 5. Again, use type() and check the type of the object fruit . Is that what you expected? ³. Create another object empty = {} and check the type of the object by using type() . Is that what you expected? 1 2 3 4 5 6 7 8 9 10 11 12 fruit = {"apple", "pineapple", "grape", "apple"} print(fruit) print(type(fruit)) fruit.add('grapefruit') fruit.clear() print(type(fruit)) empty = {} print(type(empty)) {'grape', 'apple', 'pineapple'} <class 'set'> <class 'set'> <class 'dict'> Dictionary (Lecture 2, page 45 - 50) 1-4.Dictionaries Dictionaries are also written with curly brackets { } . Where lists or tuples use numbered indexes such as list[0] to access their elements, dictionaries use keys to access their elements. Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered* ( As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. ), changeable and does not allow duplicates. In a dictionary, keys are unique so a 02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 8/17 given key can only appear once. Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created. Part 1 Try out the following piece of code. laptop = { "brand": "dell", "model": "alienware", "year": 2010 } 1. Print the brand value of the dictionary. 2. Add new information ( key: value ) by using a boolean data type as value and home as key : This laptop is at home now, so "home": True . 3. Modify the value of the key year to 2019 . *Additional Methods for extracting keys or values: keys() and values() Try and see how the output comes out. 1 2 3 4 5 6 7 8 9 10 11 laptop = { "brand": "dell", "model": "alienware", "year": 2010 } print(laptop['brand']) laptop['home'] = True print(laptop) laptop['year'] = 2019 print(laptop) dell {'brand': 'dell', 'model': 'alienware', 'year': 2010, 'home': True} {'brand': 'dell', 'model': 'alienware', 'year': 2019, 'home': True} Part 2
02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 9/17 Write a program that stores information about a user into a dictionary , and performs exactly as follows: *Note : The yellow-highlighted texts are things that the user types into the terminal. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 name = input('What is the user\'s name? ') age = input('What is the user\'s age? ') country = input('What is the user\s country of birth? ') known = input('What is the user known for? ') print('The user\'s data is: ') user_data = { 'name': name, 'age': age, 'country': country, 'known_for': known } print(user_data) What is the user's name? Zain What is the user's age? 18 What is the user\s country of birth? Pakistan What is the user known for? skills The user's data is: {'name': 'Zain', 'age': '18', 'country': 'Pakistan', 'known_for': 'skills'} 2.Control Flow Control Flow Programs written so far execute sequentially (e.g. execute Line 1 then Line 2 so on…) We can control the ´ow of program by using: Selection statements: if, elif, else statements (this week) Iteration statements: while, for statements (lab 3) 02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 10/17 Flowchart shapes to represent intention. Parallelogram – input/output to the program Rectangle – assignment or computations Diamond – decision Arrows – direction of execution if Statement (Lecture 2, page 54 - 56) 2-1.Control Flow: if Control ´ow is an important topic in programming. It allows us to execute speci±c branches depending on the current state of the program. Up until now, all of our programs executed sequentially. In this week, we will learn how we can control the ´ow of the program by using selection statements. Control ´ow: if statement IF statement starts with keyword if Colon symbol : denotes start of if block Body of the if statement is indented with 4 spaces or a tab Python Conditions and If statements Python supports the usual logical conditions from mathematics. This will be used in several ways, most commonly in selection and iteration. 02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 11/17 if takes in a single boolean. If it is True, its branch will execute. Try the following code: if 10 > 5: # Note the colon : symbol which denotes the start of a new block. print("10 is indeed greater than 5.") # Code inside the block must be indented with 4 Note: Python does not accept ±les that mix spaces and tabs as indentation. You may receive an IndentationError. If you run into such an issue, look for a setting to make tabs and spaces visible. Good editors will resolve all tabs to 4 spaces or vice versa, so you shouldn't run into issues. 1 2 if 10 > 5: # Note the colon : symbol which denotes the start of a new block. print("10 is indeed greater than 5.") # Code inside the block must be inden 10 is indeed greater than 5. Part 1: Checking power level (by using if statement only) Write a program that asks the user for their power level. Make the program output a different response depending on whether the user's power level is over 9000 or not (by using two if statements) *Note: The yellow-highlighted texts are things that the user types into the terminal. 02/11/2023, 21:40 Copy of CITS2401_Lab2.ipynb - Colaboratory https://colab.research.google.com/drive/1JzUhaMQ4sxQ_7AHRAJafh30eCZjRe-8Q#scrollTo=NykcBGJ4vc08&printMode=true 12/17 1 2 3 4 5 6 7 power = int(input('Vegeta, what does the scouter say about his power level? ')) if power > 9000: print('IT\'S OVER NINE THOUSAND!!!') if power < 9000: print('it\'s not over 9000...') Vegeta, what does the scouter say about his power level? 800 it's not over 9000... if, else Statement (Lecture 2, page 57 - 61) 2-2.Control Flow: if-else An if statement is used to do some action(s) if the condition is true. IF statement starts with keyword if Colon symbol : denotes start of if block Body of the if statement is indented with 4 spaces or a tab The else keyword catches anything which isn't caught by the preceding conditions. else statement to do something else if the condition is false No condition after the else statement Note: It is useful to draw ´owcharts to represent the control ´ow in our programs. Below is the ´owchart for a piece of code that includes an if statement Part 1: If ... Else with a ²ow chart
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help