Programming for Engineers in Python

Slides:



Advertisements
Similar presentations
Introduction to Computing Science and Programming I
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
1 Gentle Introduction to Programming Session 2: Functions.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Structured programming
Recitation 1 Programming for Engineers in Python.
Fundamentals of Python: From First Programs Through Data Structures
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Fundamentals of Python: First Programs
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
More Looping Structures
Programming for Linguists An Introduction to Python 24/11/2011.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Computer Programming Basics Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University, Korea.
Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
CIT 590 Intro to Programming Lecture 4. Agenda Doubts from HW1 and HW2 Main function Break, quit, exit Function argument names, scope What is modularity!
Lists Computers and Programming. Agenda What is a list? How to access elements in the list? The for statement Operations on lists Looping with.
Compunet Corporation1 Programming with Visual Basic.NET While, Do and For – Next Loops Week 5 Tariq Ibn Aziz.
Built-in Data Structures in Python An Introduction.
Loops & List Intro2CS – week 3 1. Loops -- Motivation Sometimes we want to repeat a certain set of instructions more than once. The number of repetitions.
COMP Loop Statements Yi Hong May 21, 2015.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
1 Programming for Engineers in Python Autumn Lecture 8: Recursion.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
String and Lists Dr. José M. Reyes Álamo.
Introduction to Computing Science and Programming I
Introduction to C++ Programming Language
Topic: Iterative Statements – Part 1 -> for loop
Introduction to Python
Control Flow Constructs: Conditional Logic
CSE 341 Lecture 5 efficiency issues; tail recursion; print
Iterative Constructs Review
CS 115 Lecture 8 Structured Programming; for loops
Agenda Control Flow Statements Purpose test statement
Looping.
Chapter 4: Control Structures I (Selection)
For loops Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble Notes for 2010: I skipped slide 10. This is.
Topics Introduction to File Input and Output
CS1100 Computational Engineering
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
3 Control Statements:.
Module 4 Loops.
String and Lists Dr. José M. Reyes Álamo.
More Looping Structures
Unit 3 Test: Friday.
Chapter 6: Repetition Statements
15-110: Principles of Computing
For loops Taken from notes by Dr. Neil Moore
Topics Sequences Lists Copying Lists Processing Lists
The structure of programming
Introduction to Computer Science
Using C++ Arithmetic Operators and Control Structures
More Looping Structures
Topics Introduction to File Input and Output
While Loops in Python.
Class code for pythonroom.com cchsp2cs
REPETITION Why Repetition?
Introduction to Python
Control 9 / 25 / 19.
Presentation transcript:

Programming for Engineers in Python Lecture 2: Lists, Loops Autumn 2015-16

Admin Python installation status?

Last Week Highlights Memory and variables Different variables types (number, string, bool) Different operations for different types If-else statements if expression: statement1 else: statement2

Plan for today While loop Lists For loop

Algorithms and Pseudo Codes How can I get to the university in the morning?

Algorithms and Pseudo Codes How can I get to the university in the morning? Get up Drink coffee if there is time Get out of the house Walk for four blocks While waiting for the bus: play angry birds text friends 6. Get on the bus …

Think First, Code Later How can I get to the university in the morning? Get up Drink coffee if there is time Get out of the house Walk for four blocks While waiting for the bus: play angry birds text friends 6. Get on the bus …

While Loop Used to repeat the same instructions until a stop criterion is met while expression: statement1 statement2 … expression true false statement(s)

Example - factorial #factorial n = 7 fact = 1 i = 1 while i <= n: fact = fact * i i = i + 1 print n, "! = ", fact

Example – smallest divisor # Find the smallest divisor n = 2015 div = 2 while n % div != 0: div = div + 1 print "Smallest divisor of", n, "is", div Can the while loop above be infinite?

Infinite Loops i = 1 while i < 4: print i

Plan for today While loop Lists For loop

Lists A list is an ordered sequence of elements. Create a list in Python: >>> my_list = [2, 3, 5, 7, 11] >>> my_list [2,3,5,7,11]

Lists are Indexable Remember this? The same indexing + slicing works for lists! H e l o 1 2 3 4 5 -5 -4 -3 -2 -1

Lists are Indexable >>> my_list = [2, 3, 5, 7, 11] >>> my_list[0] 2 >>> my_list[4] 11 >>> my_list[-3] 5 >>> my_list[5] Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> my list[5] IndexError: list index out of range 11 7 5 3 2 4 1 -1 -2 -3 -4 -5

Slicing >>> my_list[1:5] # slicing [2, 3, 4, 5] >>> my_list[0:-1] # forward/backward indexing [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> my_list[::2] # add a step [1, 3, 5, 7, 9] 1 2 3 4 5 6 7 8 9 10 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Slicing # reverse >>> my_list[::-1] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] # output is an empty list. This is NOT an error >>> my_list[3:8:-2] [] # slicing does NOT change original list >>> my_list [1,2,3,4,5,6,7,8,9,10]

Lists Lists can contain strings: Lists can mix different types: >>> days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] >>> days[3] 'Wed' >>> len(days) 7 Lists can mix different types: >>> pi = ['pi', 3.14159, True] # student: name, age, height, SAT >>> student = ['Roi', 21, 1.83, 782]

Lists – Dynamic Maintain a list of the students either by name or by id: >>> students = ['Itay',9255587, 'Alon', 'Zohar',744554887] >>> students[2] 'Alon' Michal decided to join the course, so we update the list: # append - add an element to the end of the list >>> students.append('Michal') >>> students ['Itay', 9255587, 'Alon', 'Zohar', 744554887, 'Michal']

Lists – Dynamic Alon wants to leave the course: >>> students.remove('Alon') >>> students ['Itay', 9255587, 'Zohar', 744554887, 'Michal'] remove removes only the first occurrence of a value.

Nested Lists >>> mat = [ [1, 2, 3],[4, 5, 6] ] [4,5,6] >>> mat[1][2] 6 What is len(mat) ?

Nested Lists >>> family = [‘Meir‘, [‘Yossi‘, [‘Yuval‘, [‘Elisha‘]] ], [‘Yitzhak‘, [‘Meir‘], [‘Orna‘], [‘Evyatar‘] ], [‘Gavri‘, [’Uri‘], [‘Boaz‘]]]

Range >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] An ordered list of integers in the range. >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(from, to) contains all integers k satisfying from ≤ k < to. range(to) is a shorthand for range(0, to). >>> range(2,10) [ 2, 3, 4, 5, 6, 7, 8, 9] >>> range(-2,2) [-2, -1, 0, 1] >>> range(4,2) []

Range >>> type(range(3)) <type 'list'> Step size: range(from, to, step) returns: from, from+step, from+2*step,…, from+i*step until to is reached, not including to itself. >>> range(0,10,2) [0, 2, 4, 6, 8] >>> range(10,0,-2) [10, 8, 6, 4, 2]

Range >>> range(0, 10, -1) [] >>> range(0,10,0) Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> range(0,10,0) ValueError: range() step argument must not be zero

Plan for today While loop Lists For loop

For Loop for element in iterable: statement1 statement2 … Run over all elements in the iterable (list, string, etc.) Iteration 0: Assign element = iterable[0] Execute the statements Iteration 1: Assign element = iterable[1]

For Loop Note No infinite lists in Python  No infinite for loops! Indentation determines the scope of the iteration. Note No infinite lists in Python  No infinite for loops!

For Example Compute 1 + 2 + … + 100: >>> partial_sum = 0 >>> for i in range(1,101): partial_sum = partial_sum + i >>> print "The sum is", partial_sum The sum is 5050 Shortcut: sum(range(1,101))

For Example # factorial n = 8 fact = 1 for i in range(2, n+1): fact = fact * i print n, "! = ", fact Syntactic sugar: fact *= i is equivalent to fact = fact * i

Fibonacci series Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 Definition fib(0) = 0 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) en.wikipedia.org/wiki/Fibonacci_number Leonardo Fibonacci 1170-1250, Italy

סלט פיבונאצ'י

Fibonacci series Write a program that for an integer n > 0, prints the nth Fibonacci number.

Fibonacci series - code if n < 2: curr = n else: prev = 0 curr = 1 for i in range(2, n+1): new = prev + curr prev = curr curr = new print "The nth Fibonacci number is", curr

For Loop and Strings Iterate over strings: name = "Kobe" for letter in name: print "Give me", letter print "What did we get?", name Give me K Give me o Give me b Give me e What did we get?

Break – breaking loops break terminates the nearest enclosing loop, skipping the code that follows the break inside the loop. Used for getting out of loops when a condition occurs. Example: for elem in lst: if elem < 0: print "First negative number is", elem break

Break Example # Find smallest divisor using for loop: if n % div == 0: for div in range(2, n+1): if n % div == 0: break print div

Example - Prime n = 2013 for div in range(2,int(n**0.5)): if n % div == 0: break print n, "is not prime" else: print n, "is prime" range must accept argument of the type int so we perform casting on the result of the power operation.

Where is the bug?... n = ??? for div in range(2,int(n**0.5)): if n % div == 0: break print n, "is not prime" else: print n, "is prime"

Where is the bug?... n = 4 for div in range(2,int(n**0.5)+1): if n % div == 0: break print n, "is not prime" else: print n, "is prime"

Continue The continue statement, continues with the next iteration of the loop. Example - create a list of unique elements: >>> lst = [1,4,5,8,3,5,7,1,2] >>> uniques = [] >>> for x in lst:     if x in uniques:          continue     uniques.append(x) >>> print uniques [1,4,5,8,3,7,2]

for or while? In most cases it is more natural to use for In some cases it is better to use while for: Predefined number of iterations No need to initialize or advance the loop variable while: Unknown number of iterations Can specify a stop condition

Programming Style Why is it important? Comments: # Meaningful variables names Why is it important?

Bonus (if time allows) Python web environment: http://pythontutor.com/visualize.html - choose the option “render all objects on heap”. (http://www.codeskulptor.org/)