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

时间:2017-07-04 17:50:59

标签: 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')

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:0)

在将cows声明为全局之前,您可以为其提供一个值。您应首先声明全局范围

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