Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

random_no = random.sample(range(0, 10), 4)
cows = 0
bulls = 0
#random_num = ','.join(map(str, random_no))
print(random_no)
user_input = input("Guess the no: ")
for index, num in enumerate(random_no):
    global cows, bulls
    print(index, num)
    if user_input[index] == num:
        cows += 1
    elif user_input[index] in random_no:
        bulls += 1

print(f'{cows} cows and {bulls} bulls')
like image 202
k.lo Avatar asked Jul 04 '17 17:07

k.lo


2 Answers

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 += 1
    elif user_input in random_no:
        bulls += 1
like image 73
Martijn Pieters Avatar answered Oct 10 '22 01:10

Martijn Pieters


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.

like image 41
Ben Avatar answered Oct 10 '22 00:10

Ben