(Python) Return 来自 if 语句的值未分配给 if 语句外的变量
(Python) Return value from if-statement does not get assigned to variable outside the if-statement
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")
食肉动物
食肉动物
None
这是否意味着 eating_style
是不可变的?如果是这样,我应该如何更改函数以将不同的值分配给 eating_style
?
您的参数作为值传递。分配新值不会对其产生任何影响。你可以 return 像这样的新字符串。
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
查看此 link 了解更多信息。
How do I pass a variable by reference?
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")
食肉动物
食肉动物
None
这是否意味着 eating_style
是不可变的?如果是这样,我应该如何更改函数以将不同的值分配给 eating_style
?
您的参数作为值传递。分配新值不会对其产生任何影响。你可以 return 像这样的新字符串。
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
查看此 link 了解更多信息。 How do I pass a variable by reference?