Week 11 — Homework assignment
due: Tues, November 16, 8pm
Review the class notes for last week (week 10) and this week (week 11).
Please note: You have a reading to prepare for discussion this week. Check the schedule page (under week 12).
Python warm-up in the interactive shell. Open up Terminal or Cygwin, run the Python shell, create a simple loop that prints a message 5 times.
Can you also print the looping variable?
Challenge. Can you print a five-by-five grid of some
character? Hint: you'll need a nested loop
back from week 5, and you'll also
need to know that you can print without a line break with the
following optional parameter: print("x ",end="")
Post a screenshot of your interactive Python shell session that does this into your homework folder for this week.
A simple interactive Python program. Create a
new file in Atom and save it
as week11-part2.py
. Review
the Interactive
python file exercise discussion from the week 10 notes,
and follow the instructions there to create a program that
prompts the user for two inputs: their name and a number, then
prints their name that number of times.
Create a simple word definition lookup
program. Open your text editor (Atom), create a new
file, and save it
as week11-part3.py
. In it, create a
new dictionary
variable. Add key-value pairs that correspond
to words and their definitions. Add as many as you'd like.
Now, use the Python command input()
to ask the
user for a word. Remember that you can pass an argument to
this command as a prompt, and the return value is the string
that the user entered. You can read more
in
the Python documentation here. So for example:
user_text = input("Please enter a word: ")The variable
user_text
will now contain the user
input, and you can use this as a key with
your dictionary.
Look up the definition for the word that the user typed and print it.
Try running it and entering some words for which you have
definitions. What happens if you enter a word for which you
don't have a definition? You should get
a KeyError
. You can prevent this by using
the in
command (see the section
on dictionary syntax
and usage from week 10). If the user input
is in
your dictionary, print the
definition to the user, if not (else
) print a
message stating "I don't know that word."
Expand this example using a while
loop so that
the program repeatedly asks the user for a word. You can use
an infinite while
loop (while True
)
which means the user would have to enter CONTROL-c to exit, or
you could use a check for some kind of stop word (such
as while user_text != "exit"
).
in
the dictionary, ask the user if they
would like to add it. You can prompt the user to
type "y"
or "n"
. If the user wants to
define the word, prompt them for a definition, then add that
word and definition to your dictionary as a key-value pair.