Python While Loop: Else tripped despite valid input -


doing cs101 course github oss , i've got bug 1 of projects runs fine specific use case(input: o, m, n, ., n) last 'n' triggers else block (even though prints out 'n' variable gamedecision. i've tried can think of coming short. since course closed, advice appreciated. thanks!

link problem: https://courses.edx.org/courses/course-v1:mitx+6.00.1x_8+1t2016/courseware/week_4/problem_set_4/

code:

# 6.00x problem set 4a template # # 6.00 word game # created by: kevin luu <luuk> , jenna wiens <jwiens> # modified by: sarina canelake <sarina> #  import random import string  vowels = 'aeiou' consonants = 'bcdfghjklmnpqrstvwxyz' hand_size = 7  scrabble_letter_values = {     'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 }  # ----------------------------------- # helper code # (you don't need understand helper code)  wordlist_filename = "words.txt"   def loadwords():     """     returns list of valid words. words strings of lowercase letters.      depending on size of word list, function may     take while finish.     """     print "loading word list file..."     # infile: file     infile = open(wordlist_filename, 'r', 0)     # wordlist: list of strings     wordlist = []     line in infile:         wordlist.append(line.strip().lower())     print "  ", len(wordlist), "words loaded."     return wordlist  def getfrequencydict(sequence):     """     returns dictionary keys elements of sequence     , values integer counts, number of times     element repeated in sequence.      sequence: string or list     return: dictionary     """     # freqs: dictionary (element_type -> int)     freq = {}     x in sequence:         freq[x] = freq.get(x,0) + 1     return freq   # (end of helper code) # -----------------------------------  # # problem #1: scoring word # def getwordscore(word, n):     """     returns score word. assumes word valid word.      score word sum of points letters in     word, multiplied length of word, plus 50 points if n     letters used on first turn.      letters scored in scrabble; worth 1, b worth 3, c     worth 3, d worth 2, e worth 1, , on (see scrabble_letter_values)      word: string (lowercase letters)     n: integer (hand_size; i.e., hand size required additional points)     returns: int >= 0     """     # ... <-- remove comment when code function     count = 0     in word:         count += scrabble_letter_values[i]     count *= len(word)     if len(word) == n:         count += 50     return count    # # problem #2: make sure understand how function works , does! # def displayhand(hand):     """     displays letters in hand.      example:     >>> displayhand({'a':1, 'x':2, 'l':3, 'e':1})     should print out like:        x x l l l e     order of letters unimportant.      hand: dictionary (string -> int)     """     letter in hand.keys():         j in range(hand[letter]):              print letter,              # print on same line     print                               # print empty line  # # problem #2: make sure understand how function works , does! # def dealhand(n):     """     returns random hand containing n lowercase letters.     @ least n/3 letters in hand should vowels.      hands represented dictionaries. keys     letters , values number of times     particular letter repeated in hand.      n: int >= 0     returns: dictionary (string -> int)     """     hand={}     numvowels = n / 3      in range(numvowels):         x = vowels[random.randrange(0,len(vowels))]         hand[x] = hand.get(x, 0) + 1      in range(numvowels, n):             x = consonants[random.randrange(0,len(consonants))]         hand[x] = hand.get(x, 0) + 1      return hand  # # problem #2: update hand removing letters # def updatehand(hand, word):     """     assumes 'hand' has letters in word.     in other words, assumes many times     letter appears in 'word', 'hand' has @ least     many of letter in it.       updates hand: uses letters in given word     , returns new hand, without letters in it.      has no side effects: not modify hand.      word: string     hand: dictionary (string -> int)         returns: dictionary (string -> int)     """     # ... <-- remove comment when code function     chand = hand.copy()     in word:         if chand.get(i,0) == 0:             return false             break         else:             chand[i] -= 1     return chand       # # problem #3: test word validity # def isvalidword(word, hand, wordlist):     """     returns true if word in wordlist , entirely     composed of letters in hand. otherwise, returns false.      not mutate hand or wordlist.      word: string     hand: dictionary (string -> int)     wordlist: list of lowercase strings     """     # ... <-- remove comment when code function     chand = hand.copy()     if word in wordlist , updatehand(chand, word) != false:         return true     else:         return false   # # problem #4: playing hand #  def calculatehandlen(hand):     """      returns length (number of letters) in current hand.      hand: dictionary (string-> int)     returns: integer     """     # do... <-- remove comment when code function     length = 0     in hand:         length += hand.get(i, 0)     return length     def playhand(hand, wordlist, n):     """     allows user play given hand, follows:      * hand displayed.     * user may input word or single period (the string ".")        indicate they're done playing     * invalid words rejected, , message displayed asking       user choose word until enter valid word or "."     * when valid word entered, uses letters hand.     * after every valid word: score word displayed,       remaining letters in hand displayed, , user       asked input word.     * sum of word scores displayed when hand finishes.     * hand finishes when there no more unused letters or user       inputs "."        hand: dictionary (string -> int)       wordlist: list of lowercase strings       n: integer (hand_size; i.e., hand size required additional points)      """     score = 0      while calculatehandlen(hand) > 0:          displayhand(hand)         word = raw_input("please provide word: ")         if word == ".":             break         else:             if isvalidword(word, hand, wordlist) != true:                 print "please enter valid word"              else:                 print "points scored: " + str(getwordscore(word, n))                 score += getwordscore(word, n)                 hand = updatehand(hand,word)      print "game over! total score: " + str(score)   # # problem #5: playing game #   def playgame(wordlist):     """     allow user play arbitrary number of hands.      1) asks user input 'n' or 'r' or 'e'.       * if user inputs 'n', let user play new (random) hand.       * if user inputs 'r', let user play last hand again.       * if user inputs 'e', exit game.       * if user inputs else, tell them input invalid.      2) when done playing hand, repeat step 1         """      n = random.randint(3,9)     hand = dealhand(n)     gamedecision = raw_input("input 'n' or 'r' or 'e': ")     quitting = false       while quitting == false:          if gamedecision == "n":             n = random.randint(3,9)             hand = dealhand(n)             playhand(hand, wordlist, n)             gamedecision = raw_input("input 'n' or 'r' or 'e': ")          if gamedecision == "r":             playhand(hand, wordlist, n)             gamedecision = raw_input("input 'n' or 'r' or 'e': ")          if gamedecision == "e":             quitting = true          else:             print "input invalid"             gamedecision = raw_input("input 'n' or 'r' or 'e': ")                 # # build data structures used entire session , play game # if __name__ == '__main__':     wordlist = loadwords()     playgame(wordlist) 

because of way formed block:

    if gamedecision == "n":         n = random.randint(3,9)         hand = dealhand(n)         playhand(hand, wordlist, n)         gamedecision = raw_input("input 'n' or 'r' or 'e': ")      if gamedecision == "r":         playhand(hand, wordlist, n)         gamedecision = raw_input("input 'n' or 'r' or 'e': ")      if gamedecision == "e":         quitting = true      else:         print "input invalid"         gamedecision = raw_input("input 'n' or 'r' or 'e': ")        

the else case tied if case "e" character. should using "elif" statements "r" , "e" case.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -