Why won't the cities print? Python

Put your programming skills to the test in these challenges.

Why won't the cities print? Python

Post by ghostheadx2 on Wed Apr 29, 2015 2:18 pm
([msg=87859]see Why won't the cities print? Python[/msg])

When I try to run this program in cmd prmpt, It won't return the values for items in the dictionary. I thought I typed it as was in the book. It's not working though:

Code: Select all
cities={'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}

cities['NY']='New York'
cities['OR']='Portland'

def find_city(themap, state):
  if state in themap:
    return themap[state]
  else:
    return "Not found"

#ok pay attention!
cities['_find']=find_city

while True:
  print "State? (ENTER to quit)"
  state=raw_input("> ")
 
  if not state: break
 
#this line is the most important line ever, study!!
city_found=cities['_find'](cities, state)
print city_found


I'm pretty sure its a syntax error, but my cmd prompt lets me type it in. and loops the program from the beginning.
ghostheadx2
Contributor
Contributor
 
Posts: 728
Joined: Wed Nov 19, 2014 1:19 am
Blog: View Blog (0)


Re: Why won't the cities print? Python

Post by Turn on Thu Apr 30, 2015 4:54 am
([msg=87864]see Re: Why won't the cities print? Python[/msg])

So, it's not really just a syntax error. This code is structured incorrectly.
Let's go over the objective of the code, and then review what actually happens.

- Define a list of States with a key pair according to a city in the state. i.e, CA => San Francisco
- Create a method to get a state from a user and return the city (according to our defined list)
- Print the city assigned to the given state

Here you did the task of creating the state list with cities paired to them.
Code: Select all
cities={'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
cities['NY']='New York'
cities['OR']='Portland'


Here you defined a method that takes the state list and some given state. The result of this method will be the city inside the state list, or the result 'Not found'. The key thing to note is that we pass our state list and state to the method.
Code: Select all
def find_city(themap, state):
  if state in themap:
    return themap[state]
  else:
    return "Not found"


This piece of code is irrelevant and unneeded. You are appended to the state list a new item with a key as the state we are searching for. This will clutter the state list with data it doesn't actually need. There is a better approach and solution.
Code: Select all
#ok pay attention!
cities['_find']=find_city


It appears that the goal here is to create an infinite loop until the user enters a state that does not exist. The problem here is that state is always going to exist (even if it is invalid) unless the user enters a nil value (i.e, a carriage return)
Code: Select all
while True:
  print "State? (ENTER to quit)"
  state=raw_input("> ")
 
  if not state: break


Again, this code is outside of the loop initialized above, and is also not relevant to us. The word pair value you defined above is being declared to the variable city_found and then you attempt to print that value out.
Code: Select all
#this line is the most important line ever, study!!
city_found=cities['_find'](cities, state)
print city_found


Now, if you look at your code you will find that you defined your method: find_city
Do you call this function anywhere and pass the correct parameters? The answer is no. You only define two variables from the method.

The correct code calling the method appropriately would look something like this:
Code: Select all
cities={'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}

cities['NY']='New York'
cities['OR']='Portland'

def find_city(themap, state):
  if state in themap:
    return themap[state]

while True:
  print "State? (ENTER to quit)"
  state=raw_input("> ")
  found_city = find_city(cities, state)
  if state in cities:
    print found_city
  else:
    print 'Terminating'
    break


Online interpreter
Social Engineering:
<cen> .lua print ('Tsyn 9.47.-u 3 12 5')
* slickery has quit (User has been banned from HackThisSite (Attempting to use a SpyBot))
* cen has quit (User has been banned from HackThisSite (Attempting to use a SpyBot))
User avatar
Turn
Poster
Poster
 
Posts: 120
Joined: Tue Feb 17, 2015 5:42 am
Blog: View Blog (0)


Re: Why won't the cities print? Python

Post by ghostheadx2 on Thu Apr 30, 2015 10:22 pm
([msg=87868]see Re: Why won't the cities print? Python[/msg])

Thanks, that worked a lot better than the code FROM THE BOOK?! Lol.
ghostheadx2
Contributor
Contributor
 
Posts: 728
Joined: Wed Nov 19, 2014 1:19 am
Blog: View Blog (0)


Re: Why won't the cities print? Python

Post by tgoe on Sat May 02, 2015 5:22 am
([msg=87887]see Re: Why won't the cities print? Python[/msg])

That's just a typo by either you or the author. The code after the while block should have been included within it.

Code: Select all
cities={'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}

cities['NY']='New York'
cities['OR']='Portland'

def find_city(themap, state):
    if state in themap:
      return themap[state]
    else:
      return "Not found"

#ok pay attention!
cities['_find']=find_city

while True:
    print "State? (ENTER to quit)"
    state=raw_input("> ")

    if not state: break

    #this line is the most important line ever, study!!
    city_found=cities['_find'](cities, state)
    print city_found


The code is a little strange. The point is probably to introduce the idea of first-class functions. Functions in Python are just variables of type 'function'.

Maybe this is a better example:
Code: Select all
#speak.py

def make_voice(v):
    def to_self(words):
        return "..."

    def whisper(words):
        return "(" + words + ")"

    def normal(words):
        return words

    def loudly(words):
        return words + "!"

    def screaming(words):
        return words.upper() + "!!!!"

    voices = {
        0: to_self,
        1: whisper,
        2: normal,
        3: loudly,
        4: screaming
    }

    return voices[v]

def speak(words, v):
    voice = make_voice(v)
    print(voice.func_code)
    print("voice->%s('%s')" % (voice.func_name, words))
    print("%s" % voice(words))
    print("%s\n" % voice("yes, they are"))

speak("hippos are huge", 0)
speak("hippos are huge", 1)
speak("hippos are huge", 2)
speak("hippos are huge", 3)
speak("hippos are huge", 4)


First, look at the make_voice function. Notice how local functions can be made just like any other local variable. You can stuff these away easily inside data structures like the voices dict. You can even use these as return values.

In the speak function I make a variable of type 'function' called 'voice' by assigning the return value of make_voice to it. 'voice' will now act as if it were which ever function was returned -- it points to the same code object in memory.

Output:
Code: Select all
<code object to_self at 0x800734330, file "speak.py", line 4>
voice->to_self('hippos are huge')
...
...

<code object whisper at 0x800734cb0, file "speak.py", line 7>
voice->whisper('hippos are huge')
(hippos are huge)
(yes, they are)

<code object normal at 0x800755ab0, file "speak.py", line 10>
voice->normal('hippos are huge')
hippos are huge
yes, they are

<code object loudly at 0x800755030, file "speak.py", line 13>
voice->loudly('hippos are huge')
hippos are huge!
yes, they are!

<code object screaming at 0x8007553b0, file "speak.py", line 16>
voice->screaming('hippos are huge')
HIPPOS ARE HUGE!!!!
YES, THEY ARE!!!!

User avatar
tgoe
Contributor
Contributor
 
Posts: 716
Joined: Sun Sep 28, 2008 2:33 pm
Location: q3dm7
Blog: View Blog (0)



Return to Programming

Who is online

Users browsing this forum: No registered users and 0 guests