1/96
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
What is the best way to create functions for a program? Give example
Top down approach, break it down into parts
ex. Program to calculate interest, break it into 3 functions
1. Get info
2. Do Calculations
3. Display results
What is the result of and how does it work?
def displayInstructions ( ):
print ("Displaying instructions")
displayInstructions ( )
print ("End")
You created a function called displayIntructions. The body of that function has the print function in it which will have the output of: "Displaying instructions"
Then you called on your newly defined function, so this executes the function (ie, its body) and then the last output is: "End"
True or false: once a function is executed one time, it can't be called again, even if you try and call the function multiple times.
False! You can reuse a function as many times as you want/is called
What is the difference between a local variable and global variable?
Local variables are stored within function bodies.
Global variables are generally defined at the beginning of the code and can be accessed anytime
Why have local variables?
Since variables are memory locations, they take up a portion of memory of the program. So by creating local variables, the memory is used up temporarily, and then once the function is executed, that memory frees up.
When a constant or a variable is in scope, we really mean...Give example
It is somewhere that it can be used. Ex. a local variable is in scope of the function it is under
What is parameter passing? What's often forgotten (2)?
Passing local variables from one function to another.
The number of parameters passed into a function, must equal the number of parameters/variables that are called on. It also needs to match exactly what is called on in the start function.
Is this correct:
def start ( ):
print (num)
No, no parameter 'num' passed into start, so it can't access that memory location called 'num'.
To fix it, must have:
def start (num):
print (num)
What does the return function do? What is often forgotten?
Give example
It communicates a copy of information out of a function (back to caller) as function ends.
THE RETURN VALUE MUST BE STORED IN THE START FUNCTION
def square (num):
result = num * num
return (result)
def start ( ):
aStr = input ("Enter a number: ")
num = int(aStr)
result = square (num)
print (result)
Difference between parameter passing and return values?
Parameter passing passes info INTO function before it executes (passes memory location of variable into function)
Return values communicate info OUT of a function as the function ends
What are some good style of functions that should be implemented?
1. Function should have a well defined task
2. Have a self-descriptive name
3. No longer than 1 screen
4. Use variable naming conventions (lower case, camel-case, or underscore)
Why should you not use global variables? Give an example
Can accidentally be changed anywhere - since they can be accessed from anywhere, makes code harder to trace
num = 1
def fun ( ):
global num #calls in global num
num = 2 #changes global num from 1 to 2
print (num)
def start ( ):
print (num) #1
fun ( )
print (num) #2, global variable changed after fun ( )
start ( )
What are some common mistakes when calling in functions (4)?
1. Not defining the function before it is called
2. Forgetting the ( ) during that start function
3. Not indenting body of function properly
4. Creating empty functions (a function must have a least 1 body instruction)
Pros and cons of defining functions
Pros:
- solution easier to visualize
- easier to test 1 feature at a time
- easier to maintain
- smaller program size
Cons:
- more complex
- tracing may seem harder as a lot of 'jumping around'
What does immutable mean?
No 'mutations'/changes allowed
Name the 3 types of simple variables
Integer, boolean, float
Name the 3 types of composite/aggregate variables
Lists, tuples, strings
In a programming language, a list is implemented as an ...
array
How would you access a whole list vs just one element in that list? What is another name of accessing one element of the list?
aList = [1,2,3]
print (aList) # whole
print (aList[i]) #1 element
INDEXING
Create a list with a fixed size and the same data for each element.
aList = [" ! "] *3
3 elements of ! in list
output: ['!', '!', '!']
For lists, your index should be _____ and ranging from ____
1. positive integer
2. 0 to (list size -1)
What are the 2 steps needed to create a list?
1. Create variable that refers to a list
ex aList = [ ]
2. Initialize list with elements
ex. aList.append (3)
Declaring a list will result in ___ memory locations...Name them
2
one location for list itself (ie., a building)
another location contains address of list (ie., address of building)
True or false:
You can't pass a list as a parameter
False!
You can, you are passing a reference to a list and it can be modified/appended
True or false:
You must return a list variable in the start function.
Give an example and what is another name for this
False.
Since the address of the list is created in the start function is actually modified, you do not need to return it.
ex.
def start ( ) :
classGrades = initialize()
#classGrades is list reference address, it was passed from initialize function's return value
Pass by reference
True or false:
You should NOT assign a new value to the reference of a list when passing reference.
True.
If you make changes to a list/reference to a list, are those change permanent? Explain and give an example
No, if you make changes to the parameters in a function, they are only made locally. To pass these modified lists, you must return the variable name with which the reference to the list is assigned to.
Ex.
def createList ():
aList = [3,2,1]
return (aList) #passing aList to other functions after this function ends
def Function (aList):
aList[0] = 888
return (aList) #returning modified list to start function
def start ():
aList = createList ()
print (aList)
aList = Function (aList)
print (aList)
start ()
output:
[3, 2, 1]
[888, 2, 1]
How can you avoid overflowing a list? Give an example
Use a constant! It controls how many times you traverse/step through the list
ex. SIZE = 10
...
for i in range (0,SIZE,1)
What is a Python specific way to avoid overflow? Example?
Use len () which is the length function built into python
ex.
for i in range (0, len(aList) ,1)
True or false:
2D list is a list containing rows of 1D lists.
True
Given:
table = [ [0,0,0],
[1,1,1],
[2,2,2],
[3,3,3] ]
How would you get it to display this list as an actual table?
How about 1 row at a time?
Table:
for r in range (0,4,1)
for c in range (0,3,1)
print (table [r] [c], end="")
# r/c stop 1 over the actual number or r/c because the it stops ONE BEFORE!!!!
1 row at a time:
for r in range (0,4,1)
print (table [r])
Given:
table = [ [0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3] ]
What will be the output of the following?
1. print(table)
2. print(table[0])
3. print(table[3][1])
4. print(table[0][0][0])
1. entire list
[ [0, 0, 0],
[1, 1, 1], [2, 2, 2], [3, 3, 3] ]
2. first row
[0,0,0]
3. 4th row, 2nd column
3
4. error
What's happening here:
MAX_COLUMNS = 5
MAX_ROWS = 3
ELEMENT = "*"
aList = []
r=0
while (r < MAX_ROWS):
tempList = [ELEMENT] * MAX_COLUMNS
aList.append(tempList)
r=r+1
print (aList)
2D list is created by creating a 1D list and appending this 1D list to the end of the 2D list
1
12
123
[['', '', '', '', '*']]
[['', '', '', '', ''], ['', '', '', '', '']]
[['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '*']]
What are shallow copies? Give an example.
A copy of what is stored in the variable name reference (location of a list)
list1 = [1,2,3]
list2 = list1
they are both referencing the location of the list
What are deep copies? Give an example
Copies info from one list to another
list1 = [1,2,3]
list2 = [0]*3
list2[0] = list1[0]
print (list1)
print (list2)
output:
[1,2,3]
[1,0,0]
How can you boundary check a 2D list? (6)
1. for r in range (0,SIZE,1):
2. if, elif, else statements..
if (50 <= randomNum <= 80)
3. create a true/false condition
outOfBounds = True
while (outOfBounds == True):
4. add in empty row
world.append(tempRow)
5. create a function
def isOut (row,col):
outside = False
if....
6. create while loops
What are the 3 steps to dynamically create a list?
1. create variable that refers to empty list
grid = [ ]
2. successively create rows
for r in range (0,SIZE,1):
grid.append ([ ]) #need this so can add elements to end in step 3
3. EACH ROW IS A 1D LIST, add elements to the end of each row from 1D list
for c in range (o,SIZE,1):
grid [r].append("*")
# the [r] specifies which row the loop will add elements to on the end
Given:
table = [ [0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3] ]
What is the output of the following:
1. table.append ([2,7,1])
print (table)
2. table[3].append (3)
print (table)
3. table[2][1].append(888)
print (table)
1. adds [2,7,1] to end of table list
2. adds and extra element '3' in row 3
[3,3,3,3]
3. error! can't append to an integer...can only add onto end of list in this case
Strings are just a series of ____
Characters
True or false:
Composites types can be treated as only one entity.
Give an example
False!
Composites can also be treated as individual parts
print(aString) prints whole string
print(aString[1]) prints the 2nd character of that string
What are:
- mutable types
- constants
- immutable types
Mutable: memory location CAN change
Constants: shouldn't change
Immutable: original memory location WON'T change
True or false:
Lists are immutable. Give an example
False. Lists can be changed
ex.
aList = [1,2,3]
aList[0] = 10
print(aList) # [10,2,3]
True or false:
Strings are immutable. Give an example.
True. Strings CANNOT be edited.
ex.
s1 = "bye"
print (s1) # bye
s1[0] = "G" #ERROR, can't modify characters in a string
What are the two substring operations?
1. Slicing will return a portion of the string based on the indices given
2. Splitting divides a string into portions
Given
aString = "abcdefghij"
What will be the output of:
1. temp = aString[2:5]
2. temp = aString[:5]
3. temp = aString[7:]
1. Start at 2 go to up to but not including 5
cde
2. Start at 0 and go up to but not including 5
abcde
2. Start at character 7 and go to end
hij
Given:
aString = "James,Tam"
What will be the output of:
first,last = aString.split(",")
James
What are some examples of string testing functions? What do they do?
They see if a given BE has been met (True or False)
isalpha ( )
isdigit ( )
isalnum ( )
islower ( )
isupper ( )
isspace ( )
What are some examples of functions that return modified copies of strings?
lower ( ) #returns copy of string with only lower case
upper ( ) #returns copy of string with only upper case
lstrip ( ) #leading whit spaces removed
rstrip ( ) #trailing white spaces removed
strip ( ) #removed all leading/trailing whitespaces removed
lstrip(char) #leading instances of character in parameter removed
rstrip(char) #trailing instances of character in parameter removed
What will the outputs be of the following:
1. aString = "talk1! abouT"
aString = aString.upper()
2. aString = "xxhexllo"
aString = aString.lstrip("x")
3. aString = "thxerex"
aString = aString.rstrip("x")
1. TALK1! ABOUT
2. hexllo
3. thxere
What are tuples?
Like lists, but immutable.
Tuple is a composite type, and elements can be any other type
What will the output be?
tup = (1,2,"foo",0.3)
print (tup)
print (tup[2])
tup[2]="bar"
1. (1,2,'foo',0.3)
2. foo
3. error because can't change immutable
True or false:
Functions in python can only return 0 or 1 items.
True
if had:
return (1,2,3), it's just returning ONE tuple with 3 elements
How can you 'unpack' a tuple with multiple elements? Given an example
def fun ( ):
return (2,10) #2 elements in tuple
num1,num2 = fun ( ) #2 memory locations for 2 elements of tuple
What are the 5 modes when opening a file in python? Give an example
r - open for reading
w - open for writing
c - open file for reading or writing, if no file then create one
n - create new file for reading or writing, if file exits the overwrite it
a - open file for appending, create one if it doesn't exist
ex. file = input("Enter file name:")
inputfile = open(file, "r")
True or false:
Reading a file is done within the body of a loop, each execution of the loop will read a character from the file into a BE.
False.
Yes, reading is done within the body of a loop, but each iteration of the loop will read a LINE from the file into a string
True or false:
The loop continues to read liens from the file even if there are no more line with characters.
False, it terminates as soon as end of information from file is reached
When writing a file you need __ and __. And the second one will only take a __
An input file
Output file
String parameter
ex. outputFile.write(temp)
What are the 4 error handling exceptions for files?
while (inputFileOk == True):
*Try:
body of file reading/opening
*Except IOError:
react to error
Else:
do this is no error occurs
Finally:
always do this
To create a dynamic list when reading information in from a file, use ___
Append
Who, what and when are the first microprocessor?
Intel
4004
1970
What is a microcomputer? What is it sometimes called?
A computer that uses a microprocessor.
PC (Personal Computer)
What was the fist computer for home users called?
Altair
What two companies did IBM approach as possible vendors of an OS to run it's computers?
Digital Research and Microsoft
What was the difference between Digital Research's CP/M operating system and PC/MS-DOS (Microsoft disk operataing system)
CP/M would reboot if the wrong floppy disk was in and all your work would be lost
PC/MS-DOS would ask if you wanted to save, reboot or retry if the wrong disk was in, so you could swap disks and retry
When did IMB release their first PC? What were some softwares that developers wrote for it?
1981, ran on Microsoft OS
Word processing
Accounting software
Games
Spreadsheets
True or false:
Apple entered the microcomputer market later than IBM, and thus IBM took over sales
False
Apple got into the market first, but because there were so many software developed for IBM's PC, it dominated
True or false:
IBM-PC was made with in-house parts.
False. Parts were off the shelf, so people could customize/build their own PC
What was compaq?
A new PC company opened by 3 ex-Texas Instruments employees. Ran on MS-DOS....after this more opened.
What happened when Dell and other companies joined the market?
IBM lost control
True or false:
Microsoft won the clone wars
Why?
They had MAC GUI (graphical user interface)
When did the Apple I Computer come out?
1976
What was special about the Apple II Computer released in 1977 (2)?
Had colour graphics that were superior to more posh computers. And had VisiCalc
Who invented the first graphical interface?
Xerox Star pioneered the Graphical Use Interface in 1981
A tour of the Xerox PARC inspired Apple to make?
Apple Lisa 1983, which had GUI
What was Laika and who sent her to space?
A dog and USSR
What did the USA do in response to Russia launching Sputnik (2)?
Changed school requirements
What did ARPA (Advanced Research Projects Agency) do?
To get different computers to communicate, but communication between different interfaces was lacking
What was ARPANET?
The first computers were connected via ARPANET, started with two host computers at UCLA and Stanford
What other two host computers were added to ARPANET in 1969?
University of California and University of Utah
What were the 4 milestones of the internet?
1972
Email intoduced by Ray Tomlinson
1989
Ideas of WWW appear in a paper
1990
ARPANET shut down, Archie (internet search program) developed at McGill and first web browser written
1991
WWW release to public
***First was internet and the WWW
What are the WWW milestones (3)?
1989
Tim Berners-Lee and others wanted to make it easier to share research, documents linked via http (hyper text transfer protocol), documents available for reading and downloading
1990
WWW renamed Nexus
1993
Mark Andreeseen of NCSA lauched Mosaic X (Firefox)
True or false
Before the WWW, the internet was largely used by a niche group
True
After WWW, internet usage soared
Who invented the mouse when and why?
Douglas Engelbart 1962
To create a better way for humans and computers to communicate
Name some areas of computer science
Human-Computer Interaction (HCI)
Graphics
AI
Vision
Software Engineering
Security
Games
True or false:
Software should be written to make it as easy as possible for the user to complete their task
True
What is user-centered design? Benefits?
Getting users involved and getting feedback from the beginning of the program writing process.
Cost reduction, because can make changes as you go
Computer graphics are mainly concerned with ___
manipulating and producing images...making things look 'real'
What are the 4 areas of computer graphics?
Animations (motion)
Modeling (structures)
Rendering (textures/details)
Image Processing (modifying images)
What are some areas of AI?
Expert systems (getting knowledge stored in database) and neural networks (building structures that work like neurons, ie., pattern recognition)
What is the Turing Test?
a test for intelligence in a computer, requiring that a human being should be unable to distinguish the machine from another human being by using the replies to questions put to both.
Interpreting and understanding visual information, such as FaceID, is what?
Computer vision
The main concerns of software engineers are:
Producing on time and on budget
What are the difference between the waterfall development process and Agile Software Development?
Waterfall (one-way):
1. gather requirements
2. design system
3. implement and test system
4. verify with user
5. maintain system
Traditional approach, works well for larger orjects
Agile:
- broken into parts
- all 5 of the above stages are worked on for weeks
- show shareholders
- easier to go back and change things
- smaller projects
A design pattern is __
a way of creating software that has proven to work well under a number of different contexts
(past programs that worked!)
True or false:
Many security breaches are due to machine failure.
False
Humans because of social engineering
Cryptography is __
transmitting and sorting sensitive information
What areas of computer science apply to game programming?
All
HCI
Graphics
AI
Vision
Software engineering
Security