Title | Invitation to computer science (CS1001) Lecture 07 |
---|---|
Author | Chloe Briand |
Course | Intro Computer Science |
Institution | Memorial University of Newfoundland |
Pages | 7 |
File Size | 48.2 KB |
File Type | |
Total Downloads | 58 |
Total Views | 138 |
This is the lecture notes of CS 1001: Invitation to computer science 7th edition. This will help students prepare for their midterm and final. Lecture 07...
Computer Science 1001 Lecture 7 Jan. 19, 2018 Lecture Outline • Flow control: repetition
– CS1001 Lecture 7 –
Example: prime numbers • Consider the problem of determining whether a given number, num is prime (ie. is divisible only by 1 and itself). • One approach to this problem is to check whether num is divisible by 2, 3, 4, . . . . • An algorithm might look like: 1. Get value for num from user. 2. Set divisor = 2. 3. Check if num is divisible by divisor. – if divisible then num is not prime, go to step 4. – if not divisible then add 1 to divisor and repeat step 3. 4. Output the result (prime or not prime). • But when can we stop adding 1 to divisor?
– CS1001 Lecture 7 –
1
Example: prime numbers # Check if a number is a prime number from math import * num = int(input("Enter a number > 1 ")) isPrime = True divisor = 2 while isPrime and divisor 1: while isPrime and divisor = 0: sum += number number = int(input("Next number: ")) print("The total is",sum)
• Here, we are adding positive values, so any negative value can be used to terminate the loop.
– CS1001 Lecture 7 –
6...