问题描述
我正在尝试在循环内编辑全局变量cows
和bulls
,但出现此错误"SyntaxError: name 'cows' is assigned to before global declaration"
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')
推荐答案
Python没有块作用域,只有函数和类引入了新的作用域.
Python has no block scoping, only functions and classes introduce a new scope.
因为这里没有功能,所以不需要使用global
语句,cows
和bulls
已经已经为全局变量.
Because you have no function here, there is no need to use a global
statement, cows
and bulls
are already globals.
您还有其他问题:
-
input()
始终返回一个字符串.
input()
returns a string, always.
索引适用于字符串(您会得到单个字符),确定要这样做吗?
Indexing works on strings (you get individual characters), are you sure you wanted that?
user_input[index] == num
始终为假; '1' == 1
测试两种不同类型的对象是否相等;他们不是.
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
也总是会为假,您的random_no
列表仅包含整数,没有字符串.
user_input[index] in random_no
is also always going to be false, your random_no
list contains only integers, no strings.
如果用户要输入一个随机数,请将input()
转换为整数,而不必理会enumerate()
:
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
这篇关于SyntaxError:在Python3.6中的全局声明之前将名称"cows"分配给了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!