使用基本的计算器程序制作了我的第一个学校课程,但添加了一个变量,不确定它是全局的还是本地的。它计算正常,但不会将'tribble'作为新整数返回。
tribble = 1
def buy():
x=int(raw_input("How many?"))
return (tribble + x);
def sell():
x=int(raw_input("How many?"))
return (tribble - x);
def breed():
x=int(raw_input("Multiply them by 2"))
return (tribble * x);
def cull():
x=int(raw_input("Kill half your Tribbles"))
return (tribble / x);
print "1: Buy"
print "2: Sell"
print "3: Breed"
print "4: Cull"
print "0: QUIT"
while True:
CHOICE = int(raw_input("What will you do with your Tribbles?"))
if CHOICE == 1:
print "Buying Tribbles"
print buy()
print "You have" + str(tribble) + "Tribbles."
elif CHOICE == 2:
print sell()
print 'Selling Tribbles'
print "You have" + str(tribble) + "Tribbles."
elif CHOICE == 3:
print 'Breeding Tribbles, good luck.'
print breed()
print "You have" + str(tribble) + "Tribbles."
elif CHOICE == 4:
print "You're killing them!!"
print cull()
print "You have" + str(tribble) + "Tribbles."
elif CHOICE == 0:
exit()
答案 0 :(得分:1)
您是否正在尝试更新tribble的值?
然后,您应该使用:tribble = buy()
更新变量而不是print buy()通过这种方式,您知道该值已更新为函数buy()的结果。
对其他功能也一样。
希望它有所帮助。
答案 1 :(得分:1)
您永远不会将操作结果重新分配给tribble
。我还建议您尽可能避免使用全局变量。例如,我会将您的cull
函数重写为以下内容:
def cull(number_of_tribbles):
x=int(raw_input("Kill half your Tribbles"))
return number_of_tribbles / x # No need for the parenthesis or the semicolon
# To use
tribble = cull(tribble)
# No need for explicit str conversion in print
print "You have", tribble, "Tribbles."
作为旁注,很奇怪你的消息是"杀掉你的一半Tribbles"但是你要求用户输入。您应该硬编码到return tribbles / 2
或将消息更改为用户;同样适用于breed
。
答案 2 :(得分:1)
您不会在函数中更新 tribbles 的值,因此每次调用函数时,tribbles都会被视为1,它是原始值。例如,不是返回tribbles * 2,而是执行tribbles * = 2然后返回tribbles。
答案 3 :(得分:1)
是的' tribble'在while循环中没有更新。因为每次函数返回更新的tribble时,你只需要打印它。
您可能希望以这种方式更新tribble:
...
...
tribble= buy()
print tribble
...
....
答案 4 :(得分:0)
你也可以这样做:
tribble = 1
def buy():
global tribble
x = int(raw_input("How many?"))
tribble = tribble + x;
...
print "1: Buy"
print "2: Sell"
print "3: Breed"
print "4: Cull"
print "0: QUIT"
while True:
CHOICE = int(raw_input("What will you do with your Tribbles?"))
if CHOICE == 1:
print "Buying Tribbles"
print buy()
print "You have " + str(tribble) + " Tribbles."
...
elif CHOICE == 0:
exit()
应以类似的方式更改所有其他方法。
但是,建议避免使用全局变量。