-1

I declare a global variable pos, anyway the method printArr() doesn't see it. The interpreter says: undifined variable pos. Why? Thanks

import nltk


class Analyzer():

    """Implements sentiment analysis."""





    def __init__(self, positives, negatives):
        global pos
        global neg
        positives=[]
        negatives=[]
        i=0
        file = open("negative-words.txt","r")
        for line in file:
            h=file.readline()
            if h!="":
                if h[0]!=';':
                    negatives.append(h)
                    i=i+1
                    print(h)

        i=0
        file = open("positive-words.txt","r")
        for line in file:
            h=file.readline()
            if h!="":
                if h[0]!=';':
                    positives.append(h)
                    i=i+1
                    print(h)
        neg=negatives
        pos=positives


    def printArr (self, arr):
        print (pos[2])
    """Initialize Analyzer."""

I'll try to make it easier: The next code does not work properly, the program still prints out "0", not "5"

import os
import sys
global x
x=0

def func1():
    x=5
def func2():
    print (x)

func2()

2 Answers2

0

Python will always look for local variables first before searching in global scope.

Your func2() will always refer to global value of x as x is not defined locally.

You could try to nest the 2 functions.

Func2(func1())

That way your func1 will assign value 5 to variable x and func2 will return 5 instead of 0.

Hope it helps.

Sagar Dawda
  • 1,126
  • 9
  • 17
  • Thanks! The interpreter says: too many positional arguments in function call. Right now I am aware that I did not even call func2() in order to change the variable x. Now I did it, but all the same it prints out "0" – Сергій Фокін Sep 11 '17 at 19:07
  • Ok ... I am writing the code in another answer. This one did return 5 – Sagar Dawda Sep 13 '17 at 06:56
0
def func1():
    x = 5
    return x

def func2():
    print(func1())

#It returned 5
Sagar Dawda
  • 1,126
  • 9
  • 17
  • func1() will create the local variable x as defined by us to be used in func2() – Sagar Dawda Sep 13 '17 at 07:00
  • Thanks, Sagar. It did work for me! Am I right if I understand a global variable as that one seen in all the scopes and always retaining the last assigned value? – Сергій Фокін Sep 14 '17 at 06:14
  • Glad to hear it worked for you. And you got it absolutely right about the global variables :) – Sagar Dawda Sep 14 '17 at 08:31
  • Thanks! And, in the case of Python, in order to "update" the last assigned value of a variable, I should call all the funcions that deal with that variable. Right? Anyway, I wold like to see how the modificator "global" is used. – Сергій Фокін Sep 15 '17 at 06:59
  • Yup. You can also modify global variables from within the function however thats a bad practice. – Sagar Dawda Sep 15 '17 at 07:47