Chapter 4 and 5 Flashcards

(52 cards)

1
Q

Disadvantages of duplicating code

A
  • makes program very large
  • time consuming to write
  • time consuming to correct/debug
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

A ____ loop is a condition-controlled loop

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

A ____ loop is a count-controlled loop

A

for

repeats statement for a SPECIFIC number of times

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to write a while loop?

A

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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is “pretest” loop?

A
  • loop tests a condition BEFORE performing an iteration

e. g. while

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to use the while loop to cycle through numbers?

e.g. print 1 through 10

A
  • use a counter variable
  • set counter = 1

while counter =< 10:
print(counter)
counter += 1

  • will iterate 10 times
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What type of loop is this:

number = 0
while number < 10:
print(‘I love to code’)

A

Infinite loop

  • number never changes value and will always be less than 10
  • No way to stop unless “INTERRUPTED” with CTRL C
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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.

A

n refers to positive integer

total = 0
k = 1
while k <= n:
    total += k**3
    k += 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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

A

i = lo

while i <= hi:
result += i
i += 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to write a for loop?

A

for variable in range():
set of statements
or

for variable in [1, ‘hello’,3,’hi’]:
set of statements

  • variable is called a Target Variable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Can you iterate a target varible in a for loop through strings?

A

Yes - numeric literals or string literals

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Characteristics of the range() function?

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Write a for loop with the range function that prints the following output, name the target variable number:

0
100
200
300
400
500
A

for number in range(0, 501, 100):

print(number)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Write a loop to create a table:

Number    Square
-------------------------
1                  1
2                 4
3                 9
A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Write a range call to create the following:

10
9
8
7
6
5
4
3
2
1
A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to keep a “running total” with each iteration of a loop?

A
  • use a variable called an “accumulator”

- set total = 0 outside of the loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Augmented Assignment Operators

A

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:
\+= 
-=
*=
/= 
%=
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Sentinel value

A

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:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

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:

A
grade = input()
counter = 0
sum = 0

while grade != ‘stop’:
counter += 1
sum += int(grade)
grade = input()

print(sum/counter)

** Don’t FORGET int!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Input validation loops

What is step to obtain the first input value called?

A
  • 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())

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Garbage in Garbage out

A

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)

22
Q

Nested loops - how does it work?

A
  • 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
23
Q

How many iterations does the inner loop go through:

for hours in range(24):
for minutes in range(60):
for seconds in range(60);

A

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

24
Q

Nested Loops to create pattens:

  • Outer loop?
  • Inner loop?
A

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
25
What will the following program display? for r in range(8): for c in range(r + 1): print('*', end='') print()
r = 0, c goes through range(1), c = 0 * r = 1, c = goes through range(2), c = 0, 1 ** r = 7, c goes through range (8), c = 0, 1, 2, ... 7 ******** ``` therefore output: * ** *** **** ***** ****** ******* ******** ```
26
Define function
a GROUP of statements that perform a SPECIFIC TASK - "Divide and conquer" - "Modularized program"
27
Benefits of using functions
1. Simpler code to READ 2. Can REUSE code (reduce duplication) 3. Better TESTING an DEBUGGING 4. FASTER development 5. Easier facilitation of TEAMWORK *for COMMON tasks
28
Void versus value returning functions
Void function -> do not return a value to the statement that called the function - just terminates after executing statements Value Returning Function returns a value to the statement that called it - uses return keyword
29
Function definition format: - function header - Block
``` def functionName(parameters): block of statements ```
30
Function naming convention | 6 rules
- Same rules as variable naming conventions - First character must be _, lower or upper case letters - subsequent characters can be _, lower or upper case letters, or numbers - no special characters - case sensitive - no spaces - no python keyword
31
Calling functions and jumping back and forth?
- call a function by simply typing function name and ALL parameters (can't miss any parameters) e. g. main() - when the function is called, the interpreter JUMPS TO that function and executes the statements in the block - once it finishes executing, the interpreter jumps BACK to the PART of the program that called it and continues
32
What does this function print out: ``` def main(): print('Hello') message() print('Bye!') ``` ``` def message(): print('I am here') compliment() print('Okay') ``` ``` def compliment(): print('You are cute') ``` main()
``` Hello I am here You are cute Okay Bye! ```
33
Symbol for flowcharting functions
Rectangle with two black lines on the sides
34
How to slow down a program so that the user can read everything at their own speed?
input('Press enter to continue') - don't set input to anything
35
Local variable features
- created WITHIN a function and can only be used WITHIN that function - Local scope - error will occur if other functions try to use that same variable - you can have local variables with the SAME NAME in different functions
36
How to pass arguments to functions
1. Pass by Value (of the parameter) - relies on POSITION of the parameter variable - can pass STRINGS, VARIABLES, and NUMBERS as argument e.g. doMath(12, 14) def do Math(width, length) 2. By Keyword Argument - specifies which parameter variable the argument should be assigned to e. g. doMath(length = 14, width = 12) - keyword arguments do not match the order of the parameters, this is okay! The position in the function call DOES NOT MATTER when calling by Keyword Argument 3. By mix of keyword arguments and positional arguments - pass by position first - then pass by keyword argument e. g. show_interest(1000, rate=0.01, periods=10) - 1000 matches with the first parameter variable
37
Why should you avoid global variables?
1. Global variables make DEBUGGING difficult - Hard to track down every statement that accesses the global variable 2. Functions using global variables are usually DEPENDENT on the global variables - Can't use the same function in a different program 3. Global variables make the program HARD to understand - Can be MODIFIED by any statement in a program
38
Can you use global constants?
Yes
39
Examples of library functions
Pre-written by Python Stored in a MODULE which you have to IMPORT e.g. math, random can we thought of as a BLACK BOX
40
Random functions random.randint
import random random.randint(low, high) --> generates a random NUMBER between low and high, inclusive E.g. simulate a coin toss (set Heads = 1, Tails = 2)
41
Random functions random.randrange
import random random. randrange(start, end, step) - returns a random integer from start up to but not including end, step value
42
Random functions random.uniform
import random random.uniform(low, high) --> randomly generated FLOATING-POINT number through RANGE low to high (beyond 1.0)
43
Random functions random.random
import random random. random() - returns a random floating point number in range 0.0 up to but not including 1.0
44
Random functions random.seed
import random random. seed(#) - a seed value (typically set to the system time of the computer's internal clock) determines the series of random numbers - if the same seed value is used, the random numbers generate the SAME SEQUENCE of random numbers e. g. 58 43 57 21
45
Void function does not return a value (T/F)
F - returns "None"
46
Write a print statement that displays a random integer between 5 and 5000 assume the random library is imported
random.randint(5, 5000)
47
Write a print statement that displays a random floating-point number within the range of 10.0 through 14.99 Assume that random library is imported.
random.uniform(10.0, 14.99)
48
What is the defining feature of value returning functions?
Must have a return statement (return an expression, boolean, string, numbers, variables) - after the function reaches the return statement, a value is returned back to the statement that called it (function ends execution) - can be printed, used in a mathematical expression, and even formatted
49
How to set up functions that return multiple values return decision1, decision2
Separate with COMMAS In the function: return expression1, expression2, etc. Back at the function: - need MORE VARIABLES TO COLLECT returned values e.g. FirstName, LastName = functionCall()
50
You should define new functions within functions
FALSE | - all function definitions should be on the same level of indentation
51
What happens to this output: ``` def myFun(length, width, colour) return length*width ``` myFun(70, 40)
ERROR | - not enough arguments
52
How do you use a global variable?
You can use the global variable from inside functions (without needing to pass it through as an argument). HOWEVER, if you want to make CHANGES to the global variable, you must DECLARE IT inside the function like so: global variable_name