Search code examples
pythonvalidationinputuser-input

Python Global Variable Errors


  global temp
   while True:
       Print("Please enter a text: ")
       text = raw_input()
   if text == temp:
       print("the same value")
   else:
       temp = text
       print(text)

I have this code to check if the user is repeating the same value, but getting below error:

NameError: global name 'temp' is not defined

I don't know why I declare the temp but got this error. Is there any other way to check if user keep on putting the same value?


Solution

  • no need to use use global at all.

    temp = ""  # Define empty temp
    while True:
        text = raw_input("Please enter a text: ")   #write your print message in raw_input only
        if text == temp:  #compare with temp
            print("the same value")
        else:
            temp = text
            print(text)
    

    Output:

    Please enter a text: hi
    hi
    Please enter a text: hi
    the same value
    Please enter a text: new
    new
    Please enter a text: new
    the same value
    Please enter a text: new
    the same value
    Please enter a text: hi
    hi