Python 函数和条件语句
我想知道是否有可能将条件语句放在函数中,根据执行的条件,它将移到另一个函数中 例如:Python 函数和条件语句,python,Python,我想知道是否有可能将条件语句放在函数中,根据执行的条件,它将移到另一个函数中 例如: def main(): animal = input("Enter an animal name: ") if animal == cow: cow() else: other() def cow(): print("You entered cow") def other(): print("You didn't enter cow")
def main():
animal = input("Enter an animal name: ")
if animal == cow:
cow()
else:
other()
def cow():
print("You entered cow")
def other():
print("You didn't enter cow")
main()
对。你的例子几乎就是你要怎么做。但是,代码中有一个问题,那就是
if
条件。您需要检查animal
返回的值是否是字符串,而不是当前正在执行的函数或变量
您可以将其更改为:
如果animal==“cow”:
是,您可以在函数内部实现一个控制结构,该结构可以确定使用哪个函数。我会将您的代码更改为:
def main():
animal = input("Enter an animal name: ")
if (animal == 'cow'):
cow()
else:
other()
def cow():
print("You entered cow")
def other():
print("You didn't enter cow")
main()
这将允许将输入与cow(字符串到字符串比较)进行正确比较。是的,您的代码几乎完美无瑕。唯一的问题是,在进行比较时,需要在cow周围加引号,以便python知道您正在尝试与字符串“cow”进行比较,而不是与一些未定义的变量cow进行比较。此外,如果希望使动物变量不区分大小写,可以对其使用.lower()方法。以下代码正常工作:
def main():
animal = input("Enter an animal name: ")
if animal.lower() == "cow":
cow()
else:
other()
def cow():
print("You entered cow")
def other():
print("You didn't enter cow")
main()
试试这个,它要短得多:
def main():
animal = input("Enter an animal name: ")
cow() if animal == 'cow' else other()
def cow():
print("You entered cow")
def other():
print("You didn't enter cow")
main()
产出:
Enter an animal name: cow
You entered cow
Enter an animal name: snake
You didn't enter cow
字符串周围需要引号:
如果animal==“cow”:
是的,这是可能的。@AGNGazer:不可能。但那会很好。