INFS2822_T3_2024_LecW04.pdf

Full Transcript

UNSW Business School INFS2822 Programming for Data Analytics Lecture 4 Python Fundamentals Part IV Term 3, 2024 Lecturer-in-Charge: Dr. Henry KF Cheung ([email protected]) Copyright There are some file-sharing websites that specialise in buying and selling academic...

UNSW Business School INFS2822 Programming for Data Analytics Lecture 4 Python Fundamentals Part IV Term 3, 2024 Lecturer-in-Charge: Dr. Henry KF Cheung ([email protected]) Copyright There are some file-sharing websites that specialise in buying and selling academic work to and from university students. If you upload your original work to these websites, and if another student downloads and presents it as their own either wholly or partially, you might be found guilty of collusion — even years after graduation. These file-sharing websites may also accept purchase of course materials, such as copies of lecture slides and tutorial handouts. By law, the copyright on course materials, developed by UNSW staff in the course of their employment, belongs to UNSW. It constitutes copyright infringement, if not academic misconduct, to trade these materials. Country UNSW Business School acknowledges the Bidjigal (Kensington campus) and Gadigal (City campus) the traditional custodians of the lands where each campus is located. We acknowledge all Aboriginal and Torres Strait Islander Elders, past and present and their communities who have shared and practiced their teachings over thousands of years including business practices. We recognize Aboriginal and Torres UNSW Business School. (2022, August 18). Acknowledgement of Country [online video]. Strait Islander people’s ongoing Retrieved from https://vimeo.com/369229957/d995d8087f leadership and contributions, including to business, education and industry. 5 6 Reminder of Week 4 Homework Week 4 Homework is on Ed Lessons, which contributes 2% to your overall grade in this course Only exercise(s) carrying a percentage, e.g., 1%, will be marked You can attempt multiple times, and solutions and feedback will be released on Ed one week after the due date (with the assumption of no approved special consideration cases) Due on Sunday 6th October 2024, 3 pm (AEDT) 7 Reminder of Group Assignment 30% Group Assignment ⎻ Assignment description available on Moodle from Week 4 Monday 30 September 2024, 10 am AEST ⎻ Submission, including code in.ipynb, PPT, report, by Week 10 Monday 11 November 2024, 3 pm AEDT ⎻ Lab 10: Group Assignment Presentation in person, on campus, in your officially enrolled lab Group formation must be finalised by Friday 4 October 2024 ⎻ Group size: 4 (minimum 3) ⎻ All team members must be from your officially enrolled lab ⎻ Nominate a team leader, then the team leader sends an email to your tutor with all teammates’ names and zIDs ⎻ If you don’t have a group, your tutor will randomly assign you to a group 8 Things about Quiz in Week 5 Lab Total marks for the course – 5% Time allowed – 15 minutes including reading time Type and number of questions – 7 multiple-choice questions ⎻ Each question is worth ONE mark. There is only one correct answer in each question and no negative mark for a wrong answer. ⎻ Scope: Materials in Weeks 1 – 4, except topics marked as Advanced What students can have on their desk during this quiz: ⎻ A laptop installed Inspera Safe Exam Browser (SEB) ⎻ Any printed material (Open book, but no electronic devices except your laptop) ⎻ Student card (Tutor will verify) Quiz is on-campus & in-person, and starts at 15 minutes after the scheduled start time of your enrolled lab ⎻ Make sure you attend your officially enrolled lab in Week 5 ⎻ Your tutor will give you the exam/quiz code to access the quiz during class 9 Inspera Inspera is the examination platform you will use. You will use Safe Exam Browser (SEB) for your exam/quiz: Inspera will stop you from accessing other applications and/or websites on your laptop while SEB is running. This will ensure that you CANNOT look at your notes or access the websites. You must download and install the SEB application from Inspera – Assessment Platform – Safe Exam Browser (SEB) section. Make sure you choose the right version of your OS. 10 Student Practice Test for SEB The advice we got from the Inspera team is for all of you to complete the Inspera Student Practice Test (https://unsw.inspera.com/student#list/112563919). This is an open test that any UNSW student can take to check whether they have successfully downloaded SEB. Test Password: 12345a. Quit Password: 1234. Note: If the test doesn't open, try a private/incognito window on your browser. It is your responsibility to make sure the SEB is downloaded and works before coming to the exam venue/class. If you have any questions, please go to see UNSW IT walk-in services (Contact Us | UNSW IT | UNSW Sydney). Note: Lecturer(s)/Tutor(s) cannot help you help fix issues related to Inspera SEB. 11 Recommendations Both Windows and Mac have regular updates and upgrades. Do NOT trigger updates or upgrades two days before the exam/quiz to ensure the settings are NOT modified. I believe this might be one of the causes for some students who had temporary access issues in the exam/quiz. If you did, then you should perform the Student Practice Test (https://unsw.inspera.com/student#list/112563919) again. have a test on SEB again on Thursday, the day before the exam, to ensure everything is working. 12 Inspera Practice Set and Quiz Info In the INFS2822 Moodle Page 13 Outline Conditional Statements Loops Function 14 Recap: What is a Statement? A statement is an instruction that the Python interpreter can execute. Assignment: x = 5 Conditional statements: if, else, elif Loops: for, while Control statements: break, continue Function definitions: def 15 What is a Conditional Statement? A conditional statement often employs relational operators to form conditions. Conditional statements create branches in the flow of a program, allowing different blocks of code to be executed depending on whether a given condition is true or false. ⎻ Branching means an instruction that tells a computer to begin executing a different part of a program rather than executing statements one-by-one. ⎻ Branching allows us to run different statements for different conditions. ⎻ The simplest branching is the if statement. 16 Logical Flow on Condition Execution if x > 0 : print('x is positive') 17 Syntax of Conditional Statements The Boolean expression after the if statement is called the condition. We end the if statement with a colon ':' After if statement, we use indent to indicate a block of statements to be executed when the condition is met There is no limit on the number of statements that can appear in the body, but there must be at least one We remove indent to indicate a part that is outside the block x = 10 if x == 5: print('x is equal to 5') # this line has an indent print('This line will also be printed if x == 5') print('This line will be always printed') 18 Meet the Condition?! If the logical condition is True, then the indented statement gets executed If the logical condition is False, the indented statement is skipped x = 10 if x == 5: print('x is equal to 5') # indented print('This line will also be printed if x == 5') print('This line will be always printed') 19 Recap on Relational Operators Relational operators compare We leverage these relational operations operands and produce a to define conditions Boolean x = 10 equal: == if x > 5: not equal: != print('x is greater than 5') greater than: > less than: < if x < 10: print('x is less than 10') greater than or equal to: >= less than or equal to: = 80: grade = 'B' else: grade = 'C' print(grade) 24 Logical Operators in Conditions Recall that Logical Operators can be applied to conditions The and statement is only True when all conditions are True The or statement is True if at least one condition is True The not statement outputs the opposite truth value a = 10 b = 10 c = -10 if a > 0 and b > 0 and c > 0: print("a, b and c are greater than 0") else: print("At least one number is not greater than 0") What if we change and to or? 25 Exception Statement for Error Handling Exception statement try … except … is a conditional execution structure built into Python to handle exceptions, i.e., errors Use this when you anticipate an exception, and you want to handle it gracefully instead of letting the program terminate abruptly How the statement is executed ⎻ If the code in try has no error, the statements in except are skipped ⎻ If exception occurs within the try, the rest of try clause is skipped, and the statements in except are executed try: val = 'a' + 5 print('val = ', val) except: val = -100 print('an error exists here') 26 Exception Statement with Multiple ‘except’ A try statement may have more than one except clause, to specify different handlers At most one handler will be executed The last except clause may omit exception names, to serve as a wildcard to catch all unexpected errors that were not handled try: # code that might trigger an exception except Exception1: # execute if there’s an Exception1 except Exception2: # execute if there’s an Exception2 except: # execute if the exception does not match Exception1 and Exception1 27 Example for Multiple ‘except’ Clauses # At most one handler will be executed, just like if-elif-else try: y = int(input("Enter a number: ")) y = 1 / y print("the rest of the code in try clause") except ValueError: print("ValueError: input() did not work. Please enter an integer.") except ZeroDivisionError: print("ZeroDivisionError: do not divide by 0! ") except: #wild card, in case of any unexpected unhandled errors print("unexpected error") print("some important code that must run") 28 Outline Conditional Statements Loops Function 29 What is a Loop? A loop is defined as a segment of code that executes multiple iterations (1 iteration means 1 round of running the code). Loops are used to repeatedly execute a block of code. i = 0 while i < 5: print(i) i += 1 30 Two Types of Loops in Python for loop: iterate over a sequence (list, tuple, string) or other iterable objects. while loop: repeatedly execute a block of code, as long as the condition is True. 31 for Loop It is used for iterating over a sequence of elements. It enables you to execute a code block multiple times, one iteration for one element in the sequence. Day_Of_Week = ["Monday", "Tuesday", "Wednesday"] # Day_Of_Week is a list for x in Day_Of_Week: #iterate the Elements in a List print(x) 32 Iterate Elements in range() range() function generates a sequence of numbers Use the sequence in for loop range(3) range(3, 9) excludes 9 33 Types of for Loop Iteration Iteration by index Iteration by element for i in range(len(alist)): for elem in alist: alist[i] = alist[i] * 10 elem = elem * 10 print(alist) print(alist) Loop variable i is the increasing index Loop variable elem takes the value of number to access items in the list by each element in alist directly, NOT the putting index in square brackets, [i] index Iteration by index allows read access Iteration by element allows read access and modification of the individual to the items in a sequence items This does NOT allow modification of the individual items, because replacement of elements by item assignment requires an index number 34 Exercise numbers = [5, 11, 7, 13, 9, 17] total = 0 # sum is a built-in function # and should not be used as variable name for num in numbers: # iterate over the list total = total + num # or total += num print ("The sum is", total) num sum What is the printout? 1st iteration 5 5+0=5 The sum is 5 The sum is 16 2nd iteration 11 5+11=16 The sum is 23 3rd iteration 7 16+7=23 The sum is 36 The sum is 45 … The sum is 62 Question: This is iteration by element. Would iteration by index be more suited? 35 while Loop The while loop is a tool for repeated execution based on a condition. We don’t necessarily know the number of iterations. But we know the condition for the loop to continue running. The code block will keep being executed until the given logical condition returns a False Boolean value. i = 0 i = 0 i = 1 i = 0 while i < 5: while i < 5: while i

Use Quizgecko on...
Browser
Browser