Chapter 4 and 5 Flashcards
(52 cards)
Disadvantages of duplicating code
- makes program very large
- time consuming to write
- time consuming to correct/debug
A ____ loop is a condition-controlled loop
while
(repeats statements as long as the Boolean expression is True)
- when the expression becomes False, the program resumes statements AFTER the loop
- Helpful for input validation
A ____ loop is a count-controlled loop
for
repeats statement for a SPECIFIC number of times
How to write a while loop?
while expression:
set of statements
*expression is a Boolean expression (can use relational and logical operators)
- relational operators > < == != etc.
- logical operators or and not
- while loops need to INITIALIZE a variable (for loops do not)
- while loops need some way to terminate the loop (e.g. sentinel value)
What is “pretest” loop?
- loop tests a condition BEFORE performing an iteration
e. g. while
How to use the while loop to cycle through numbers?
e.g. print 1 through 10
- use a counter variable
- set counter = 1
while counter =< 10:
print(counter)
counter += 1
- will iterate 10 times
What type of loop is this:
number = 0
while number < 10:
print(‘I love to code’)
Infinite loop
- number never changes value and will always be less than 10
- No way to stop unless “INTERRUPTED” with CTRL C
Given thatnrefers to a positiveinteger,use awhileloopto compute the sum of the cubes of the firstncounting numbers, and associate this value withtotal. Use no variables other thann,k, andtotal.
n refers to positive integer
total = 0 k = 1 while k <= n: total += k**3 k += 1
In this exercise, use the following variables:i,lo,hi, andresult. Assume thatloandhieach are associated with anintegerand thatresultrefers to0.
Write awhileloop that adds the integers fromloup throughhi(inclusive), and associates the sum withresult.
Your code should not change the values associated withloandhi. Also, just use these variables:i,lo,hi, andresult.
e.g. lo = 3, hi = 6, result = 0
3 + 4 + 5 + 6
i = lo
while i <= hi:
result += i
i += 1
How to write a for loop?
for variable in range():
set of statements
or
for variable in [1, ‘hello’,3,’hi’]:
set of statements
- variable is called a Target Variable
Can you iterate a target varible in a for loop through strings?
Yes - numeric literals or string literals
Characteristics of the range() function?
range(end #)
- default start at 0
- default step value = 1
- increase up to but not including end #
e.g. range(10) means 0, 1, 2, 3 … 9
range(beg, end#)
- start at beg, increase up to but not including end #
e.g. range(4,10) means 4, 5, 6…9
range(beg, end, step#)
- start at beg
- increase by step # up to but not including end #
e.g. range(4, 10, 2) means 4, 6, 8
** to get 10 inside, do + 1 for ending value
e.g. range(4, 11, 2)
Write a for loop with the range function that prints the following output, name the target variable number:
0 100 200 300 400 500
for number in range(0, 501, 100):
print(number)
Write a loop to create a table:
Number Square ------------------------- 1 1 2 4 3 9
USE TABSSSS
#Print the table headings. print('Number\tSquare') print('-----------------------')
#print numbers 1 through 3 #and their squares
for num in range(1, 4):
square = num**2
print(num, ‘\t’, square)
Write a range call to create the following:
10 9 8 7 6 5 4 3 2 1
range(10, 0, -1)
- start at 10
- decrease by 1
- down to but not including 0
- starting value needs to be LARGER than ending value
- step value needs to be negative
(If starting value is not larger than ending value, then will display NOTHING)
How to keep a “running total” with each iteration of a loop?
- use a variable called an “accumulator”
- set total = 0 outside of the loop
Augmented Assignment Operators
Used when the variable on the left side of the = operator is also on the right side
- don’t need to type variable name twice
5 Augmented Assignment Operators: \+= -= *= /= %=
Sentinel value
Marks the END of a sequence of values
- when the program READS the sentinel value as an input from the user, it TERMINATES
- must be distinctive enough such that it isn’t a regular part of the sequence
e. g.
while lot != 0:
You want to know your grade in Computer Science, so write a program that continuously takes grades between 0 and 100 to standard input until you input”stop”, at which point it should print your average to standard output.
NOTE: When reading the input, do not display a prompt for the user. Use theinput()function with no prompt string. Here is an example:
grade = input() counter = 0 sum = 0
while grade != ‘stop’:
counter += 1
sum += int(grade)
grade = input()
print(sum/counter)
** Don’t FORGET int!!
Input validation loops
What is step to obtain the first input value called?
- keeps prompting user to enter the correct data (display error message, ask for new input)
- need a “priming read” to obtain the first input value
while ans != ‘Y’ and ans != ‘N’:
print(‘ERROR!’)
ans = input()
or
while score < 0:
print(‘ERROR!’)
score = float(input())
Garbage in Garbage out
If a user provides bad data (garbage) as input to a program, the program will process that bad data and, as a result, will produce bad data as output (garbage)
Nested loops - how does it work?
- think of a clock with the second hand moving faster than the minute hand, which moves faster than the hour hand
- inner loop runs completely for EVERY outer loop
- use of for loops
How many iterations does the inner loop go through:
for hours in range(24):
for minutes in range(60):
for seconds in range(60);
Hour loop = 24 times
Minute loop = 24*60 = 1440 times
Second loop = 246060 = 86,400 times
Total number of iterations = MULTIPLY # of iterations of all the loops
Nested Loops to create pattens:
- Outer loop?
- Inner loop?
Outer loop = rows
- need another print() to make a new line
Inner Loop = columns
for I in range(10):
print(‘*’, end=’’)
- arguments for inner loop range can be the target variable in the outer loop