[Courses] [python] Lesson 6: Functions and dictionaries

Peggy Russell prusselltechgroup at gmail.com
Mon Aug 1 07:58:03 UTC 2011


===================== Homework ===========================

1. Write a function that takes a dictionary as argument, chooses a random key from that
   dictionary, and returns the key and its value as a tuple.

  #!/usr/bin/python3
  import random

  def get_random_organization(orgs) :
    '''See: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#views-and-iterators-instead-of-lists'''
    key = random.choice(list(orgs.keys()))
    value = orgs[key]
    return (key, value)

    #The above 3 lines could be replaced with:
    #return random.choice(list(orgs.items()))

  orgs = {"LinuxChix"     : "http://linuxchix.org",
          "Ubuntu Women"  : "http://ubuntu-women.org/",
          "Debian Women"  : "http://women.debian.org/",
          "Geek Feminism" : "http://geekfeminism.wikia.com/"
         }

  key, value = get_random_organization(orgs)
  print("{0}  -  {1}".format(key, value))

2. Use the function you just defined to make a flashcard program. The flashcards can be
   on any subject you want (or a mix of subjects).  Make a dictionary of questions and
   answers -- the keys are the questions, the answers are the values.

   See: #3

3. Change your flashcard program so that the user has to type the answer, and you
   compare it against the right answer and keep track of how many were answered right or
   wrong.

   Note: you may find this is kind of a pain, because if you make any typos or add
   extra spaces or anything you don't get credit for a right answer. If you find this to
   be a problem, do you have any ideas for ways you could make it more flexible?

   I chose the route of making the text lowercase and eliminating spaces. The answers
   are in this "minimalistic" form.

  #!/usr/bin/python3
  import datetime  # http://docs.python.org/py3k/library/datetime.html (strftime, timedelta)
  import os        # http://docs.python.org/py3k/library/os.html
  import random    # http://docs.python.org/py3k/library/random.html

  def print_quiz_score(correct, wrong) :
    '''Print the number of correct and incorrect replies.'''
    total = correct + wrong
    print("\nCorrect: {0:d}/{1:.0f}%  Incorrect: {2:d}/{3:.0f}%  Total: {4:d}".format
          (correct, (correct/total)*100, wrong, (wrong/total)*100, total))
    return None

  def finished() :
    '''Return users response to continue quiz.'''
    reply = input("Type 'q' to Quit or enter to Continue...").lower().startswith('q')
    return reply

  def print_footer() :
    '''Print quiz footer info to stdout.'''
    print("\n*Feedback*")
    active = datetime.datetime.now() - startTime
    # http://docs.python.org/py3k/library/functions.html#divmod
    hrs, remainder = divmod(abs(active.seconds), 3600)
    mins, secs = divmod(remainder, 60)
    print("You were active: {0:02d}:{1:02d}:{2:02d}".format(hrs, mins, secs))

    if feedback :
      print("These questions were incorrectly answered:")
      for i in range(len(feedback)) :
        print("  {0} {1}".format(i+1, feedback[i]))
    else :
      print("Yeh! All questions answered correctly.")
    print("Bye " + userName)
    return None

  def get_random_question(quiz) :
    '''Return random question/answer pair.'''
    return random.choice(list(quiz.items()))

  def print_header():
    '''Print quiz header info to stdout.'''
    print("Hello " + userName + "!")
    print(startTime.strftime("%B %d, %Y, %H:%M:%S"))
    print("Try a Python 3 Quiz" + "\n" + "-"*30)
    return None

  def verify_response(reply) :
    ''' Verify users response against quiz answer. '''
    if len(reply) == 0 :                            # No answer
      return False
    elif reply == answer :                          # Long answer
      return True
    elif len(answer) == 1 and reply[0] == answer :  # Short answer
      return True
    else :
      return False

  quiz = {
    "What command do you use to display the Python version?" :
      "python--version",
    "What is the python extension?" :
      "py",
    "true or false: The author of Python is Guido van Rossum." :
      "t",
    "What Python function (v3)/keyword (v2) prints values to a stream?" :
      "print",
    "true or false: Python is case sensitive." :
      "t",
    "What Python built-in function reads a string from standard input?" :
      "input",
    "Given wDays={ 1:'Mon', 2:'Tue', 3:'Wed' }, is wDays a string, list, tuple, or dictionary?" :
      "dictionary",
    "Name the Python numeric loop keyword:" :
      "for",
    "What Python statement generates a list of numbers from 1 to 6:" :
      "range(1,6)",
    "Can a range count backwards, yes or no?" :
      "y",
    "true or false: A colon indicates the start of an indented block." :
      "t",
    "Which one is not a Python flow control statement: for until while?" :
      "until",
    "true or false: + or += can be used to concatenate a string." :
      "t",
    "If name=\"Linus Torvalds\", what is the value of len(name)?" :
      "14",
    "true or false: The print statement is the same in Python V2 and Python V3." :
      "f",
  }

  startTime = datetime.datetime.now()
  userName = os.getenv('USER')
  print_header()
  correct = 0
  wrong = 0
  feedback=[]

  while True :
    question, answer = get_random_question(quiz)

    try :
      reply = input("\n" + question + "\n").lower().replace(' ','')
    except (KeyboardInterrupt, EOFError) :          # ctrl-c  # ctrl-d
      print("Bye " + userName)
      break

    if verify_response(reply) :
      correct += 1
    else :
      print("The correct answer is: " + answer)
      feedback.append(question)
      wrong += 1

    print_quiz_score(correct, wrong)

    if finished() :
      print_footer()
      break

#EOF
Peg


More information about the Courses mailing list