CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

Loops (Part 1) Computer Science Erwin High School Fall 2014.
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Chapter 4 Repetitive Execution. 2 Types of Repetition There are two basic types of repetition: 1) Repetition controlled by a counter; The body of the.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Control Structures II (Repetition)
Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Fundamentals of Python: From First Programs Through Data Structures
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Fundamentals of Python: First Programs
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Programming Logic and Design Fifth Edition, Comprehensive
Chapter 5 Loops.
Flow of Control Part 1: Selection
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
The Software Development Process
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 13 Conditional.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
ITERATION. Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
Control Structures II Chapter 3
Chapter 5: Control Structure
Java Programming: Guided Learning with Early Objects
( Iteration / Repetition / Looping )
Incrementing ITP © Ron Poet Lecture 8.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Learning to Program in Python
MSIS 655 Advanced Business Applications Programming
Program Design Introduction to Computer Programming By:
Outline Altering flow of control Boolean expressions
Coding Concepts (Basics)
Repetition Control Structure
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Presentation transcript:

CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7

Repetition and loops The control structures that implement repetition, or iteration, are called loops Python has two loop structures  for loop  while loop

The for loop The for loop is simple to use but is not suitable for all situations. It can only be used when the number of times that the loop body is to be executed is fixed at the time of the loop's execution and this is not always the case. It cannot be used, for example, when the program needs to prompt a user repeatedly for input until the appropriate input is received.

The while Loop Here is a program that uses a while loop to prompt the user for a password. It repeatedly prompts until the correct password is entered. # password.py # Program prompts user to enter the password # until they do so correctly. print "Entry is password protected.", password = raw_input("Enter the password! ") while password != "python": print "Entry is password protected.", password = raw_input("Enter the password! ") print "Welcome!"

The while loop The only lines of code that are new to you in the above program are those that form the while loop structure: while password != "python": print "Entry is password protected.", password = raw_input("Enter the password! ")

The while loop The general form of the while loop in Python has the following syntax: while : When the Python interpreter encounters a while loop it first evaluates the Boolean expression. If the Boolean expression evaluates to True, the statements in the block are executed. If the Boolean expression evaluates to False, the statements in the block are not executed. Control passes to the next statement after the block The block can contain one statement or many statements. All statements in the block must be indented equally to associate them with the loop

The while loop If it still evaluates to True, the statements in the block are executed again. This process repeats until the Boolean expression no longer evaluates to True. As soon as it becomes False, Python passes control to the statement immediately following the block

The while loop # password.py # Program prompts user to enter the password # until they do so correctly. print "Entry is password protected.", password = raw_input("Enter the password! ") while password != "python": print "Entry is password protected.", password = raw_input("Enter the password! ") print "Welcome!"

Infinite loops In the password program once the user initially enters an incorrect password and the while loop is entered there is only one way to exit the loop. The correct password had to be entered. This was no problem for us, since we knew what it was, python. But suppose we didn't – the loop would not terminate – it would become an infinite loop.

Infinite loops In the password program once the user initially enters an incorrect password and the while loop is entered there is only one way to exit the loop. The correct password had to be entered. This was no problem for us, since we knew what it was, python. But suppose we didn't – the loop would not terminate – it would become an infinite loop. The password program can be made more practical by limiting the number of attempts that the user is allowed to input the correct password. This will be done as an exercise later in the chapter.

Input Validation The next program is logically very similar to the previous one. The while loop is again used to repeatedly prompt the user for integer input – this time until the input is of the appropriate size. Open the program validate.py in IDLE and Run it. The program requires the input integer to be between 5 and 10 inclusive (i.e. 5, 6, 7, 8, 9 or 10)

Input Validation # validate.py # Program prompts user to enter an integer between 5 and # 10 (inclusive) until they do so correctly. number = input("Enter an integer between 5 and 10 (inclusive): ") while number 10: print "Invalid input!", number = input("Enter an integer between 5 and 10 (inclusive): ") print "Thank-you!"

The Boolean Condition The Boolean condition this time is: number 10 We need a Boolean condition that will test True when user's input is inappropriate. Correct input is between 5 and 10 inclusive. Inappropriate input would be less than 5 or bigger than 10.

while VS for Loop In this chapter you will see conditional loops being used in a variety of programs. Most of these programs could not have been written using for loops. This is because the number of iterations of the loop that would be required was not fixed in advance of the loop's execution

while VS for Loop The reverse is not the case. Any program that can be written using a for loop can also be written using a while loop. As you will see, for loops are generally easier to write so we strongly recommend that you always a for loop where possible

2 Times table Using for loopUsing while loop # twoTimesTable.py # prints out the two times table #from 1 to 10 # using a for loop print "Two times table " for i in range (1,11): result = i * 2 print i, "x 2 =", result # twoTimesTable2.py # prints out the two times table #from 1 to 10 using # a while loop print "Two times table " i = 1 while i <= 10: result = i * 2 print i, "x 2 =", result i = i + 1

Comparing the two programs You should note that writing a while loop places more demands on the programmer. The programmer is now responsible for two essential tasks that the for loop did automatically:  initialising the loop control variable before entering the loop  updating its value during each iteration of the loop.

Comparing the two programs In the while loop program these two tasks are carried out by the statements: i = 1  which initialises the loop control variable before entering the loop and i = i + 1  which updates the value of the loop control variable inside the body of the loop

Comparing the two programs Failure to do either of these tasks will result in an error. If the first statement, i = 1 is omitted then the Boolean condition i <= 10 cannot be tested as i has not been given a value so an error message is generated. If the second statement i = I + 1 is omitted from the body of the while loop there is a major problem. because there are no statements in the body of the loop to alter the value of i, the condition, while i <= 10 remains True and the loop continues to execute for ever. An infinite loop results, there is no way out.

Constructing while loop When writing a while loop you must ALWAYS check that these two tasks have been satisfactorily carried out. You must always:  initialise the loop control variable before entering the loop  update the value of the loop control variable during each iteration of the loop.

Finding Errors As our programs become more complex it is highly likely they will initially contain logic errors. Two two strategies are described in Chapter 6 that you can adopt to try to find the cause of the problem.  The first uses the computer  The second just needs a pencil & paper.

Finding Errors 1. Try inserting extra print statements into your code to: keep track of the value of a variable or variables before, during and after the execution of the loop. to track the value of i in twoTimesTable2.py extra print statements can be added identify these tracking statements in some way so they are easy to delete later, when the problem is resolved, – here we have begun them using ***

Finding Errors print "Two times table " i = 1 print "***Before the loop: i = ", i while i <= 10: print "***At the start of iteration", i, "i = ", i result = i * 2 print i, "x 2 =", result i = i+1 print "***After the loop: i = ", i

Finding Errors print "Two times table " i = 1 print "***Before the loop: i = ", i while i <= 10: print "***At the start of iteration", i, "i = ", i result = i * 2 print i, "x 2 =", result i = i+1 print "***After the loop: i = ", i

Finding Errors 2. Tracing code by hand is a very useful skill: We have been doing this on the white-board Not only is it useful for finding an error in a piece of code at a time when computer access is not possible it also improves your ability to write code by getting you to focus on what each line of code actually does. one way to trace the program twoTimesTable2.py on paper a) Begin by drawing a table with a column heading for each of the variables, the loop condition and the screen output as follows: iresulti <= 10screenoutput

Finding Errors b) Every time an assignment statement is executed, update the value in the column for the variable on its left hand side every time a print statement is executed, write down the output it produces. use a new line for each statement that results in the table being changed.

Finding Errors c) A horizontal line is drawn before each iteration of a loop body and another after exiting the loop. Tracing twoTimesTable2.py would result in the following table: (This is only shown for the first three iterations of the body of the loop to explain the concept but is complete in your booklet)

Hand tracing 2 times table iresult1 <= 10Screen output 12true1 X 2 = 2 24true2 X 2 = 4 36true3 X 2 = 6 48true4 X 2 = 8

Thank You ! Questions?