Programming Fundamentals


YouTube - Geeks Lesson(Python)
Cairo Graphics Library


Final Practice Quiz - September 3rd
What is the output of print("3"+4)TypeError
Consider the following function:
def celebrate(event):
print("Happy",event)
celebrate("Christmas")
in this code, event is an example of:
function name
program
parameter
What is the 2nd number printed by this program, assuming that the user enters 3 as the input?
def evaluate();
x = eval(input("Enterr a number between 1 and 5:"))
for i in range(3):
x = 5 * x * (2 + x + x)
print(x)
evaluate()
145200
Consider the following statement:
for val in range(10):
Here, what does the variable val refers to?
inversion variable
interactive variable
iterative variable
Suppose a program executes the following statement.value = eval(input("Enter a numbet: ")) In response to the prompt the user types '1'+'2'+'x'+'y' What does value contains?Xy
TypeError12
12xy
Suppose a program executes the following statement. value = eval(input("Enter a number: ")) In response to the prompt, the user R what is the result?82
r
String
error
How soes the following statement assigns the value?
varN,varS = 7, 9
incorrect syntax
varN=9 varS=7
varN=7 varS=9
What wwill this statement do?
for i in range(7):
Invalad Statement
it multiplies i times 7
it looks for the value of i in the number 7
it causes the program to do something 7 times
Evaluate:
int(float(10))
10.0
10.1
10
Evaluate:
round(10.09)
9
11
10
Evaluate:
list(range(1,10,2.0))
[3,5,7,9]
[1,3,5,7,9]
[1.0,3.0,5.0,7.0,9.0]
Error
Consider the following program:
def main():
    number = eval(input("enter a number: "))
    for n in range(4):
        number = number // 4
    print(number)
main()
5
1
0
Suppose that the variable x has the value 5 and y has the value 10.
After execusing thiss statement:
x,y = y,x
What will the values of x and y be, respectively?
5 & 10
10 & 10
5 & 5
10 & 5
Evaluate:
list(range(11))
[0,1,2,3,4,5,6,7,8,9,10,11]
[1,2,3,4,5,6,7,8,9,10,11]
[1,2,3,4,5,6,7,8,9,10]
[0,1,2,3,4,5,6,7,8,9,10]
What is the output of this program?
def main():
    j = 45
    k = 54
    for i in range(2):
        j,k = k,j
    print(j,',',k)
main()
54,45
45,45
54,54
45,54
Which of the following statement would set the coordinates of win from (0,0) in the lower-left corner to (8,8) in the upper-right corner?win.setcoords(Point(0,0), Point(8,8))
win.setcoords((0,0)(8,8))
win.setcoords(Point(8,8), Point(0,0))
win.setcoords(0,0,8,8)
What is the result of
import math
round(math.pi,2)
3.1
6.28
3.14
What is the output from the following program, assuming that the user enters the input value 5
def add():
    limit = eval(input("Enter a number: "))
    answer = 0
    for value in range(1,limit):
        answer = answer + value
    print(answer)
add()
0
720
120
none of these
Evaluate: 13//34.5
1
4
What is the output from the following code fragment
number=1
for num in range(4):
    number = number * num
print(number)
256
1
64
0
What is printed by the following Python fragement?
str3 = "Rr"
str5 = "Ss"
print(str3 * 4 + str5)
Rr2Ss
Rr Rr Rr Rr Ss
RrRrRrRrSs
What is the result of this code?

One = "Number One"
print(One[-2])
u
e
n
What is the result of evaluating this expression?
"{0}.{1:02}".format(22,2)
22.20
22.22
22.02
Which of the following is the same as s[0:-1]s[0:len(s)]
s[:]
s[-1]
s[:len(s)-1]
The code myFile = openb("data.txt".'w") returns error if the file 'data.txt' is not foundfalse
What expression would create a line from (4,5) to (2,3)Line((4,5),(2,3)),
Line(4,5,2,3)
Line(2,4,3,5)
Line(Point(4,5),Point(2,3))
Which of the following statements could be used to get the poistion of mouse click from a user?p = input("Click the mouse")
p = mouise.get(win)
p = getMouse()
p = win.getMouse()
Which of the following method is usd to draw pixel at the raw position (x,y) ignoring any coordinate transformations set up by setCoords?win.draw(Pixel(x,y))
Pixel(x,y)
Plot(x, y, color))
plotPixel(x, y, color)
Which statement correctly draws a circle of a radius 5 centered at (10,10) in the graphics window win?draw(win).Circle(Point(10,10),5)
Circle(win, Point(10,10),5)
win.dra(Circle(Point(10,10),5))
Circle(Point(10,10),5)
Suppose you want to create a square graphics window & draw lines to divide it into 4 equal-sized quadrants. Fill in the missing line in this code:
win=Graphwin("Four Square", size, size)
# Missing line here
Line(Point(0,1),Point(2,1)).draw(win)
Line(Point(1,0),Point(1,2)).draw(win)
win.setcoords(Point(0,0),Point(2,2))
win.setCenter(1,1)
win.setcoords(Point(2,0),Point(0,2))
win.setCoords(0,0,2,2)
Formal and actual parameters are matched up by:name
id
position
What is the output from the follwoing code?
def cube(n):
    for i in range (len(n)):
        n[i] = n[i] * n[i] * n[i]

nn=[4,5,6]
cube(nn)
print(nn)
nn
[4,5,6]
[64,125,216]
What does this code results?
for char in "clicked flicked kicked".split("k"):
    print(char,end="")
clic ed flic ed ic ed
clicedflicediced
cliced fliced iced
How to open a file called "MyAnalysis.spss" to read its conteents memory?"data = MyAnalysis.read()
infile = open("myAnalysis.dat","w")
open = infile("MyAnalysis.dat","r")
infile = open("MyAnalysis.spss","r")
Evaluate: "{0}.{1:03}".format(13.10)13.001
13.10
13.100
13.010
The following are examples of ways to output data in the month/day/year format.str(month)+"/"str(day)+"/"str(year)
"{0}/{1}/{2}".format(str(month),str(day)str(year))

"{0}/{1}/{2}".format(month.day.year)
The following program fragment is to find the sum of the Unicode values for the characters in a string. What is teh missing line in this program?
def uAdd():
    word = input("Enter a word: ")
    Uadd = 0
    for i in word
        #missing line here
    print(Uadd)

uAdd()
Enter a word: Xmas
409
Uadd = Uadd + 1
Uadd = Uadd + i(ord)
Uadd = ord(i)
Uadd = Uadd + ord(i)
Identify the missing line of this code fragment:
def Acronym():
    phrase = input("Enter a phrase:")
    acr = ""
    for ch in phrase.split():
        print(acr)


Acronym()
Enter a phrase:Hyper text markup language
HTML
print(ch[0].upper())
acr = ch[0]
acr = ch[0].upper()
acr = acr + ch[0].upper()
Find the output of:
for o in "GOOD MORNING GOD".split("0"):
    print(o, end=" ")
G O O D MO RNING GO D
GDMRNINGGGD
O O O
G D M RNING G D
What is the output from the following program, if the input is "Spam And Eggs" (Typed without the quotes)?
def main():
    msg=input("enter a phrase: ")
    for W in msg.split():
        print(W[0],end="")
main()
SSS
SEA
ASE
Pridict the output:
m = 98
n = 74
m ! = m
True
Predict the output of boolean expression:
"hello"<"Hello"
False
Predict the output:
def m():
    txt = 'yes'
    if txt == 'yes':
        print ("X")
    elif answer != "yes":
        print("Y")

m()
Y, yes, X
Predict the output:
for i in [12, 16, 17, 24, 29]:
    if i % 2 == 1:
    
    break
    print(i)
print("done")
12
16
done


Programming / Python Notes




Python Chapter 4
Objects & Graphics
To understand the concept of object and how they can be used to simplify programming.
to be familiar with the various objects avaiable in the graphics library.
to be able to create ojbects in p[rograms and call appripiate methods to perform graphical computations.
Traditional view of computation.
-Data are the passive entities that were manipulated and combined via active operations.
More comple systems.
-Need richer view of relationship between data and operations.
Modern Computer Programs.
-Built using object oriented approach.
-Object Oriented approach emcompasses a number of principles for designing and implementing software and principles.
Graphical programming - lot of fun, great vehicle for learnign about objects.
Graphical User interface GUI
-Interactive graphics Programming.
-Most familiar applications today have GUIs tha tprogides interactive visual elements like windows, icons(Represeentatative piectures, buttons and menus.
GUI in Python.
Great language for developing real world GUI's
Used as embedded language in various desktop apps and software like Maya, Blender and several games.
Python comes with its own standard GUI module called Tkinter.
The Object of Objects.
Basic idea of OO development is to view a complex system as the interaction of simpler objects.
OO programming - figure out the vocabulary.
Objects know the stuff (they contain data) and can do stuff (they have operations)
Objects interact by sending messages to each other.
Messages - request for an object to perform an operation.
Python Graphics Library.
System archatech. layout and flowcharts/ logic planning
Developers.
project leaders.
product owner.(acts like client. Lieason)
Scrum Master
Use Agile Development.
Literal and strings
Literal numbers 9,32, etc
Strings "hello"
standard mathematical order of operations NOT sequential
how to change case
any="batman"
any.upper()
'BATMAN'
BaTmAn.lower()
'batman'
string count (includes spaces)
print(len("wow!! Batman!"))
13
-or-
abc="wow!! Batman!"
print(len(abc))
13
output statements
print function
special marker character \n -or- end="\n"
print lie joining end=""
the Pythonhas automatic memory management mechanism called 'GARBAGE COLLECTOR'
in python the user does not hae to pre-allocate or de-allocate memory.
ans
x=input ("XXXXX") -vs- x=eval(input("XXXXX"))
first will record the string value
second will record mathematical value
simultaneous assignment statements
a,b=10,20
print(a)
10
print(b)
20
Swapping the values
store a value in variable x and another value in vairable y
swap the x value to variable y and the y value to variable x
Python notes 2/4/2019
input process output (IPO)
identifiers
s
spam
spam2
spamandeggs
Spam_and_Eggs
uppercase and space sensitive
keywords "reserved words" this is the complete list of Python Keywords.
False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise
Boolean operators have uppercase first letters "False True None"
Literal and Strings
Single or double quote are the same "" ''
Operators
Addition +
Subtraction -
Multiplication *
Division /
Exponentation **
simultanious vairable entry
x,y=5,6
x,y=eval(input("Enter "))
Python - 2/4/2019
Understanding the Program Development cycle
program development cycle
1. understand the problem
Users or end users: people for whom a program is written
Documentation: Supporting paperwork for a program
2. Plan the logic
Heart of the programming process
Most common planning tools: Flowcharts, pseudocode, ipo charts(input process output)
TOE charts(tasks objects & events)
Desk-checking:walking through a program's logic on paper before you actually write the program
3. code the program
Easier then the planning step, hundredes of prgramming languages
choose based on features
similar in their basic capabilities
4. use compiler interperter to trnslate the program into machine language
Translator prgram
compiler or interperter
changes the programmers english like high level proramming language into low machine language
Sytntax Error
misuse of a languages grammer rules
programmer correcrs listed syntax errors
might need to recompile the code several times
5. test the program
logical error
results when a syntacically correct statement but the wrong one for the current context
test:execute the program with some sample data to see weather the results are logically correct
debugging is the process of finding and correcting program errors
programs should be testetd with many sets off data
6. put the program into production
Process depends on programs purpose, may teke several months
conversion - the entire set of actions an orginazation myst take to switch over to a new program or set of programs
7. maintain the program
maintence - making chages aftger the program is put into production
common first programming job - maintaining previously written programs
make changes to existing programs -repeat the development cycle
8. Using pseudocode to statements and flowchart symbols
Pseudo code - english-like representation of the logical steps it takes to solve a program
Flowchart - pictorial representation of the logical steps it takes to solve a program
9. Writing pseudocode
start
input mynumber
set my answer
output myanswer
stop
programmers preface flexible planing tools
Programming/c# chapter2
Data types
Numeric- numbers
String – takes a form of text. Anything not used in math
Different forms
integers and floating point numbers
literal and string constants
unnamed constatns
Variables- named memory location with varying content
Declaration- statement that provides a data type and an identifier for a variable
Indentifier- the variables name
Data type
classification that describes
what values can be held by the item
how the item is stored in computer memory
what operations can be performed on the data item
Initializing the variable: declare a starting value for any variable
Garbage
any variable declared and not initialized any value, contains an unkown value until its assigned an initializing value
variable’s unkown value before initialized is known as garbage
certain programming languages assign 0 to a garbage variable.
Naming variables
Camel casing
variable names with a “hump” in the middle like hourlyWage
Pascal casing
first letter of variable name is uppercase Hourlywage
Hungarian notation
variable’s data type is a part of the identifier numhourlywage
Must be one word.
must start with a letter
should be a meaningful name.
Math/arithmetic uses the order of operations.
Modularization
the process of breaking down a large program into modules
Modularization allows multiple programmers to work on a program
and reuse work a lot easier.
Abstraction
paying attention to important properties while ignoring non essential details
selective ignorance
Newer high level programming languages use English-like vocabulary.
Reusability
most modular programs are reusable.
using different modules in different programs. Passwords/databases, card payments. Etc
Reliability- making sure a programs tested and works.