Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.

Slides:



Advertisements
Similar presentations
Introduction to Computing Science and Programming I
Advertisements

I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Computer Science 1620 Loops.
1 Gentle Introduction to Programming Session 2: Functions.
Lecture 12 Another loop for repetition The while loop construct © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
1 Agenda - Loops while for for & while Nested Loops do-while Misc. & Questions.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Fundamentals of Python: From First Programs Through Data Structures
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
The University of Texas – Pan American
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
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.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
General Programming Introduction to Computing Science and Programming I.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
Programming Training Main Points: - Problems with repetitions. - Discuss some important algorithms.
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b WHILE.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Lists Computers and Programming. Agenda What is a list? How to access elements in the list? The for statement Operations on lists Looping with.
If statements while loop for loop
More While Loop Examples CS303E: Elements of Computers and Programming.
Built-in Data Structures in Python An Introduction.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Chapter 4: Control Structures II
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
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.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
COMP Loop Statements Yi Hong May 21, 2015.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
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.
Control flow Ruth Anderson UW CSE 160 Winter
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.
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.
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
String and Lists Dr. José M. Reyes Álamo.
Introduction to C++ Programming Language
Topic 6 Recursion.
Topic: Iterative Statements – Part 1 -> for loop
CSE 341 Lecture 5 efficiency issues; tail recursion; print
Programming for Engineers in Python
While Loops in Python.
Topics Introduction to Repetition Structures
Ruth Anderson UW CSE 160 Winter 2017
Looping.
CS1100 Computational Engineering
The University of Texas – Pan American
Ruth Anderson UW CSE 140 Winter 2014
Module 4 Loops.
String and Lists Dr. José M. Reyes Álamo.
More Looping Structures
For loops Taken from notes by Dr. Neil Moore
Using C++ Arithmetic Operators and Control Structures
More Looping Structures
While Loops in Python.
REPETITION Why Repetition?
COMPUTING.
Presentation transcript:

Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1

2 Plan for today While loop Lists For loop

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

4 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? 5

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

7 Plan for today Highlights from last week 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] 8

Lists are Indexable Remember this? The same indexing + slicing works for lists! 9

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 " ", line 1, in my list[5] IndexError: list index out of range

Slicing >>> my_list = [1,2,3,4,5,6,7,8,9,10] >>> 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] 11

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] 12

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

Lists – Dynamic Maintain a list of the students either by name or by id: >>> students = ['Itay', , 'Alon', 'Zohar', ] >>> 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', , 'Alon', 'Zohar', , 'Michal'] 14

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

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

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

Range 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) [] 18

Range >>> type(range(3)) 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] 19

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

21 Plan for today Highlights from last week While loop Lists For loop

For Loop for element in iterable: statement 1 statement 2 … 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] Execute the statements … 22

For Loop 23

For Example Compute … + 100: The sum is 5050 Shortcut: sum(range(1,101)) 24

25 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

26 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_numberLeonardo Fibonacci , Italy

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

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

29 Fibonacci series - code n = 10 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

30 Fibonacci – Another Code n = input(“Insert a non-negative number") fibs = [0, 1] for i in range(2, n + 1): fibs.append(fibs[-1] + fibs[-2]) print fibs[n] Is shorter code necessarily better? What about memory consumption?

For loop – Average # Average ages = [19, 22, 20] sum_ages = 0 for age in _____: ____________ sum_ages = sum_ages/len(ages) 31 ages sum_ages += age

For loop – Average Distance start_points = [5, 2, 8] end_points = [15, 14, 21] num_points = len(end_points) sum_dist = 0 for i in ____________: ____________________ sum_dist = sum_dist / num_points 32 range(num_points) sum_dist += end_points[i] – start_points[i]

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? 33

Example: Change Elements in List lst = [1, 4, 3, 6, 8] # we want to zero every odd element. 34 # take 2 inds_lst = range(len(lst)) for ind in inds_lst: if lst[ind] % 2 == 0: lst[ind] = 0 print lst # take 1 for elem in lst: if elem % 2 == 0: elem = 0 print lst

For loop – Think First! Given a sequence seq, we’ve seen 2 ways to go over it using a for loop: 1.Go over the elements of seq directly. for elem in seq: … # Do something with elem. 2.Go over the indexes of seq: for i in range(len(seq)): … # Do something with seq[i]. Before writing a for loop – choose the form which works better for you. 35

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 36

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

38 Example - Prime n = 2013 for div in range(2,int(n**0.5)): if n % div == 0: break if n % div == 0: 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.

Continue 39 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]

40 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

Let’s Play! secret = input(“Choose a number: ”)) while True: guess = input("Enter guess: ")) if _______________: break elif ______________: print "Try a higher number" else: print "Try a lower number" print "Right!" 41 guess == secret guess < secret Player 1 Player 2 Hint (sample output) Choose a number: 34 Enter guess: 100 Try a lower number Enter guess: 50 Try a lower number Enter guess: 25 Try a higher number Enter guess: 35 Try a lower number Enter guess: 34 Right! Hint (sample output) Choose a number: 34 Enter guess: 100 Try a lower number Enter guess: 50 Try a lower number Enter guess: 25 Try a higher number Enter guess: 35 Try a lower number Enter guess: 34 Right!

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

43 Exercise – Integer Division Input: Two positive integers – A and B Output: How many times A contains B (the result of the integer division A/B) Do not use the operators ‘/’, ‘*’

44 Exercise – Power of Two Input: a positive integer A Output: If there is an integer N such that A == 2 N then print N, otherwise print a suitable message.

45 Write a program that prints an upside-down triangle of *. Input: The height of the triangle. ***** *** ** **** * Exercise – Triangle Printout