Skip to content Skip to sidebar Skip to footer

Syntaxerror: Name 'cows' Is Assigned To Before Global Declaration In Python3.6

I am trying to edit the global variables cows and bulls inside a loop but getting this error 'SyntaxError: name 'cows' is assigned to before global declaration' import random rand

Solution 1:

Python has no block scoping, only functions and classes introduce a new scope.

Because you have no function here, there is no need to use a global statement, cows and bulls are already globals.

You have other issues too:

  • input() returns a string, always.

  • Indexing works on strings (you get individual characters), are you sure you wanted that?

  • user_input[index] == num is always going to be false; '1' == 1 tests if two different types of objects are equal; they are not.

  • user_input[index] in random_no is also always going to be false, your random_no list contains only integers, no strings.

If the user is to enter one random number, convert the input() to an integer, and don't bother with enumerate():

user_input = int(input("Guess the no: "))
for num in random_no:
    if user_input == num:
        cows += 1elif user_input in random_no:
        bulls += 1

Solution 2:

You give cows a value before you declare it as global. You should declare your global scope first

Btw you dont need the global declarations. Just remove this line.

Post a Comment for "Syntaxerror: Name 'cows' Is Assigned To Before Global Declaration In Python3.6"