代码的编译顺序-Python
提醒:初学者的问题 问题是: 两个玩家被赋予相同的字符串,例如:香蕉 对于每个以元音开头的子串,玩家1可以得到1分,否则玩家2可以重复1分 最后:玩家的1分是9分,玩家的2分是12分代码的编译顺序-Python,python,memory-management,compilation,Python,Memory Management,Compilation,提醒:初学者的问题 问题是: 两个玩家被赋予相同的字符串,例如:香蕉 对于每个以元音开头的子串,玩家1可以得到1分,否则玩家2可以重复1分 最后:玩家的1分是9分,玩家的2分是12分 vowels = "AEIOU" player_1 = 0 player_2 = 0 def winner(user_string): for index, item in enumerate(user_string): if item in vowels: pla
vowels = "AEIOU"
player_1 = 0
player_2 = 0
def winner(user_string):
for index, item in enumerate(user_string):
if item in vowels:
player_1 += len(user_string[index:])
else:
player_2 += len(user_string[index:])
if player_1 > player_2:
print("Ply 1 won")
else:
print("Ply 2 won")
winner("BANANA")
但它抛出了一个错误,如下所示
有人能帮我解决这个问题吗。我需要在这里学习编译的顺序吗?谢谢这是一个关于变量范围的问题,这两个变量都是:player_1和player_2。检查 因此,正确的方法是将变量的初始化移动到函数或添加:
global player_1
global player_2
在函数体的开头
我的偏好是第一种方法,因此正确的功能是:
def winner(user_string):
player_1 = player_2 = 0
for index, item in enumerate(user_string):
if item in vowels:
player_1 += len(user_string[index:])
else:
player_2 += len(user_string[index:])
if player_1 > player_2:
print("Ply 1 won")
else:
print("Ply 2 won")
你真的应该把错误复制/粘贴到你的问题中,而不是用图片。这也会有用的谢谢你对@EdChum的支持