Programming in Python for Business Analytics (BMAN73701) Lecture Notes PDF

Document Details

Uploaded by Deleted User

The University of Manchester, Alliance Manchester Business School

Dr. Xian Yang

Tags

python programming data types control flow programming

Summary

This document is a set of lecture notes on Python programming for Business Analytics, discussing data types, sequence types (like lists and tuples), control flow statements (like for and while loops, if/else statements, and break/continue), and comparison and Boolean operations. It explains various Python concepts and methods, suitable for undergraduate-level study.

Full Transcript

Programming in for Business Analytics (BMAN73701) Lecture 2 – Data Types and Control Flow Statements Dr. Xian Yang [email protected] 1. Built-in types 1.1. Sequence types (list, tuple, range, str) 1.2. Mapping types (dict)...

Programming in for Business Analytics (BMAN73701) Lecture 2 – Data Types and Control Flow Statements Dr. Xian Yang [email protected] 1. Built-in types 1.1. Sequence types (list, tuple, range, str) 1.2. Mapping types (dict) 2. Control flow statement 2.1. for and while loops 2.2. if, else, elif statements 2.3. break and continue statements 3. Comparison and Boolean operations 2 1.1 Built-in types: Sequence types In Python, sequence types are data structures that store a collection of items in a specific order. The basic sequence types: list, tuple, range, str https://docs.python.org/3.12/tutorial/datastructures.html 3 Built-in types: Sequence types - list Lists are the most versatile sequence type They can store collections of items, which can be of the same type (homogeneous) or of different types (heterogeneous). Initialization of a list with n items: list_name = [item_0, item_1,…, item_n-1] (initialize an empty list using list_name = list() or list_name = []) Lists are mutable, i.e. items can be appended, removed, changed, etc after assignment. 4 Built-in types: Sequence types - list Accessing items in a list All built-in sequence types can be indexed and sliced While indexing is used to obtain individual elements, slicing allows you to obtain a set of elements Indices may also be negative numbers to start counting from the right Note how the start is included and the end excluded Slice indices have useful defaults; an omitted first index defaults to zero, and an omitted second index defaults to the Note: All slice operations return a size of the sequence being sliced. new list containing the requested elements 5 Built-in types: Sequence types - list Extending a list 6 Built-in types: Sequence types - list Replacing items in a list 7 Built-in types: Sequence types - list Removing items from a list 8 Built-in types: Sequence types - list Sorting a list 9 Built-in types: Sequence types - list Other useful operations for a list 10 Quiz 1 1. squares = [1,4,9,16,25] What is the output of the code >>> squares[-3:]? a) [1,4,9] b) [9,16,25] c) [25,16,9] 2. What is the output of the code: a) [5,8,4,0,9] b) [5,4,2,4,2,0,9] c) [5,4,2,4,2] d) Error 11 Quiz 1 1. squares = [1,4,9,16,25] What is the output of the code >>> squares[-3:]? Ans: b) [9,16,25] 2. What is the output of the code: Explanation: li[1:3] is a slice of the list li, which includes the elements from index 1 up to (but not including) index 3. In this case, li[1:3] returns the sublist [4, 2]. Ans: b) [5,4,2,4,2,0,9] The operation *= 2 is applied to this slice. This operation duplicates the elements in the slice. So, [4, 2] * 2 results in [4, 2, 4, 2]. The original list is then updated by replacing the slice li[1:3] with the new list [4, 2, 4, 2]. 12 Built-in types: Sequence types - tuple Tuples are immutable, i.e. items are fixed after assignment Used for collection of heterogeneous items, e.g. a person’s details broken into (name, age, city) Generally used where order and position are meaningful and consistent Initialization of a tuple with n items: tuple_name = (item_0, item_1,…, item_n-1) (initialize an empty tuple using tuple_name = () or tuple_name = tuple()) 13 Built-in types: Sequence types - tuple These operations are the same for lists 14 Built-in types: Sequence types - tuple Adding items to a tuple 15 Built-in types: Sequence types - tuple immutable Replacing items in a tuple 16 Built-in types: Sequence types - range The range type represents an immutable sequence of numbers The range type is commonly used for looping a specific number of times in for loops. Initialization a range object with a sequence of numbers starting at start and finishing before stop with a step size of step: range_name = range(start, stop, step) 17 Built-in types: Sequence types - range True False 18 Built-in types: Sequence types - range range_name = range(start, stop, step) - default values are start = 0, step = 1 19 Built-in types: Text sequence types - str Textual data in Python is handled with str Strings are immutable Initialization of a string (both ‘ and “ can be used): string_name = ‘text’ or string_name = str(‘text’) We can apply the same operations to strings as we do for other immutable sequence types, such as indexing, slicing, etc. (see next slide for examples) Strings have also many additional methods (overview of these can be found at https://docs.python.org/3/library/stdtypes.html#str) 20 Built-in types: Text sequence types - str 21 Built-in types: Text sequence types - str If a string x is an input in list(x) or tuple(x), then the items in the sequence will be split Built-in types: Common sequence operations https://docs.python.org/3/library/stdtypes.html#common-sequence-operations 22 1. Built-in types 1.1. Sequence types (list, tuple, range, str) 1.2. Mapping types (dict) 2. Control flow statement 2.1. for and while loops 2.2. if, else, elif statements 2.3. break and continue statements 3. Comparison and Boolean operations 23 1.2. Built-in types: Mapping types - dict Think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within a dictionary). Dictionaries are indexed by keys, which can be any immutable type. The values of a dictionary can be of any type. Initialization of a dictionary (more than two options): 1. dict_name = {key_1 : value_1,…, key_n : value_n} 2. dict_name = dict([(key_1,value_1),…,(key_n,value_n)]) 24 Built-in types: Mapping types - dict https://docs.python.org/3/library/stdtypes.html#dict 25 1. Built-in types 1.1. Sequence types (list, tuple, range, str) 1.2. Mapping types (dict) 2. Control flow statement 2.1. for and while loops 2.2. if, else, elif statements 2.3. break and continue statements 3. Comparison and Boolean operations 26 2.1 Control flow statements - for The for statement is used to iterate over the elements of a sequence (e.g. a string, tuple or list) or other iterable object (typically used if we know in advance how may iterations should be done) for item in sequence: indented statements to repeat; may use item The colon (:) at the end indicates that a consistently indented block of statements follows to complete the for loop 27 Indentation What is Indentation? Indentation refers to the spaces or tabs at the beginning of a line of code. Why is it Important? In Python, indentation is crucial because it defines the scope of loops, functions, conditionals, etc. For example, the code that belongs to a loop or a function is indented under that loop or function. If you miss the indentation or do it incorrectly, the Python interpreter will throw an error. The indentation (spaces before print(n)) shows that this statement is part of the loop's body. How Much Should You Indent? Python typically uses 4 spaces per indentation level. You can also use a single tab, but it's important to be consistent throughout your code. 28 Control flow statements - for Some more examples … 29 Write a program that inputs an integer n, then inputs n numbers, a1,…,an and prints S = a1 + … + an 30 Control flow statements - while The while statement is used for repeated execution as long as an expression is true Often used if we do not know in advance how may repetitions to be done) while condition: indented statement block 31 for vs while for item in sequence: while condition: indented statements to repeat indented statement block For i in (0,1,2,3,…,n-1), While i is less than n, print i print i and increase it by one 32 Control flow statements - while Question. Write a program that Line temp Comment increases the temperature 4 15 (starting from 15 degrees) 6 15 < 25 is true, do loop iteratively by 1 degree until a 7 prints 15 certain temperature (25 8 16 15 + 1 is 16, loop back degrees) is reached. Print out 6 16 < 25 is true, do loop each new temperature and also 7 prints 16 a line indicating that the 8 17 16 + 1 is 17, loop back program has terminated. … 8 24 23 + 1 is 24, loop back 6 24 < 25 is true, do loop 7 prints 24 8 25 24 + 1 is 25, loop back 6 25 < 25 is false, skip loop 10 Prints that the water is warm enough 33 Quiz 2 Question. What is the output of this code? a) b) c) d) 1 1 1 Error 3 2 2 5 3 3 7 5 4 9 8 5 34 Quiz 2 Question. What is the output of this code? Ans: d) Error 35 1. Built-in types 1.1. Sequence types (list, tuple, range, str) 1.2. Mapping types (dict) 2. Control flow statement 2.1. for and while loops 2.2. if, else, elif statements 2.3. break and continue statements 3. Comparison and Boolean operations 36 2.2 Control flow statements - if The if statement is used for conditional execution if condition: indented statement block if condition is true else: indented statement block if condition is false 37 Control flow statements - if Convert a numerical grade to a letter grade, ‘A’, ‘B’, ‘C’, ‘D’ or ‘F’, where the cutoffs for ‘A’, ‘B’, ‘C’, and ‘D’ are 90, 80, 70, and 60 respectively. 38 Control flow statements - if- elif if condition1: indented statement block if condition1 is true elif condition2: indented statement block if condition2 is true elif condition3: indented statement block if condition3 is true elif condition4: indented statement block if condition4 is true else: indented statement block if each condition is false 39 Nested control flow statements: for, if Suppose you have a list with the numbers [4, -2, 1, -8, 0, 4]. Print out only the positive numbers. Use a loop and an if clause in your code. 40 Nested control flow statements Be careful when a (mutable) sequence is modified by a loop… numberList index number number > 0 [4,2,-8,3] 0 4 True [2,-8,3] 1 -8 False [2,-8,3] 2 3 True [2,-8] 3 for loop stops because no 3rd item in list 41 Nested control flow statements Be careful when a (mutable) sequence is modified by a loop… numberList counter numberList[counter] if condition [4,2,-8,3] 0 4 True [2,-8,3] 0 2 True [-8,3] 0 -8 False [-8,3] 1 3 True [-8] 1 Stop iteration 42 1. Built-in types 1.1. Sequence types (list, tuple, range, str) 1.2. Mapping types (dict) 2. Control flow statement 2.1. for and while loops 2.2. if, else, elif statements 2.3. break and continue statements 3. Comparison and Boolean operations 43 2.3 Further control flow statements - break The break statement terminates the loop 44 Further control flow statements - continue The continue statement returns the control to the beginning of the loop 45 1. Built-in types 1.1. Sequence types (list, tuple, range, str) 1.2. Mapping types (dict) 2. Control flow statement 2.1. for and while loops 2.2. if, else, elif statements 2.3. break and continue statements 3. Comparison and Boolean operations 46 3. Comparison operations 47 Comparison operations Eight comparison operations in Python All have the same priority Comparisons can be chained arbitrarily Will become clearer next week Supported for sequences only 48 Boolean operations Boolean operations, ordered by ascending priority (all three Boolean operators have a lower priority than the comparison operators on previous slide): Ordered in ascending order of priority 49 Quiz 3 Question. Which output will be created by the code and why? a) b) c) 50 Quiz 3 Question. Which output will be created by the code and why? Ans: a) Ordered in ascending order of priority 51 A note on Boolean expressions So far, condition had a Boolean value, e.g. score > 80 is either True or False. But most data structures/types can be used in a condition. Some general rules: None (i.e. empty) and 0 (zero) evaluate to False. Non-zero numbers evaluate to True. 52 Lecture 3 Preparation Prior to lecture, have a look at functions modules exceptions BB: Additional materials Multiple choice questions Videos to support you in understanding how to determine and interpret line equations 53 10/30/24, 10:18 PM Review Test Submission: Self-check: Conditionals and loops &... BMAN73701 Programming in Python for Business Analytics 2024-25 1st Semester Course Content Week 1, Lecture 2 (Xian Yang) - Conditionals and loops in Python Review Test Submission: Self-check: Conditionals and loops Review Test Submission: Self-check: Conditionals and loops User Melissa Hidayat Course BMAN73701 Programming in Python for Business Analytics 2024-25 1st Semester Test Self-check: Conditionals and loops Started 30/10/24 22:14 Submitted 30/10/24 22:18 Status Completed Attempt Score 40 out of 50 points Time Elapsed 4 minutes Instructions Fill in the blanks, or tick or select all of the answers that you think are correct. Self-Test Student answers and score are not visible to the instructor. Results All Answers, Submitted Answers, Correct Answers, Feedback Displayed Question 1 10 out of 10 points Fill in the blanks to compare the total number of items sold for the US, and output the corresponding shipping costs; there are no costs if more than 150 items will be ordered. country = "US" total = 30 if country == "US": [a] total y = -1 >>> not((x != 2 or y > -1) and x == 3) https://online.manchester.ac.uk/webapps/assessment/review/review.jsp?attempt_id=_24146276_1&course_id=_83513_1&content_id=_16225313… 3/5 10/30/24, 10:18 PM Review Test Submission: Self-check: Conditionals and loops &... Selected Answer: III. False Answers: I. An error message II. True III. False Response Well done:) Feedback: The correct output is False because the first comparison to be validated is (x != 2 or y > -1), which is true, followed by ((x != 2 or y > -1) and x == 3), which is also true, thus not((x != 2 or y > -1) and x == 3) becomes false (Python output being False). Question 5 10 out of 10 points Fill in the blanks to create a code that iterates through all items of a list, and print outs every single item except items with the value "-1": items = [a]"hello", "-1", "xmas", "-1"[b] [c] item [d] items: if [e] == "-1" [f] print(item[g] Specified Answer for: a [ Specified Answer for: b ] Specified Answer for: c for Specified Answer for: d in Specified Answer for: e item Specified Answer for: f continue Specified Answer for: g ) Correct Answers for: a Evaluation Method Correct Answer Case Sensitivity Exact Match [ Correct Answers for: b Evaluation Method Correct Answer Case Sensitivity Exact Match ] Correct Answers for: c Evaluation Method Correct Answer Case Sensitivity https://online.manchester.ac.uk/webapps/assessment/review/review.jsp?attempt_id=_24146276_1&course_id=_83513_1&content_id=_16225313… 4/5 10/30/24, 10:18 PM Review Test Submission: Self-check: Conditionals and loops &... Exact Match for Case Sensitive Correct Answers for: d Evaluation Method Correct Answer Case Sensitivity Exact Match in Case Sensitive Correct Answers for: e Evaluation Method Correct Answer Case Sensitivity Exact Match item Case Sensitive Correct Answers for: f Evaluation Method Correct Answer Case Sensitivity Exact Match continue Case Sensitive Correct Answers for: g Evaluation Method Correct Answer Case Sensitivity Exact Match ) Response Well done:) Feedback: The correct code is items = ["hello", "-1", "xmas", "-1"] for item in items: if item == "-1" continue print(item) We need to add a squared open and closing bracket to complete the initialization of the list items. The for loop allows us to iterate through every single element in the list items, and the standard code for a for loop is "for item in sequence". This allows us to access an element via the variable "item". The break statements terminates the current loop and moves on to the next iteration, which is exactly what we want to do upon encountering a "-1" value in the list. Wednesday, 30 October 2024 22:18:35 o'clock GMT ← OK https://online.manchester.ac.uk/webapps/assessment/review/review.jsp?attempt_id=_24146276_1&course_id=_83513_1&content_id=_16225313… 5/5

Use Quizgecko on...
Browser
Browser