Python Forum

Full Version: Help me please!!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Okay, so I am posting about the same thing I did last time I posted here. This program doesn't work:
def getNumber(low, high, prompt="Enter a number: "):
    number=low-1
    while number<low or number>high:
        numberString=input(prompt)
        try:
            number=int(numberString)
        except ValueError:
            print("That is not a valid number")
    return number

def compress():
    file1 = open("words.txt", "w")
    file2 = open("positions.txt", "w")
    sentence = input("What is your sentence?: ")
    sentence = sentence.split()
    words = sentence
    positions = [0]
    uniqueWords = []
    for i in words:
        if i not in uniqueWords:
            uniqueWords.append(i)
    uniqueWords = " ".join(uniqueWords)
    file1.write(uniqueWords)
    file1.close()
    for count, i in enumerate(sentence): 
        if sentence.count(i) < 2:
            positions.append(max(positions) + 1)
        else:
            positions.append(sentence.index(i) + 1)    
    positions.remove(0)
    positions = " ".join(map(str, positions))
    file2.write(positions)
    file2.close()
    print("Check your folder")
    return

def decompress():
    global positions
    global uniqueWords
    uniqueWords = uniqueWords.split()
    newSentence = []
    positions = list(map(int,positions.split()))
    file3 = open("original.txt","w")
    for i in positions:
        newSentence.append(uniqueWords[i-1])
    newSentence = " ".join(newSentence)
    file3.write(newSentence)
    file3.close()
    return

loop = True
while loop:
    print("\nTask3 Menu\n1. Compress a sentence\n2. Decompress a sentence\n3. End the program")
    choice = getNumber(1,3,"Enter your choice (1,2 or 3): ")
    if choice == 1:
        compress()
    elif choice == 2:
        decompress()
    else:
        loop = False
        print("Program ending...")
It returns this error message whenever I choose decompress:
Error:
Traceback (most recent call last):   File "//HUHTA-FPS0001/Claitusers$/huhta-clait53/documents/Phillip Holmes/Programs/Task3/Task3v7.py", line 58, in <module>     decompress()   File "//HUHTA-FPS0001/Claitusers$/huhta-clait53/documents/Phillip Holmes/Programs/Task3/Task3v7.py", line 40, in decompress     uniqueWords = uniqueWords.split() NameError: name 'uniqueWords' is not defined
However, this version works:
def reverse():
    global positions
    global uniqueWords
    uniqueWords = uniqueWords.split()
    newSentence = []
    positions = list(map(int,positions.split()))
    file3 = open("original.txt","w")
    for i in positions:
        newSentence.append(uniqueWords[i-1])
    newSentence = " ".join(newSentence)
    file3.write(newSentence)
    file3.close()
    return
file1 = open("words.txt", "w")
file2 = open("positions.txt", "w")
sentence = input("What is your sentence?: ")
sentence = sentence.split()
words = sentence
positions = [0]
uniqueWords = []
for i in words:
    if i not in uniqueWords:
        uniqueWords.append(i)
uniqueWords = " ".join(uniqueWords)
file1.write(uniqueWords)
file1.close()
for count, i in enumerate(sentence): 
    if sentence.count(i) < 2:
        positions.append(max(positions) + 1)
    else:
        positions.append(sentence.index(i) + 1)    
positions.remove(0)
positions = " ".join(map(str, positions))
file2.write(positions)
file2.close()
option = input("Would you like to convert your sentence back to its original form? ")
if option in ["yEs","yeS","yES","YEs","Yes","yes","YES","y","Y"]:
    reverse()
Do you have any question?
It's pretty clear - Read the error message:

Quote:NameError: name 'uniqueWords' is not defined
Using globals is bad practice and can be avoided.
you are trying to instantiate a global that was never defined
instead, pass uniqueWords as argument to function
Global variables are those defined outside any function, class definition. Inside a function, you explicitly specify that you want to use that global variable.


hdd_space = 1000

def add_more_hdd(new_hdd):
    global hdd_space
    
    return hdd_space + new_hdd
Actually you do not need to use global keyword to access variables from the global scope in a local scope. You need it when you want to create or change global variables from local scope.

And as Larz60+ said, its usually bad idea and you should not use it unless you really know what are you doing. So use function parameters and function return values.
The real question is why are you using global variables?