def my_diet(event, style):
if event == 1:
choice = raw_input("""What type of animal are you?
A) Carnivore
B) Herbivore
C) Omnivore
""")
if choice == "A":
style = "Carnivore"
print style
elif choice == "B":
style = "Herbivore"
elif choice == "C":
style = "Omnivore"
else:
style = "not-sure-yet"
print style
else:
pass
return style
print style
eating_style = None
my_diet(1, eating_style)
print eating_style
控制台上印刷的是:(假设choice
=“A”)
Carnivore
Carnivore
无
这是否意味着eating_style
是不可变的?如果是这样,我应该如何更改函数以将不同的值分配给eating_style
?
答案 0 :(得分:1)
您的参数作为值传递。分配新值不会对其产生任何影响。你可以像这样返回一个新的字符串。
def my_diet(event):
if event == 1:
choice = raw_input("""What type of animal are you?
A) Carnivore
B) Herbivore
C) Omnivore
""")
style = ""
if choice == "A":
style = "Carnivore"
elif choice == "B":
style = "Herbivore"
elif choice == "C":
style = "Omnivore"
else:
style = "not-sure-yet"
else:
pass
return style
eating_style = my_diet(1)
print eating_style
查看此链接以获取更多信息。 How do I pass a variable by reference?