oliver
Posts: 26
Joined: Sun Mar 30, 2014 4:53 pm

Globals?

Sat Dec 12, 2015 9:17 am

Hi

I am a beginner in python and am trying to make a code which translates text to morse code, in a tkinter application

I get this error message

Code: Select all

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1437, in __call__
    return self.func(*args)
  File "morsecode.py", line 17, in translate
    loop()
  File "morsecode.py", line 242, in loop
    length = len(phrase)
NameError: global name 'phrase' is not defined

Sorry my code is very long but almost all of it repeats itself

Code: Select all

import time
import RPi.GPIO as GPIO
from Tkinter import *

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11, False)

root = Tk()
root.wm_title('Morse Code Translator')

def translate():
  raw = text.get()
  print raw
  phrase = raw.lower()
  loop()

frame = Frame(root, width=100, height=100)
frame.pack()
write = Label(frame, text='write text below:')
write.pack()
text = Entry(frame)
text.pack()
text.delete(0, END)

button = Button(frame, text='translate', fg='red', command=translate)
button.pack()


def a():
  print 'a'
  dot()
  dash()
  pause()

def b():
  print 'b'
  dash()
  dot()
  dot()
  dot()
  pause()

def c():
  print 'c'
  dash()
  dot()
  dash()
  dot()
  pause()

def d():
  print 'd'

  dash()
  dot()
  dot()
  pause()

def e():
  print 'e'
  dot()
  pause()

def f():
  print 'f'
  dot()
  dot()
  dash()
  dot()
  pause()

def g():
  print 'g'
  dash()
  dash()
  dot()
  pause()

def h():
  print 'h'
  dot()
  dot()
  dot()
  dot()
  pause()

def i():
  print 'i'
  dot()
  dot()
  pause()

def j():
  print 'j'
  dot()
  dash()
  dash()
  dash()
  pause()

def k():
  print 'k'
  dash()
  dot()
  dash()
  pause()

def l():
  print 'l'
  dot()
  dash()
  dot()
  dot()
  pause()

def m():
  print 'm'
  dash()
  dash()
  pause()

def n():
  print 'n'
  dash()
  dot()
  pause()

def o():
  print 'o'
  dash()
  dash()
  dash()
  pause()

def p():
  print 'p'
  dot()
  dash()
  dash()
  dot()
  pause()

def q():
  print 'q'
  dash()
  dash()
  dot()
  dash()
  pause()

def r():
  print 'r'
  dot()
  dash()
  dot()
  pause()

def s():
  print 's'
  dot()
  dot()
  dot()
  pause()

def t():
  print 't'
  dash()
  pause()

def u():
  print 'u'
  dot()
  dot()
  dash()
  pause()

def v():
  print 'v'
  dot()
  dot()
  dot()
  dash()
  pause()

def w():
  print 'w'
  dot()
  dash()
  dash()
  pause()

def x():
  print 'x'
 dot()
  dash()
  pause()

def y():
  print 'y'
  dash()
  dot()
  dash()
  dash()
  pause()

def z():
  print 'z'
  dash()
  dash()
  dot()
  dot()
  pause()

def pause():
  time.sleep(1)

def space():
  print 'space'
  time.sleep(3.0)


def dash():
  print 'dash'
  GPIO.output(11, True)
  time.sleep(1.5)
  GPIO.output(11, False)
  time.sleep(0.5)

def dot():
  print 'dot'
  GPIO.output(11, True)
  time.sleep(0.5)
  GPIO.output(11, False)
  time.sleep(0.5)


def loop():
  number = 0
  length = len(phrase)
  while number < length:
    words = phrase[number]
    number += 1
    if words == 'a':
      a()
    elif words == 'b'
    b()
    elif words == 'c':
      c()
    elif words == 'd':
      d()
    elif words == 'e':
      e()
    elif words == 'f':
      f()
    elif words == 'g':
      g()
    elif words == 'h':
      h()
    elif words == 'i':
      i()
    elif words == 'j':
      j()
    elif words == 'k':
      k()
    elif words == 'l':
      l()
    elif words == 'm':
      m()
    elif words == 'n':
      n()
    elif words == 'o':
      o()
    elif words == 'p':
      p()
    elif words == 'q':
      q()
    elif words == 'r':
      r()
    elif words == 's':
      s()
    elif words == 't':
      t()
    elif words == 'u':
      u()
    elif words == 'v':
      v()
    elif words == 'w':
      v()
    elif words == 'x':
      x()
    elif words == 'y':
      y()
    elif words == 'z':
      z()
    elif words == ' ':
      space()
  else:
    print 'error'


root.mainloop()
thanks in advance

Olly

User avatar
PeterO
Posts: 5951
Joined: Sun Jul 22, 2012 4:14 pm

Re: Globals?

Sat Dec 12, 2015 9:39 am

The error message is telling you exactly what is wrong with your code.

File "morsecode.py", line 242, in loop
length = len(phrase)
NameError: global name 'phrase' is not defined

In English this reads as

"On line 242 of the file morsecode.py, in the function called "loop", the python interpreter has come across a variable called "phrase" for the first time and it doesn't know what it is !"

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
AndyD
Posts: 2334
Joined: Sat Jan 21, 2012 8:13 am
Location: Melbourne, Australia
Contact: Website

Re: Globals?

Sat Dec 12, 2015 9:49 am

Hi, it is complaining because you are using phrase as if it were a global variable (i.e. a variable defined outside of a function), but it is never defined outside of a function.

In the function translate the code:

Code: Select all

   phrase = raw.lower()
creates a local variable called phrase (i.e. it is only visible to code within the function). When you call the function loop you use phrase, but it can't find it. One way to solve this would be to initialize a variable phrase outside of the functions.

However, a better solution would be to pass phrase as an argument to loop. So change

Code: Select all

def translate():
  raw = text.get()
  print raw
  phrase = raw.lower()
  loop(phrase)
Then change the function loop to this:

Code: Select all

def loop(phrase):

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Globals?

Sat Dec 12, 2015 9:51 am

Once you've got your code working, you may then want to look at how you could use a dictionary rather than defining a function for each letter. It should make your code much shorter.

PeterO is right, Python error messages are very good at describing what the problem is.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

User avatar
PeterO
Posts: 5951
Joined: Sun Jul 22, 2012 4:14 pm

Re: Globals?

Sat Dec 12, 2015 10:11 am

elParaguayo wrote: PeterO is right, Python error messages are very good at describing what the problem is.
I'm coming to the conclusion that not enough attention and time is being spent teaching debugging skill to noob programmers.
I can't remember any tutorials that I've seen that don't present perfect examples of code that work first time.
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Globals?

Sat Dec 12, 2015 10:24 am

PeterO wrote:
elParaguayo wrote: PeterO is right, Python error messages are very good at describing what the problem is.
I'm coming to the conclusion that not enough attention and time is being spent teaching debugging skill to noob programmers.
I can't remember any tutorials that I've seen that don't present perfect examples of code that work first time.
PeterO
I would agree. I learnt most of what I know about Python by:
  1. writing some code
  2. getting an error message because I invariably got something wrong
  3. goolgling the error message
  4. finding hundreds of people with the same error message
  5. reading what the message means and how to fix it
  6. updating code
  7. going back to #2!
Olly, please don't take this as a criticism - all we're saying is that an important part of learning how to code is learning what to do when you come across an error. If you can get into the habit of reading the error message, looking at the line in question and searching for help (before asking for help) then I think you'll become much better, much quicker. You will likely even find many examples of people with the same question as you in this very forum.

If you do have more questions about your code and how to improve it then please feel free to ask and we'll do our best to help.

You're doing really well, so keep going!
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

oliver
Posts: 26
Joined: Sun Mar 30, 2014 4:53 pm

Re: Globals?

Sat Dec 12, 2015 11:03 am

Thanks everyone for helping,

i didn't really understand what a global variable was until now.

I did try to look it up online and i managed to do it all with google until now.

I agree with elParaguago and PeterO about the learning more by googling it, but i just completely didn't understand it.


Olly

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Globals?

Sat Dec 12, 2015 11:25 am

oliver wrote:Thanks everyone for helping,

i didn't really understand what a global variable was until now.

I did try to look it up online and i managed to do it all with google until now.

I agree with elParaguago and PeterO about the learning more by googling it, but i just completely didn't understand it.


Olly
Olly, perfect - the most important thing is to get in the habit of trying to debug yourself. It's perfectly understandable that the answers may not make sense when you're starting out so asking here was the best solution.

Have fun with your code.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

User avatar
r3d4
Posts: 983
Joined: Sat Jul 30, 2011 8:21 am
Location: ./

Re: Globals?

Sat Dec 12, 2015 12:10 pm

oliver wrote:i didn't really understand what a global variable was until now.
A good example of variable scope from learnxinyminutes.com/docs/python (< many other good python examples can be found hear !)

Code: Select all

# Function Scope
x = 5

def set_x(num):
    # Local var x not the same as global variable x
    x = num # => 43
    print x # => 43

def set_global_x(num):
    global x
    print x # => 5
    x = num # global var x is now set to 6
    print x # => 6

set_x(43)
set_global_x(6)
Last edited by r3d4 on Sat Dec 12, 2015 12:14 pm, edited 1 time in total.

User avatar
r3d4
Posts: 983
Joined: Sat Jul 30, 2011 8:21 am
Location: ./

Re: Globals?

Sat Dec 12, 2015 12:11 pm

PeterO wrote:I'm coming to the conclusion that not enough attention and time is being spent teaching debugging skill to noob programmers.
I can't remember any tutorials that I've seen that don't present perfect examples of code that work first time.
... A better example might show what errors to expect when things 'is not defined' ;
And like the pages linked above says
Got a suggestion? A correction, perhaps? Open an Issue on the Github Repo, or make a pull request yourself!
Open an Issue ;)

User avatar
PeterO
Posts: 5951
Joined: Sun Jul 22, 2012 4:14 pm

Re: Globals?

Sat Dec 12, 2015 1:08 pm

r3d4 wrote: ... A better example might show what errors to expect when things 'is not defined' ;
I've started a set of "C" tutorials that begin with "Hello world" with errors :-)

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
r3d4
Posts: 983
Joined: Sat Jul 30, 2011 8:21 am
Location: ./

Re: Globals?

Mon Dec 14, 2015 8:19 am

PeterO wrote:I've started a set of "C" tutorials that begin with "Hello world" with errors :-)
Do they have a url? (i did look but only found planes and an elliot emulator )

User avatar
PeterO
Posts: 5951
Joined: Sun Jul 22, 2012 4:14 pm

Re: Globals?

Mon Dec 14, 2015 8:37 am

r3d4 wrote:Do they have a url?
I've not yet done enough for it to be useful. Hope to get on with it soon (when post retirement house tidying is complete!)
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Globals?

Mon Dec 14, 2015 9:24 am

If I have the time, I might do something similar for python showing the common errors that crop up regularly in the forum.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Return to “Python”