Introduction to Mathematical and Scientific Programming TUTORIAL WEEK 2 (MATH 1MP3) Winter 2019

Similar documents
Introduction to Mathematical and Scientific Programming TUTORIAL WEEK 1 (MATH 1MP3) Winter 2019

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Algorithms and Programming

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

8. Control statements

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Introduction. C provides two styles of flow control:

4. Write the output that would be printed from each of the following code fragments. (6pts) a = 5 b = 4 temp = a a = b b = temp print(a, b, temp)

Flow Control: Branches and loops

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

Real Python: Python 3 Cheat Sheet

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Chapter 4: Making Decisions

Computer Science 217

Chapter 4: Making Decisions

Comp 150 Exam 2 Overview.

CSE 115. Introduction to Computer Science I

Introduction to Python (All the Basic Stuff)

***********PYTHON PROGRAMS FOR CLASS XI ******************** """ Program to Calculate Simple Interest """ p = eval(input("enter Principle?

4. Write the output that would be printed from each of the following code fragments. (8pts) x = 9 y = x / 2 print('y ==', y) +1 4.

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Repetition Structures

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know?

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Ch.2: Loops and lists (part 2)

Control Structures 1 / 17

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Chapter 8 Statement-Level Control Structures

CMSC201 Computer Science I for Majors

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

boolean & if-then-else

Advanced Computer Programming

LECTURE 5 Control Structures Part 2

5. Control Statements

Class 8 ALGORITHMS AND FLOWCHARTS. The City School

Introduction to programming using Python


Programming for Experimental Research. Flow Control

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Ch.2: Loops and lists

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Lecture 1: Introduction to Python

Programming to Python

Lists How lists are like strings

Ch.2: Loops and lists

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

18.1. CS 102 Unit 18. Python. Mark Redekopp

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Practice with if-then-else. COMP101 Lecture 7 Spring 2018

Control Structures. CIS 118 Intro to LINUX

Begin to code with Python Obtaining MTA qualification expanded notes

Visualize ComplexCities

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

LECTURE 04 MAKING DECISIONS

Introduction to Python Programming

Theory of control structures

Beyond Blocks: Python Session #1

MEIN 50010: Python Flow Control

Control flow statements

Chapter 8. Statement-Level Control Structures

boolean Expressions Relational and Equality Operators and if-then-else Conditional Control Statement

YOLOP Language Reference Manual

Introduction to Python! Lecture 2

Lecture 7: Python s Built-in. in Types and Basic Statements

Statements 2. a operator= b a = a operator b

Control Structures II. Repetition (Loops)

ENGR 102 Engineering Lab I - Computation

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Relational operators (1)

CPSC 217 Midterm (Python 3 version)

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

CLASS XI - HALF YEARLY EXAMINATION SUBJECT: INFORMATICS PRACTICES (065) MARKING SCHEME

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

Data Structures. Lists, Tuples, Sets, Dictionaries

Python for Non-programmers

Revision of Basics of Python

CS 2316 Exam 1 Spring 2014

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Flow Control. CSC215 Lecture

DECISION MAKING STATEMENTS

SCoLang - Language Reference Manual

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

LOOPS. Repetition using the while statement

Programming Fundamentals

Chapter 4: Programming with MATLAB

Control Flow: Branching booleans and selection statements CS GMU

Chapter 5: Control Structures

Final Exam Practice Questions

Chapter 1: Problem Solving Skills Introduction to Programming GENG 200

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Transcription:

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.