TUTORIAL WEEK 2 Introduction to Mathematical and Scientific Programming (MATH 1MP3) Winter 2019
We will review: String Slicing Lists Conditionals Loops
Some Examples for String Slicing A="This is an apple" #last 4 characters, can be written as str[-4:] B = A[len(A)-4:] print(b) pple This is an apple C=A[:-4]+B D=3*(C+"!"+"\n") print(c) print(d) E=D.split() print(e) This is an apple! This is an apple! This is an apple! ['This', 'is', 'an', 'apple!', 'This', 'is', 'an', 'apple!', 'This', 'is', 'an', 'apple!']
Lists: Lists can contain any type of data i.e. integers, characters, strings, other lists, etc. Lists are defined by [ ] Lists have their own methods. (.reverse(),..) Lists can be sliced the same way as strings.
Examples: ## List with one element L1 = [99] ## slices the list and returns the entire list print("the entire list: L1[0:1]: ", L1[0:1]) print("the entire list: L1[0:20]: ", L1[0:20]) "\n" ## returns the int 99 print("the first entry of the list: L1[0]: ", L1[0]) ----------------------------------------------------------------- The entire list: L1[0:1]: [99] The entire list: L1[0:20]: [99] The first entry of the list: L1[0]: 99 L2 = ["a", "B", "z"] ## returns the list with the first two elements print("first two elements of L2: L2[0:2]: ", L2[0:2]) ## reverse the elements of the list L2.reverse() print("reversed list: ", L2) print("print the list in the original order:\n", L2[::-1]) print("reversed list: ", L2) --------------------------------------------------------------------------------- first two elements of L2: L2[0:2]: ['a', 'B'] reversed list: ['z', 'B', 'a'] print the list in the original order: ['a', 'B', 'z'] reversed list: ['z', 'B', 'a']
Updating Lists: Lists can be updated. A=[ 1, 2, Apple, 1.5] A[2]= Orange print(a) A=[1, 2, Orange, 1.5] Elements can be added to a list with the append( ) method. A.append(2500) print(a) A=[1, 2, Orange, 1.5, 2500] Elements can be removed from a list with the remove( ) method. A.remove( Orange ) A=[1, 2, 1.5, 2500] print(a)
Conditionals: if else Statements if statement: will execute if the statement s condition is True clause is skipped if the condition is False else statement: follows an if statement is executed only when the preceding if statement is False. o o o o o elif statement: short hand for else if always follows an if or another elif statement use when you want one of many possible clauses to execute condition is tested if the preceding statement is false
break: The break statement, terminates the current loop and resumes execution at the next statement. Flowchart is for: https://www.programiz.com/pythonprogramming/break-continue
continue: The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. Flowchart is for: https://www.programiz.com/pythonprogramming/break-continue
Examples: s1 = "apple" if(s1 == "orange"): print("orange") elif(s1 == "apple"): print("apple") else: print("is it a vegetable?") -------------------------------------- apple List=[1,5,10,11.5,20,3] for element in List: if element >= 10: continue print(element) print("finish") ------------------------------ 1 5 3 Finish for i in "Apple": if i == "l": break else:print(i) ----------------------------- A p p
Important Points: Note: Index starts at 0 range( ) len( ) Indent = tab or 3 spaces(recommended)
Example: list = ['one', 'two', 'three', 'four'] list_len = len(list) print(len(list),"\n") for i in range(0,list_len): print(list[i]) 4 one two three four
Loops: For Loop While Loop
For Loops: Executes a block of code, a certain number of times Requires the "in" keyword the range(n) function can define the range of values the for loop iterates over. range(n) always starts the range at 0 and ends it at n-1 range(start, stop[, step]) Note: Lists, tuples and ranges are inherently iterable https://docs.python.org/3/library/stdtypes.html#iterator-types
While Loops: Executes the body of the loop when the logical expression is true While loops stop when logical expression is false At the end of each iteration, the program jumps back to the start of the loop An operation inside the loop has to falsify the logical expression To keep track of iterations, you can use a counter variable (often called i or k)
Examples: ##Here i is each element of the list (not its index) and it is the iteration variable ##Here i is the index of the list for i in range(len(dlist)): print("i: ",i," dlist: ",dlist[i]) n=0 x=1 while x<10: spam = 0 while(spam <5): print("spam msg: ", spam) dlist = ["a",1,"c45"] n=n+1 spam +=1 for i in dlist: print(i) --------------------- ------------------------- ----------------------- ------------------------ a 1 c45 i: 0 dlist: a i: 1 dlist: 1 i: 2 dlist: c45 This is an (infinite) loop because nothing falsifies the logical expression. These kind of loops never ends; it never breaks out of the loop. So, whatever is in the loop gets executed forever. spam msg: 0 spam msg: 1 spam msg: 2 spam msg: 3 spam msg: 4
Nested For Loops Interior loop gets executed for every index of exterior loop
Debugging Loops Use print() statements Print variables and data structures from inside your loops
Example: # Program to find the sum of all numbers stored in a list # List of numbers List = [15, 2, 25, 5] # variable to store the sum sum = 0 # iterate over the list for number in List: print(number,"+",sum) # Debugging sum = sum+number print(sum,"\n") # Debugging print("the sum is", sum) 15 + 0 15 2 + 15 17 25 + 17 42 5 + 42 47 The sum is 47
Tutorial Problems 1) Write code to print the area of the rectangle with height 4 and length 6. 2) Make a list that contains your postal code print the first three characters print the last three characters print the last three characters in reverse order using indexing only 3) In the 1111101110111 number, How many 1 exist before the first 0?
Answers: ## Problem 1 height = 4 length = 6 print("area: ", height*length) ------------------------------------- Area: 24 ## Problem 2 l1 = ["L", 7, "T", 1, "X", 9] print("first three: ", l1[0:3]) print("last: ", l1[3:6]) print("last three: ", l1[5:2:-1]) --------------------------------------- first three: ['L', 7, 'T'] last: [1, 'X', 9] last three: [9, 'X', 1] ## Problem 3 j=0 for i in "1111101110111": if i!= "1": break else: j=j+1 print(j) print("finish") ---------------------------------- 5 The end
Acknowledgement: Thanks to Peter Tait. This tutorial was written for Math 1MP3 winter 2019 and it was written and was completed based on the fall 2018 Math 1MP3 course s tutorials which were provided by Peter Tait.