0% found this document useful (0 votes)
10 views20 pages

Practice 1

The document is an exam for CSCI-UA.0003 with instructions for completing the test, including filling in personal information and answering questions in two sections. Section 1 consists of Python coding questions requiring modifications and outputs, while Section 2 involves writing programs based on provided scenarios.

Uploaded by

k2n2pvtltd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views20 pages

Practice 1

The document is an exam for CSCI-UA.0003 with instructions for completing the test, including filling in personal information and answering questions in two sections. Section 1 consists of Python coding questions requiring modifications and outputs, while Section 2 involves writing programs based on provided scenarios.

Uploaded by

k2n2pvtltd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Final for CSCI-UA.

0003

Name:
Net ID

Instructions:

• Fill in your name and Net ID (ABC1234) on this page and every page of your test. Do NOT use your N number
(N12345678).

• Answer all questions in Section 1

• Answer 2 out of 3 questions in Section 2. Please do NOT remove or reorder any pages from the exam. Removing
pages may prevent Gradescope from working properly. Please complete the test in the time allotted. Extra time can be
provided through the Moses Center if you qualify.

Contents of This Document.

• Section 1 has questions with boxes to fill in your answers. Extra boxes/extra space is provided to allow room for
cross-outs and corrections. Please do not remove any pages from the test and please do not add any pages. Extra scrap
paper is available if you need it. For the purpose of these questions, assume that each question is in a different file,
e.g., each definition and execution of the function main is independent of every other execution of main.

• Section 2 asks you to write simple programs. There are three questions, but we will only grade two of these questions.
Therefore you should only complete two of these questions (or cross out one question’s answer). If your choice of
questions is unclear, we will grade the first 2 questions in section 2 and ignore the third one.
Please write the answers to these questions immediately after the question. Extra pages are provided after each ques-
tion, in case you need more room to write the answers. Please include notes to indicate where your answers are if
they don’t immediately follow the question or are split into multiple piece. For example, if you use the page after
question 7 to finish answering question 5, you should put a note after your partial answer to question 5: Continued
after question 7. Right above the additional code, you should include a note Question 5 continued.

• A GLOSSARY OF TERMS – Please feel free to look up some of the basics in this glossary. I will also answer any
reasonable look-up style questions as I am more interested in your ability to reason than your ability to memorize.

Section 1 (50 points)


Each example consists of Python code, followed by questions and places to fill in answers. Please read all questions carefully
and answer them as precisely as possible. Assume that there are no bugs in the code that will make the system crash, although
the code may not solve a problem perfectly. If you find anything that you think is a bug, there is either a typo (and I should
fix it for everyone) or you are mistaken.
Sample Question A:

output = ’1’+’1’

Question: What is the value of the variable output?

Answer: ’11’ Answer:

Note: Attention to detail is important. The quotes indicate that it is a string. Partial credit is possible. For example, leaving
out the quotes would have resulted in a small deduction, but answering 2, would have resulted in an incorrect answer.
Question 1. Modify the initial code so that instead of producing Output1, it produces Output2. Observe that Output2 consists
of 2 instances of a version of the word spam. In each version all, the letters of spam each occur two times.
Initial Code

def string_double(word):
return(word+word)
print(string_double(’spam’)

Output 1

>>> question_1()
spamspam
>>>

Output2

>>> question_1()
ssppaammssppaamm
>>>

Answer: Answer:
Question 2 Modify the code below, so that running it will result in the output2 instead of output1. Specifically, the pairwise
product should be the same length as the input lists. Each position should be the product of the corresponding positions in
the 2 input lists, e.g., if the first position of one list is 1 and the first position of the other is 0, then the first position in the
output list should be 0 since 1 × 0 = 1. Note that the second example in Output1 should be assumed to be all on one line.
It was adjusted so it would print OK on the test.

Initial Code

def pair_wise_product(list1,list2):
if len(list1) != len(list2):
print(’Lists incompatible: Try again’)
return(False)
combined_list = []
for item1 in list1:
for item2 in list2:
product = item1*item2
combined_list.append(product)
return(combined_list)

def question_2():
print(’First:’,pair_wise_product([1,0,1,1],[1,1,0,1]))
print(’Second:’,pair_wise_product([1,0,1,1,0,1,1,1],[1,0,0,0,1,1,0,1]))

Output1 (initial output):

>>> question_2()
First: [1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1]
Second: [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1,
0, 1, 1, 0, 0, 0, 1, 1, 0, 1]
>>>

Output2 (output from modified code)

>>> question_2()
First: [1, 0, 0, 1]
Second: [1, 0, 0, 0, 0, 1, 0, 1]
>>>

Answer: Answer:
Question 3

def checking_ducks_in_a_row(input_list):
output = []
plural = False
for item in input_list:
item = item.lower()
bird_type = ’other’
if item[-1] == ’s’:
plural = True
check_item = item[:-1]
elif item == ’geese’:
plural = True
check_item = ’goose’
else:
plural = False
check_item = item
if check_item in [’duck’,’drake’,’duckling’,’mallard’,’widgeon’]:
bird_type = ’duck’
elif check_item in [’goose’,’gander’,’gosling’,’greylag’,’brant’,’honker’]:
bird_type = ’goose’
else:
print(item+’ is not a type of duck or goose! Revise and start again.’)
bird_type = ’inappropriate_bird_type’
record = [item,bird_type]
if plural:
record.append(’multiple’)
else:
record.append(’single’)
output.append(record)
return(output)

test_1 = [’duck’,’mallards’,’geese’,’widgeon’,’honkers’]
test_2 = [’ducklings’,’mallard’,’pigeon’]
output1 = checking_ducks_in_a_row(test_1)
output2 = checking_ducks_in_a_row(test_2)

Question 3a: What is the values of output1 after the above code executes?

Answer: Answer:

Question 3b: What is the values of output2 after the above code executes?

Answer: Answer:

Question 3c: What if anything prints out during the execution of the code above?

Answer: Answer:
Question 4 Modify the initial code below so that executing the code will result in the desired output listed below. The code
is trying to find the “comparative form” of adjectives. This entails either adding “er” to the end of the word or adding the
word “more” before the adjective. We will assume that the following sorts of words require “more”:

• words containing hyphens, e.g., double-jointed

• words listed in the list bound by the variable needs more

Other adjectives should have ”er” added to the end of the word. However, there should be other adjustments as well,
depending on the last 3 letters of the word. Factors include whether or not the last letter is a ”y”, whether the last letter is in
the string bound to the variable ”doubling constant”, and/or whether some of the last three letters are vowels or consonants.
Initial Code:

needs_more = [’ably’, ’aged’, ’ajar’, ’akin’, ’apt’, ’arid’, ’bent’, ’chic’,


’curt’, ’deft’, ’eery’, ’evil’, ’flip’, ’glum’, ’just’, \
’like’, ’loth’, ’nuts’, ’real’, ’used’]

doubling_consonants = ’bdgmnprt’

def add_er(word):
return(word+’er’)

def question_4():
for word in [’ajar’,’bald’,’dim’,’avid’,’sour’,’grey’,’hot-tempered’,’crusty’]:
print(word,’-->’,add_er(word))

Desired Output:

>>> question_4()
ajar --> more ajar
bald --> balder
dim --> dimmer
avid --> avidder
sour --> sourer
grey --> greyer
hot-tempered --> more hot-tempered
crusty --> crustier
>>>
Instructions for Section 2: Answer 2 out of the 3 questions in Section 2. Each question specifies a Python program for you
to write. If you complete or partially complete all three questions, please cross out the answer that you do not want to be
counted. We will only grade 2 questions. If you do complete all the questions and do not cross out any answers, we will
grade questions 5 and 6 (the first 2 questions (5 and 6) of Section 2 and ignore question 7.

Question 5: Write a program for “fairly” dividing up an inventory of items to a group of users (e.g., in a game). The file
“items and values.tsv” is a tab separated values file containing the content below. Assume the first column contains items
and the second column contains the corresponding value of the item (e.g., dollars). Let the variable inlist represent a list
of characters, each of whom will get a (fair) share of these items. Of course your program should work for any file like
“items and values.tsv” or any list of names like inlist – you should not hard-code these variables. Rather these should be
parameters of functions written to solve this and similar problems.
Contents of “items and values.tsv”

apple 1
apple 1
orange 1
rock 0.5
rock 0.5
bandage 2
soup 1
ointment 5
ointment 5
gold 10
skis 10
skis 10
pencil 1
automobile 10
umbrella 6
inlist lists the characters who will be given the items above.

inlist = [’Mary’,’John’,’Sally’,’Bugs’,’Wallace’]

Write a program that gives away all the items in “items and values.tsv” to the characters in inlist. The program should
give away the items, one at a time. After each item transfer, the recipient’s inventory value should be updated to reflect the
value of the new item. For example, if Mary’s inventory value was 6, the value would be updated to 7 after receiving a
pencil. Before each item transfer, a recipient should be chosen who has the lowest inventory value. For example, suppose
that ’Mary’ has an inventory value of 5; ’John’ and ’Sally’ each have inventory values of 6; and ’Bugs’ and ’Wallace’ each
of inventory values of 3. Then the next item should be given to either ’Bugs’ or ’Wallace’ since they are tied for having the
lowest inventory value.
. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .
. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .
Question 6: Write a program using the turtle package. Your program should convert a sentence to Morse code and write out
the morse code using turtle graphics. Assume that your program begins with the following code.

morse_code = {}

def start_turtles():
import turtle
global my_screen
global my_turtle
my_screen = turtle.Screen()
my_turtle = turtle.Turtle()
def initialize_code():
for letter,code in [[’A’,’.-’],[’B’,’-...’],[’C’,’-.-.’],[’D’,’-..’],[’E’,’.’],\
[’F’,’..-.’],[’G’,’--.’],[’H’,’....’],[’I’,’..’],[’J’,’.---’],\
[’K’,’-.-.’],[’L’,’.-..’],[’M’,’--’],[’N’,’-.’],[’O’,’---’],\
[’P’,’.--.’],[’Q’,’--.-’],[’R’,’.-.’],[’S’,’...’],[’T’,’-’],\
[’U’,’..-’],[’V’,’..-’],[’W’,’.--’],[’X’,’-..-’],[’Y’,’-.--’],\
[’Z’,’--..’],[’.’,’.-.-.-’]]:
morse_code[letter]=code

start_turtles()
initialize_code()

The user types in a sentence and your program should convert it to Morse code as follows. Your program should convert the
sentence to upper case and then use the dictionary above to convert it to Morse code as follows:

• Ignore characters not represented by the Morse code.

• Each “.” (dot) in a dictionary entry should be interpreted as a 5 pixel long horizontal line, drawn by the turtle.

• Each ’-’ (dash) should be interpreted as a 10 pixel long line.

• Each dot or dash should have 10 pixels of blank space between them.

• Characters should have 20 pixels of blank space between them.

• Words should have 40 pixels of blank space between them.

• Before starting to write a sentence, the turtle should move to position -400,300.

• If at the end of a word, a turtle is in a position X,Y, such that X is more than 100, it should move to the next line
before beginning a new word. Each new line’s starting X position is -400 and its starting Y position is 20 less than the
previous Y position. Thus the second line will start at -400,280; the third line will start at -400, 260, and so on.

Figure 1: Sample Morse Code Output for Some people say not to worry
. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .
. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .
Question 7: Implement a computer game loosely based on the cockroach race gambling game that is a yearly charity event at
the Story Bridge Hotel in Brisbane, Queensland, Australia (http://www.cockroachraces.com.au/the-event/
race-rules/).

Money, Winning and Losing Conditions: In this game, the player starts out with $1000 cash. Each round, they can bet
any amount of money up to the total amount of their current cash. The game ends, either when they decide to stop betting
or they run out of money. Winning and losing comes in degrees based on the final amount of cash they have when the stop
playing according to the following table.

Final Amount of Cash Game Status


Less than $100 You Lost Big Time
From $100 to $499 You Lost
From $500 to $799 You Lost by a Little Bit
From $800 to $1199 You Basically Broke Even
From $1200 to $1499 You Won by a Little Bit
Above $1499 You Won Big Time

How the race is conducted: There are 10 cockroaches in the race. The race ends when the first roaches crosses the finish
line and wins. Note that more than one roach can tie for first place. The race track is 10 steps long. All roaches start out at
position zero and can win by advancing 10 (or more) steps to the finish line. For each turn, randomly determine each roach’s
next position among the following 4 choices (each equally likely):

1. the roach moves forward 1 step

2. the roach moves forward 2 steps

3. the roach moves forward 3 steps

4. the roach flies – if it flies, it is moved backwards 2 steps because flying is considered cheating by the judges.

How Betting Works: A player bets on one roach at the beginning of each round. If the chosen roach loses, the player loses
the money that they bet. If the chosen roach wins, the player wins an amount of money equal to the original bet, times ten
and divided by the number of winning roaches. For example, if the player bets $100 and 3 roaches tie for first (including
their choice), then they win 10/3 × $100 or $333, rounded to the nearest dollar.
. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .
. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .
Glossary for Python Test
1. Some Basics
• return(X) causes the current function to exit and cause the expression represented by the function call
to evaluate as X. For example given the following steps, the value of output would be 5:
def add(num1,num2):
return(num1+num2)
output = add(2,3)
• print(X) prints X to the screen. This is only for the benefit of the user. It is not useful for having
programs interact. print(a,b,c,d,...) will print all the items input and put a space in between the items
by default, e.g., print(’Hello’,’world’,’it’, ’is’, ’me’) will print:
Hello world it is me
The key word parameter sep is used to separate the items by something other than a space. By default
print ends the print out with a newline, but this default can also be changed with the end key word
parameter. For example, print(’The’,’blue’,’dog’,sep=’*’,end=’:])’ would print:
The*blue*dog:], and no newline would immediately follow (so a following print statement would print
on the same line).
• The parameters of a function are the local variables inside of the parentheses in the function definition.
They are useful when you have functions call functions.
• input(prompt) is used to ask a human being a question so that a program can interact with a human
being. This is useful when you want a human being to enter information interactively. input statements
should be used only when human interaction is appropriate. input statements return a string corre-
sponding to what the user typed in. It may be necessary to convert this string to some other data type,
e.g., an integer (with int) or a float (with float).
• The format method allows you to include variables inside a string and to standardize formatting, par-
ticularly for numeric variables. For example consider the text variable txt5 defined as:
txt5 = ”I like long numbers like :5f”
The string:
txt5.format(5.77777777777777
would evaluate to ’I like long numbers like 5.777778’
because the format statement only allows 6 decimal places, one which is rounded.
• The operator + will add two numbers or concatenate two strings
• The operator * will multiple two numbers or repeat a string some number of times.
• The operator ** will represent exponents, e.g., 5**2 == 25.
• The function globals() returns a list of all the global variable names (strings). It can be useful to see if
a variable has been defined. For example, ’my turtle’ in globals() will return True if ’my turtle’ is
defined globally and False otherwise.
2. Division and Modulus
• 5 // 2 == 2
• 5/2 == 2.5
• 5%2 == 1
3. More Math
• round(4.5) == 4, round(4.6) == 5, round(-4.5) == -4, round(-4.6) == -5
• round(2/3,2) == .67 ## The second argument of round indicates number of decimal places. The default
is to round to the nearest whole number.
• math.floor(4.9) == 4, math.floor(-4.9) == 5
• math.ceil(4.9) == 5, math.ceil(-4.9) == -4
• math.trunc(4.9) == 4, math.trunc(-4.9) == -4
• math.pi == 3.141592653589793 – a variable for the value of pi
4. sequences
• object made up of other objects in an order
• the function len(sequence) returns the number of items in the sequence
• the operator in tests for membership in sequence, e.g., (’a’ in ’abc’) would have the value True.
• sequences are used in for loops (see below)
• indices and slices
– Indices in a sequence are numbers from zero to the length of the sequence. Zero refers to the posi-
tion before the first item in the string and the length of the string refers to the position following the
last item. Thus each item in the sequence are between two consecutive indices. For example, the
subscripted numbers indicate indices for the string The book: ’0 T1 h2 e3 4 b5 o6 o7 k8 ’. Similarly, the
indices in [0 ’The’,1 ’book’,2 is,3 ’there’4 ] indicate positions in the list [’The’, ’book’, ’is’,’here’].
– negative indices can be used to count positions from the end. Thus -1 is equivalent to the posi-
tion at one less than the length of the string; -2 is equivalent to the position at two less than the
length of the string; etc. The the negative positions around The book would be labeled as follows:
’−8 T−7 h−6 e−5 −4 b−3 o−2 o−1 k’.
– sequence[num] indicates an element in a sequence beginning at num (a number from zero to one
less than the length of the string), e.g., ’The book’[4] evaluates to ’b’; [’The’, ’book’, ’is’,’here’][0]
evaluates to ’The’. The negative indices can be similarly applied, e.g., ’The book’[-1] evaluates to
’k’, the last character in the string.
– sequence[num1:num2] indicates a subsequence beginning at position num1 and ending at num2,e.g.,
’The book’[4:6] evaluates to ’bo’; [’The’, ’book’, ’is’,’here’][0:2] evaluates to [’The’, ’book’].
– Leaving out the number before the colon suggests that a subsequence begins at the beginning of
the sequence and leaving out the number after the colon suggests that the subsequence ends at the
end of the list. Thus ’The book’[:3] evaluates as ’The’ and [’The’, ’book’, ’is’,’here’][2:] evaluates
as [’is’,’here’].
• ranges define a sequence of numbers based on the length of a sequence starting from 0. If given 2
arguments, the second argument is the length of a sequence starting from 0 and the first argument is a
starting point within that sequence.
– range(5) is approximately equivalent to [0,1,2,3,4]
– range(1,5) is approximately equivalent to [1,2,3,4]
• Strings
– an empty string has zero characters ”
– strings are sequences of characters, e.g., ’Hello World!’ consists of the items [’H’, ’e’, ’l’,’l’, ’o’, ’
’, ’W’, ’o’, ’r’, ’l’, ’d’, ’!’]
– string1.strip(string2) – removes instances of the characters in string2 from beginning and end of
string. For example, ’***Hello World!***’.strip(’*!’) will return ’Hello World’. It removes both
’*’ and ’!’ from the end of the input string.
– string.split(character) – creates a list by dividing a string at each instances of character. For exam-
ple, ’Hello World’.split(’ ’) will return the list [’Hello’,’World’].
– string.lower() converts string to lower case; string.upper() converts a string to upper case.
– string.index(item) returns the position index item occurs in the list – it is an error if the item is not
in the string. This works with both characters and substrings.
• Lists
– A list is represented by square brackets around a list of objects with commas between them, e.g.,
[’A’,’List’,’of’,’Strings’]
– Lists are mutable. Functions that take lists as arguments, can change those lists. e.g., if the variable
my sentence is set to [’Today’, ’is’, ’the’, ’final’, ’exam’], the function call: my sentence.reverse()
will cause the value of my sentence to change to [’exam’, ’final’, ’the’, ’is’, ’Today’]
– You can add an object to the end of a list using the append method. For example, suppose my list =
[’a’,’b’,’c’]. Then my list.append(’d’) will add ’d’ to the end of my list, setting it to [’a’,’b’,’c’,’d’].
– You can change an item in a list as follows: list[index] = newitem, e.g., if my list is set to [1,2,3],
then the statement my list[1] = 57, will change the value of my list to [1,57,3].
– You can pop an item off the end of a list with the pop method. pop will return the removed item.
For example, if my list is set to [’a’,’b’,’c’,’d’], then my list.pop() will return ’d’ and shorten the
list to [’a’,’b’,’c’].
– You can pop off an item at a particular position if you use pop with an index. For example, suppose
my list = [’a’,’b’,’c’], then next letter = my list.pop(1) would result in next letter being equal to
’b’ and my list being set to [’a’,’c’].
– You can add a list of items to a list via extend. For example, suppose my list = [’a’,’b’,’c’]. Then
my list.extend([’d’,’e’]) will add the items in the 2nd list to the end of the first one, setting it to
[’a’,’b’,’c’,’d’,’e’].
– other list methods: list.reverse() – turns a list backwards; list.sort() – puts a list in sort order; etc.
5. print
• sep – separator between items
• end – printed at the end of print statement
6. dictionaries – are sets of key/value pairs used for representing attributes of the keys. For example, consider
the dictionary phonebook = {’Mary’:’212-333-4444’,’John’:’914-444-3333’}. The keys Mary and John are
linked to the values ’212-333-4444’ and ’914-444-3333’. This dictionary provides a way to look up the
phone numbers of the named people.
• dictionary[key] – returns value associated with key in dictionary
• dictionary[key] = value – sets dictionary entry for key to value
• The in operator can be used with dictionaries to check if a key is found, e.g., (name in phone book)
evaluates to True given a dictionary phonebook and some key name such that phonebook[key] would
have a value.
• len(dictionary) – returns the number of key/value pairs found in the dictionary.
• dictionary.keys() – returns a sequence of keys from the dictionary (this can be coerced into a list using
the list function.
• dictionary.keys(), dictionary.values(), and dictionary.items() – These return sequences of keys, values
and items respectively. Items are key value pairs. These can be converted to lists using the list function
or used as is (e.g., in for loops).
7. for loops
• First Line: for VARIABLE in SEQUENCE:
• VARIABLE is set to each item in the sequence one at a time
• The indented body repeats once for each item in sequence (for each setting of VARIABLE).
• It is common to exit a loop of any kind by using a break. After a break, the statement after the loop
executes.
• It is common to exit a loop of any kind by using a return – this also exits the function.
• It is common to initialize a variable outside a loop (called an accumulator) that then gets incremented
inside the loop.
8. while loops
• First line While (BOOLEAN-EXPRESSION):
• The loop keeps executing the indented body until BOOLEAN-EXPRESSION evaluates as False.
• If BOOLEAN-EXPRESSION is always True, the loop is endless.
• Typically BOOLEAN-EXPRESSION contains one or more variable(s), such that some values of these
variables cause BOOLEAN-EXPRESSION to evaluate as True and other values cause it to evaluate as
False.
• The body of the loop can change these variables. The loop starts when BOOLEAN-EXPRESSION is
True. Then, under most circumstances, BOOLEAN-EXPRESSION eventually evaluates as False and
the loop halts. For example, if the BOOLEAN-EXPRESSION is stop == False, setting stop to True
inside the loop, will cause the loop to finish.
• It is common to use accumulator variables in a similar manner as with for loops.
• break and return behave the same way for while loops as they do with for loops.
9. if statements
• the first line of an if statement consists of if BOOLEAN-EXPRESSION:
• the body of text indented under the first line is executed if the BOOLEAN-EXPRESSION evaluates to
True
• the if statement can be followed by optional elif statements of the same form, except that the first line
begins with elif. Each elif statement is only evaluated if the BOOLEAN expressions in the if and elif
statements leading up to this one are False.
• The block of if and optional elif statements can end with an optional else statement. The first line is
simply else:. The body of text under else executes if the Boolean expressions for all previous if and elif
statements in the sequence evaluate to False.
10. logical operators
• X and Y returns True only if both X and Y are True
• X or Y returns True only if X is True, Y is True or both are True
• X in Sequence returns True if X is in a member of a sequence, e.g., ’a’ in ’abcdefg’ would return True
• X == Y returns True if X and Y are the same
• X != Y returns True if X and Y are different
• X < Y returns True if X is less than Y
• X > Y returns True if X is greater than Y
• X <= Y returns True if X is less than or equal to Y
• X >= Y returns True if X is greater than or equal to
• Not X returns True if X is False
• The operators <, >, <, > can apply to non-numeric objects. Characters are compared based on their
unicode values (so ′ a′ <′ b′ ). True is assumed to be greater than False. Sequences are compared
lexicographically – the first item in pairs of sequences are compared first, but if they are equal the
second items are compared, and so on.
11. Turtles
• Screen and Turtle objects are created using the commands turtle.Screen() and turtle.Turtle().
• The turtle is initially in the center of the screen facing rightward.
• my turtle.left(degrees) – rotates the my turtle degrees left (from its perspective).
my turtle.right(degrees) – rotates my turtle degrees right.
• my turtle.fd(distance) – moves the my turtle distance units forward.
my turtle.bk(distance) – moves the turtle distance units backwards.
• my turtle.pu() – picks the pen up
• my turtle.pd() – puts the pen down (ready to write)
• my turtle.circle(radius) – creates a circle with radius radius. The circle will be above the direction
the turtle was facing when it started drawing. The turtle will move left and up in a circle and end up in
the same place as before.
• my turtle.goto(X,Y) – (or my turtle.setposition(X,Y)) moves the turtle to the position (X,Y) (and
draws a line from the current position to (X,Y) if the pen is down.
• my turtle.pos() – returns the X and Y values of the current position, e.g., X,Y = my turtle.pos()
12. time.sleep(sec) – pauses for sec seconds (requires the module sleep to be imported)
13. random – the random module
• random.random() returns a number between 0 and 1
• random.randint(num1,num2) returns a number between num1 and num2 (inclusive).
• random.choice(sequence) returns member of sequence.
14. Input/Output
• os – module including global variables like os.linesep (end of line strings: ’\n’ or ’\r\n’) and os.sep
(path separators – forward slash ’/’ or backward slash ’\’). The os module also includes functions that
interact with the operating system. os.getcwd() returns the current working directory. os.listdir(PATH)
returns a list of files in PATH; os.path.isdir(PATH) returns True if PATH is a directory and False other-
wise; os.path.isfile(PATH) returns True if PATH is the name of an existing file and False otherwise.
• Streams – Python objects used for reading files and writing to files.
• instream = open(’my file.txt’,’r’) sets the variable instream to the contents of the file ’my file.txt’. for
loops will treat instream as a list of strings, each ending with os.linesep. For most applications, it makes
sense to remove these.
• outstream = open(’my file.txt’,’w’) sets the variable outstream to an object that will ultimately be saved
as the file my file.txt. The method outstream.write(string) will write a string to that file. It is a good
idea to include \n anywhere you would like a line break in the file as end of lines are not automatic.
\n should be used, rather than os.linesep, even in Windows.
• stream.close() will close an opened stream. This ends the connection between Python and a file. In the
case of output streams (like outstream), the content of the stream is written to the file.
• with open(file,’r’) as instream: or with open(file,’w’) as outstream: starts a block in which a stream is
opened. The body of code indented under these statements can read from or write to the stream. After
the block ends, the stream is closed.
15. Error Handling
• Try/Except – Two key words that begin blocks, similar to IF/Else statements. If the code indented under
Try: does not cause any error, then the following Except statements are ignored. If an error is raised,
the Except statements can “catch” an error. Rather than the error occurring (and the code halting), the
code indicated under Except executes.
16. Programming paradigms – these represent approaches to programming that were introduced near the end
of the semester. These paradigms represent different methodology than previous ones, not just new data
structures.
• Recursion: A recursive function typically includes a base case, in which solving the problem consists
of a single step and one or more recursive case. For the recursive case, the function solves a small part
of the problem and the calls “itself” again, but on a smaller version of the problem. In the following
count down function: the function will print 1 if one is the argument of count down. For the recursive
case, recursive count down will print the current number argument and then recursively call itself with
one less than the current number as an argument:
def recursive_count_down(number):
if number == 1:
print(number)
else:
print(number)
recursive_count_down(number-1)
• Object Oriented Programming: A style of programming in which methods (functions) and attributes
(variables) are linked to objects which they help characterize and define. Methods with the same names
can be linked to different object classes. However, they should have somewhat analogous functions.
For example a roll method should choose a random number for any die object, but depending on
the particular class of die object, the method may be different. For example, dice can have different
numbers of sides (so the choice of numbers can vary). When rolling a “fair” die, one can expect that
each possible number will have the same odds of landing on each side. However, it is also possible to
implement an “unfair” die and put different weights on the different sides.
Some example class definitions:
import random

class die:
None

class die_basic (die):


def __init__(self):
self.number_of_sides = 6
self.face = random.randint(1,self.number_of_sides)
self.number_of_sides = number_of_sides
def __repr__(self):
return(str(self.number_of_sides)+’-sided #: ’+str(utility.get_id
def __str__(self):
return(str(self.number_of_sides)+’-sided. On:’+str(self.face))
def roll(self):
self.face = random.randint(1,self.number_of_sides)
return(self.face)

class die8 (die_basic):


def __init__(self):
self.number_of_sides = 8
self.face = random.randint(1,self.number_of_sides)
self.number_of_sides = self.number_of_sides

You might also like