Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Similar documents
Functions and Recursion

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Unit 2. Srinidhi H Asst Professor

The second statement selects character number 1 from and assigns it to.

Chapter 7. Iteration. 7.1 Multiple assignment

Conditionals and Recursion. Python Part 4

Week - 01 Lecture - 03 Euclid's Algorithm for gcd. Let us continue with our running example of gcd to explore more issues involved with program.

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

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

DM536 Introduction to Programming. Peter Schneider-Kamp.

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

At full speed with Python

Text Input and Conditionals

Introduction to Python (All the Basic Stuff)

Conditionals !

Lecture Notes on Contracts

Names and Functions. Chapter 2

Repetition, Looping CS101

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

Decisions, Decisions. Testing, testing C H A P T E R 7

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CS 1301 CS1 with Robots Summer 2007 Exam 1

1/11/2010 Topic 2: Introduction to Programming 1 1

LOOPS. Repetition using the while statement

Python: Functions. Thomas Schwarz, SJ Marquette University

DM536 Introduction to Programming. Peter Schneider-Kamp.

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

CS1 Lecture 3 Jan. 18, 2019

Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution

Conditionals: Making Choices

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

CS 102 Lab 3 Fall 2012

Week - 01 Lecture - 04 Downloading and installing Python

Python for Informatics

Controls Structure for Repetition

Compound Data Types 1

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

Variables, expressions and statements

Flow Control: Branches and loops

CS 106 Introduction to Computer Science I

If Statements, For Loops, Functions

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?

Topic 2: Introduction to Programming

(Refer Slide Time: 00:26)

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

How to Design Programs

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

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Repetition CSC 121 Fall 2014 Howard Rosenthal

CSCE 110: Programming I

Lecture Notes for Chapter 2: Getting Started

Built-in functions. You ve used several functions already. >>> len("atggtca") 7 >>> abs(-6) 6 >>> float("3.1415") >>>

Compound Data Types 2

Units 0 to 4 Groovy: Introduction upto Arrays Revision Guide

Solutions to the Second Midterm Exam

Introduction to Python Programming

COMPSCI 230 Discrete Math Prime Numbers January 24, / 15

Programming Training. Main Points: - Python Statements - Problems with selections.

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Chapter 5: Control Structures

CS1 Lecture 3 Jan. 22, 2018

AP Computer Science A

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

ELEMENTARY NUMBER THEORY AND METHODS OF PROOF

CS 115 Lecture 4. More Python; testing software. Neil Moore

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES

1 Elementary number theory

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

CS 1301 Exam 1 Answers Fall 2009

Introduction. C provides two styles of flow control:

Control structure: Repetition - Part 2

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

Register Machines. Connecting evaluators to low level machine code

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself.

More Programming Constructs -- Introduction

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Real Python: Python 3 Cheat Sheet

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists

Chapter 9: Dealing with Errors

STUDENT LESSON A12 Iterations

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

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

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

SNS COLLEGE OF ENGINEERING,

Problem Solving for Intro to Computer Science

Reading 8 : Recursion

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Python for Non-programmers

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Test #2 October 8, 2015

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

Transcription:

Iteration Chapter 7 Prof. Mauro Gaspari: gaspari@cs.unibo.it

Multiple assigments bruce = 5 print bruce, bruce = 7 print bruce

Assigment and equality With multiple assignment it is especially important to distinguish between an assignment operation (=) and a statement of equality (==). Equality is a symmetric relation and assignment is not. Furthermore, in mathematics, a statement of equality is either true or false, for all time. If a = b now, then a will always equal b. In Python, an assignment statement can make two variables equal, but they don t have to stay that way: a = 5 b = a # a and b are now equal a = 3 # a and b are no longer equal

Updating variables One of the most common forms of multiple assignment is an update, where the new value of the variable depends on the old. X = X + 1 If you try to update a variable that doesn t exist, you get an error. Before you can update a variable, you have to initialize it, usually with a simple assignment: Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.

Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. We can program repetition with recursion, however: The programming task is sometimes difficult. Maximum recursion depth problem. Python provides several language features to make repetition easier. One is the while statement and another is the for statement.

The while statement: def countdown(n): while n > 0: print n n = n 1 print "Blastoff!" Note: recursion is not used. You can almost read the while statement as if it were English. It means, While n is greater than 0, display the value of n and then reduce the value of n by 1. When the condition becomes false the while terminates and the next instruction is executed.

Semantics of while 1) Evaluate the boolean condition. 2) If the condition is false, exit the while statement and continue execution at the next statement. 3) If the condition is true, execute the body and then go back to step 1. This type of flow is called a loop because the third step loops back around to the top. The body of the loop should change the value of one or more. variables so that eventually the condition becomes false and the loop terminates. Otherwise the loop will repeat forever (infinite loop).

Examples def nlines(n): while n!= 0: print n = n 1 What happens if you remove the last line?

Try this example while True: print Sorry

break Sometimes you don t know it s time to end a loop until you get half way through the body. In that case you can use the break statement to jump out of the loop. Suppose you want to take input from the user until they type exit. while True: line = raw_input('>> ') if line == 'exit': break print line print 'Stopped!'

Exercise 1 Write a dummy python interpreter using while and break to exit. The dummy interpeter returns False when reads True and viceversa, otherwise always returns syntax error.

Tables One of the things loops are good for is generating tabular data. Tables can be useful for displaying financial data. As characters and strings are displayed on the screen, an invisible marker called the cursor keeps track of where the next character will go. After a print statement, the cursor normally goes to the beginning of the next line. The tab character shifts the cursor to the right until it reaches one of the tab stops. Tabs are useful for making columns of text line up.

Example of a table The following program outputs a sequence of values in the left column and their logarithms in the right column: import math x = 1.0 while x < 20.0: print x, '\t', math.log(x) x = x + 1.0

Considerations Remember that the log function uses base e. Since powers of two are so important in computer science, we often want to find logarithms with respect to base 2. To do that, we can use the following formula: log 2 (x) = log e (x)/log e (2) The log 2 table can be computed changing the output statement to: print x, '\t', math.log(x)/math.log(2.0)

Exercise 2 Modify the program to show logarithms of other powers of two only. Hint: x should be a power of two.

A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: Example >>> fruit = "banana" >>> letter = fruit[1] >>> print letter a The expression in brackets is called an index. Why 'a'??? The first letter of banana is not 'a'.

Understanding strings The index is an offset from the beginning of the string, and the offset of the first letter is 0. So if a string has n chars its indexes ranges from 0 to n-1. You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. >>> letter = fruit[0] >>> letter2 = banana [0] >>> print letter b >>> type(letter) <type 'str'> >>> print letter2 b

Length of a string: len >>> fruit = "banana" >>> len(fruit) 6 Accessing the last letter: length = len(fruit) last = fruit[length] last = fruit[length 1] # ERROR!

Traversal with a for loop index = 0 while index < len(fruit): letter = fruit[index] print letter index = index + 1 It is possible to specify this in this way: for char in fruit: print char

Example >>>prefixes = "JKLMNOPQ" >>>suffix = "ack" >>>for letter in prefixes:... print letter + suffix Jack Kack Lack Mack Nack Oack Pack Qack

Exercise 3 Write a function indent_string(n,string) which prints the string n+1 times indenting it from 0 to n as follows: indent_string(5, duffy ) duffy duffy duffy duffy duffy duffy n+1 Hint: use the expression ' '*i to print i blanks.

Exercise 4 GREATEST COMMON DIVISOR IMPERATIVE KNOWLEDGE (EUCLID) IF A<B, exchange A and B. Divide A by B and get the remainder, R. If R=0, GCD(A,B) = B. Replace A by B and replace B by R. Return to the previous step. Write a function gcd that takes two arguments and returns the greatest common divisor.