SyntaxError: name 'cows' is assigned to before global declaration in Python3.6

孤人 提交于 2020-05-29 02:37:14

问题


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')

回答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 += 1
    elif user_input in random_no:
        bulls += 1



回答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.



来源:https://stackoverflow.com/questions/44911743/syntaxerror-name-cows-is-assigned-to-before-global-declaration-in-python3-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!