Lecture 12 – Loops – while loops COMPSCI 1 1 Principles of Programming.

Slides:



Advertisements
Similar presentations
Programming In C++ Spring Semester 2013 Lecture 3 Programming In C++, Lecture 3 By Umer Rana.
Advertisements

CS107 Introduction to Computer Science Lecture 3, 4 An Introduction to Algorithms: Loops.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.1 Chapter 5 Loops.
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Introduction to Computing Science and Programming I
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Decisions in Python elif. A new keyword elif A contraction of “else if” Used to tie two if statements (or more) together into one structure Syntax – elif,
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
INTRODUCTION TO PYTHON PART 3 - LOOPS AND CONDITIONAL LOGIC CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
Lecture 11 – if … else, if... elif statements, nested ifs COMPSCI 1 1 Principles of Programming.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Lecture 13 – range function, for…in loops COMPSCI 1 1 Principles of Programming.
Python quick start guide
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Flow of Control. 2 Control Structures Control structure: An instruction that determines the order in which other instructions in a program are executed.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
CPS120 Introduction to Computer Science Iteration (Looping)
Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.
CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Course A201: Introduction to Programming 09/16/2010.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Chapter 3: Branching and Program Flow CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
Repetition and Iteration ANSI-C. Repetition We need a control instruction to allows us to execute an statement or a set of statements as many times as.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Designing While Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
Repetition Control Structure. Introduction Many applications require certain operations to be carried out more than once. Such situations require repetition.
Lecture 15 – more on lists and for…in loops, the split() function COMPSCI 1 1 Principles of Programming.
5 While-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
Control Structures WHILE Statement Looping. S E Q C E N U E REPITITION …a step or sequence of steps that are repeated until some condition is satisfied.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Control Flow (Python) Dr. José M. Reyes Álamo.
Python: Control Structures
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Loops CIS 40 – Introduction to Programming in Python
Design and Implementation
Repetition Control Structure
Chapter 5 Loops.
3. Decision Structures Rocky K. C. Chang 19 September 2018
Selection Statements.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Conditional and iterative statements
PYTHON: BUILDING BLOCKS Sequencing & Selection
Flow of Control.
The structure of programming
CMPT 120 Lecture 13 – Unit 2 – Cryptography and Encryption –
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Lecture 12 – Loops – while loops COMPSCI 1 1 Principles of Programming

 At the end of this lecture, students should:  understand the concept of a loop for defining repeated tasks  understand the structure of a while loop, i.e.,  the loop initialisation  the body of the loop  the loop condition  the loop increment  be able to design and write Python while loops Learning outcomes CompSci Principles of Programming2

Recap  From lecture 11  the if block of an if…else statement is executed only if the boolean expression evaluates to True, otherwise the else block is executed.  if…elif statements are useful if there is a situation where at most one option is to be selected from many options. The if…elif statement has an optional final else part. def get_random_horoscope(): number = random.randrange(0, 10) if number < 4: return "Amazing day ahead" elif number < 7: return "Romance is very likely" elif number < 8: return "Proceed with caution" return "Lucky lucky you" def main(): print("Today's message:", get_random_horoscope()) main() def get_random_horoscope(): number = random.randrange(0, 10) if number < 4: return "Amazing day ahead" elif number < 7: return "Romance is very likely" elif number < 8: return "Proceed with caution" return "Lucky lucky you" def main(): print("Today's message:", get_random_horoscope()) main() Today's message: Romance is very likely Today's message: Amazing day ahead CompSci Principles of Programming3

Control structures  We want to understand how the computer works its way through a program, finding which instruction to execute next.  Control structures allow us to change the flow of statement execution in our programs. So far we have looked at selection statements (if statements). Selection or if statements are also called branches, as, when the program arrives at an if statement, control will "branch" off into one of two or more "directions".  Now we will look at another control structure, iteration. Iteration means that the same code is executed repeatedly.  Some examples where iteration is required are:  User login – asking for the password until the correct one is given  Menu option control – menu options are repeatedly displayed and processed until the ‘exit’ option was selected CompSci Principles of Programming4

Iteration – while loops  We use loops to implement iteration.  How does the while loop execute? while boolean_expression: statement1 statement2 statement3 … If the condition is true loop body condition If the condition is false First, the condition is tested. If the condition is true, the loop statements (the loop body) are executed. After the loop statements (loop body) have been executed, control returns to top of the loop, and the condition is tested again. As long as the condition is true, the loop statements will be executed. CompSci Principles of Programming5

while loop - example def print_lines(): count = 0 while count < 100: print("Programming is fun!") count = count + 1 def main(): print_lines() main() def print_lines(): count = 0 while count < 100: print("Programming is fun!") count = count + 1 def main(): print_lines() main() Programming is fun! … Programming is fun! If the condition is true If the condition is false count = 0 count < 100 print("Programming is fun!") count = count + 1 When the condition becomes False the control moves on to the code after the loop. CompSci Principles of Programming6

while loop - terminology def print_lines(): count = 0 while count < 100: print("Programming is fun!") count = count + 1 print("Done!") def main(): print_lines() main() def print_lines(): count = 0 while count < 100: print("Programming is fun!") count = count + 1 print("Done!") def main(): print_lines() main() Programming is fun! … Done! Initialisation: anything which needs to be done before the loop starts. body: the statements which are to be executed over and over (or not at all). condition: a boolean expression which is test repeatedly to determine whether the body of the loop should be executed or not. increment: this changes the loop variable so that eventually the condition becomes false. Remember that a loop will only stop when the condition is false. initialisation condition CompSci Principles of Programming7 increment body

while loop - terminology  Sometimes we don't need an overt increment statement, e.g., def total_user_numbers(): total = 0 number = int(input("Enter a number (0 to end): ")) while number != 0: total += number number = int(input("Enter a number (0 to end): ")) print("Total: ", total) def main(): total_user_numbers() main() def total_user_numbers(): total = 0 number = int(input("Enter a number (0 to end): ")) while number != 0: total += number number = int(input("Enter a number (0 to end): ")) print("Total: ", total) def main(): total_user_numbers() main() Enter a number (0 to end): 5 Enter a number (0 to end): 6 Enter a number (0 to end): 2 Enter a number (0 to end): 4 Enter a number (0 to end): 0 Total: 17 CompSci Principles of Programming8

Give the output def show_output(): number = 1 count = 10 value = 4 while count > 4: count = count - 2 print(str(number) + ":", count, value) value += count number += 1 print() print(str(number) + ":", count, value) def main(): show_output() main() def show_output(): number = 1 count = 10 value = 4 while count > 4: count = count - 2 print(str(number) + ":", count, value) value += count number += 1 print() print(str(number) + ":", count, value) def main(): show_output() main() CompSci Principles of Programming9

Complete the function  For an integer, a divisor is a number which divides exactly into the integer (a factor of the integer), e.g., the divisors of 6 are 1, 2, 3, 6. Complete the get_divisor_string() function. def get_divisor_string(number): def main(): print(get_divisor_string(24)) print(get_divisor_string(25)) print(get_divisor_string(5628)) main() def get_divisor_string(number): def main(): print(get_divisor_string(24)) print(get_divisor_string(25)) print(get_divisor_string(5628)) main() CompSci Principles of Programming10

Complete the function  The following function throws a number of dice (given by num_dice_throws) and counts how often a particular dice (given by dice_to_check) occurs. Complete the get_dice_throws_result() function. def get_dice_throws_result(num_dice_throws, dice_to_check): def main(): print(get_dice_throws_result(30000, 6), "sixes thrown (out of throws)") print(get_dice_throws_result(6, 6), "sixes thrown (out of 6 throws)") print(get_dice_throws_result(600000, 6), "sixes thrown (out of throws)") main() def get_dice_throws_result(num_dice_throws, dice_to_check): def main(): print(get_dice_throws_result(30000, 6), "sixes thrown (out of throws)") print(get_dice_throws_result(6, 6), "sixes thrown (out of 6 throws)") print(get_dice_throws_result(600000, 6), "sixes thrown (out of throws)") main() 4913 sixes thrown (out of throws) 0 sixes thrown (out of 6 throws) sixes thrown (out of throws) CompSci Principles of Programming11

Complete the function  A perfect number is an integer that is equal to the sum of its divisors (excluding the number itself), e.g., 28 = Complete the following two functions. The check_perfection prints either ' # is a perfect number' or '# is NOT a perfect number'. def get_divisor_sum(number): def check_perfection(number): def main(): check_perfection(28) check_perfection(54) check_perfection(496) main() def get_divisor_sum(number): def check_perfection(number): def main(): check_perfection(28) check_perfection(54) check_perfection(496) main() 28 is a perfect number 54 is NOT a perfect number 496 is a perfect number CompSci Principles of Programming12

Complete the function  The following function should return a number (from the user) which is within (both inclusive) the two numbers passed as parameters. Complete the get_legal_number() function: def get_legal_user_num(lower, upper): prompt = "Enter a number (" prompt += str(lower) + "-" + str(upper) + "): " def main(): print(get_legal_user_num(0, 6)) print(get_legal_user_num(10, 20)) print(get_legal_user_num(1, 2)) main() def get_legal_user_num(lower, upper): prompt = "Enter a number (" prompt += str(lower) + "-" + str(upper) + "): " def main(): print(get_legal_user_num(0, 6)) print(get_legal_user_num(10, 20)) print(get_legal_user_num(1, 2)) main() Enter a number (0-6): -1 Enter a number (0-6): 8 Enter a number (0-6): 6 6 Enter a number (10-20): Enter a number (1-2): 3 Enter a number (1-2): 0 Enter a number (1-2): 2 2 CompSci Principles of Programming13

Complete the function  The following function keeps prompting the user to guess a hidden number until the user correctly guesses the number. At each guess the function lets the user know if the guess is too high or too low. The function also keeps track of (and prints) the number of guesses. Complete the user_number_guess() function: def user_number_guess(computer_num): prompt = "Enter your guess (1 - 99): " def main(): user_number_guess(random.randrange(1, 100)) main() def user_number_guess(computer_num): prompt = "Enter your guess (1 - 99): " def main(): user_number_guess(random.randrange(1, 100)) main() Enter your guess (1 - 99): 50 Too high Enter your guess (1 - 99): 25 Too high Enter your guess (1 - 99): 13 Too low Enter your guess (1 - 99): 20 Too low Enter your guess (1 - 99): 23 Correct! Number of guesses: 5 CompSci Principles of Programming14

Summary  In a Python program:  a loop is used for implementing repeated tasks  a loop has four parts  the loop initialisation  the body of the loop  the loop condition  the loop increment  a while loop has the following syntax: while boolean_expression: statement1 statement2 … CompSci Principles of Programming15

Examples of Python features used in this lecture def get_divisor_sum(number): divisor = 1 div_sum = 0 while divisor <= number // 2: if number % divisor == 0: div_sum += divisor divisor += 1 return div_sum def fun_stuff(): count = 0 while count < 4: print("Programming is fun!") count = count + 1 CompSci Principles of Programming16