我已经找到了两种分配全局变量的方法。
第一种方法为函数指定属性。
第二种方法更改全局变量名称。
我将把它实现为基于文本的冒险游戏。
哪种方法最适合我的任务?为什么?
这是代码。
# Method 1. Assigning attributes to function.
def coin():
print "You see a coin. Pick it up?"
choice = raw_input("> ")
if choice == "yes":
coin.amount = coin.amount + 1
print coin.amount
elif choice == "no":
print "No monies for you."
# Method 2. Assigning global name within function.
def coin2():
global purse
print "You see a coin. Pick it up?"
choice = raw_input("> ")
if choice == "yes":
purse = purse + 1
print purse
elif choice == "no":
print "No monies for you."
coin.amount = 0
coin()
purse = 0
coin2()
答案 0 :(得分:2)
都不是。将硬币金额作为参数传递,然后返回修改后的值。现在你根本不需要全局或函数属性。
def coin3(amount):
print "You see a coin. Pick it up?"
choice = raw_input("> ")
if choice == "yes":
amount += 1
print amount
elif choice == "no":
print "No monies for you."
return amount
x = 0
x = coin3(x)