Python3.6中的语法错误:在全局声明之前分配名称“cows”。

12
我试图在循环内编辑全局变量 cows 和 bulls ,但出现错误"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')
2个回答

25

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

因为这里没有函数,所以不需要使用global语句,cowsbulls已经是全局变量了。

你还有其他问题:

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

  • 对字符串进行索引(会得到单个字符),您确定您想要那样做吗?

  • user_input[index] == num始终为false;'1' == 1测试两种不同类型的对象是否相等;它们不相等。

  • user_input[index] in random_no也始终为false,您的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

4

在将它声明为全局变量之前,您需要为奶牛赋值。您应该先声明全局作用域。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接