SyntaxError:name'cows'在Python3.6中的全局声明之前被赋值

k.l*_*.lo 5 python global-variables python-3.6

我试图编辑全局变量cowsbulls循环内部,但得到此错误"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')
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 12

Python没有块作用域,只有函数和类引入了新的作用域.

因为你这里有没有作用,有没有必要使用global的语句,cowsbulls已经全局.

您还有其他问题:

  • input() 总是返回一个字符串.

  • 索引适用于字符串(你得到个别字符),你确定你想要吗?

  • user_input[index] == num永远是假的; '1' == 1测试两种不同类型的对象是否相等; 他们不是.

  • user_input[index] in random_no也总是假的,你的random_no列表只包含整数,没有字符串.

如果用户要输入一个随机数,请将其转换input()为整数,并且不要打扰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
Run Code Online (Sandbox Code Playgroud)


小智 5

在将其声明为全局之前,您先给奶牛赋予一个值。您应该首先声明您的全局范围

顺便说一句,您不需要全局声明。只需删除此行即可。