[Tutor] How the shell relates to programs in idle
daniel rieder
mdrieder at msn.com
Tue Feb 25 09:48:03 EST 2020
I am new to Python and am going through a guide at anh.cs.edu/handsonPythonTutorial.
I am learning how to create dictionaries PLUS learning how, when a program is run, the variables and, as I understand it, dictionaries created in a program that is run from idle are retained so they can be accessed via the shell. For example, I created a program that, among other things, creates a variable x=3. After I ran the program, I used the shell and entered print(x) and it dutifully printed 3. Well and good.
But supposedly if I create a dictionary in a program and run that program, the dictionary is still “stored” by python such that if I enter a print line in the shell referencing the dictionary, it should print the contents I indexed.
Here is the program:
def createDictionary():
'''Returns a tiny Spanish dictionary'''
spanish = dict()
spanish['hello'] = 'hola'
spanish['yes'] = 'si'
spanish['one'] = 'uno'
spanish['two'] = 'dos'
spanish['three'] = 'tres'
spanish['red'] = 'rojo'
spanish['black'] = 'negro'
spanish['green'] = 'verde'
spanish['blue'] = 'azul'
return spanish
def main():
dictionary = createDictionary()
print(dictionary['two'])
print(dictionary['red'])
main()
When I ran the program, it displayed ‘dos’ and ‘rojo’ as intended. Then immediately afterward, using the shell, I typed in: print (dictionary[‘two’]) hoping it would access the dictionary and print “dos,” but it returned an error message:
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
print (spanish['two'])
NameError: name 'dictionary' is not defined
Did I make a mistake in how I referenced the dictionary? Or is the guidance I am following somehow outdated such that NOW python no longer stores dictionaries after the program is run like it seems to store variables…like it did x in the above example?
Thanks, Dan
More information about the Tutor
mailing list