问题
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, yourrandom_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