Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7."— Presentation transcript:

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

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

3 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.

4 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!"

5 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! ")

6 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

7 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

8 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!"

9 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.

10 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.

11 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)

12 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!"

13 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.

14 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

15 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

16 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

17 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.

18 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

19 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.

20 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.

21 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.

22 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 ***

23 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

24 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

25 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

26 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.

27 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)

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

29 Thank You ! Questions?


Download ppt "CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7."

Similar presentations


Ads by Google