在Python中的嵌套IF中调用函数 [英] Calling function in nested IF in Python
本文介绍了在Python中的嵌套IF中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须接受用户输入的鸟名并检查bird_names列表.
我尝试了以下代码:
第一个输入:蝴蝶
输出:
I have to take the user inputs of bird names and check in the list of bird_names.
I have tried the following code:
first input: butterfly
output:
2nd try fail, please do 3rd try
在第二次尝试
输入:鹦鹉
输出:<
On 2nd try
input: parrot
output: <
1st try fail, do 2nd try
''
斜体代码不起作用.
请告诉我我的逻辑哪里错了.
提前谢谢!
我尝试过的事情:
''
The code in italics is not working.
Kindly tell me where I am wrong in my logic.
Thanks in advance!
What I have tried:
bird_names=(''crow'', ''parrot'', ''eagle'')
def bird_guess():
bird_guess1=input(''Enter the bird guess :'')
return bird_guess1
bird_guess()
if(bird_guess not in bird_names):
print(''1st try fail, do 2nd try'')
bird_guess()
if(bird_guess not in bird_names):
print(''2nd try fail, please do 3rd try'')
bird_guess()
if(bird_guess not in bird_names):
print(''Sorry, exhausted tries'')
else:
print(''corect on 3rd try'')
elif(bird_guess in bird_names):
print(''good work! correct on 2nd try'')
elif(bird_guess in bird_names):
print(''great work!, correct on 1st try itself'')
else:
print(''Not Valid'')
推荐答案
您在测试中使用的是bird_guess
函数,而不是其返回值.试试
You are usingbird_guess
function, instead of its return value in your tests. Try
bird_names=('crow', 'parrot', 'eagle')
def bird_guess():
bird_guess1=input('Enter the bird guess :')
return bird_guess1
guess = bird_guess()
if(guess not in bird_names):
print('1st try fail, do 2nd try')
guess = bird_guess()
if(guess not in bird_names):
print('2nd try fail, please do 3rd try')
guess = bird_guess()
if(guess not in bird_names):
print('Sorry, exhausted tries')
else:
print('corect on 3rd try')
else:
print('good work! correct on 2nd try')
else:
print('great work!, correct on 1st try itself')
尝试一下:
Try this:
bird_names=('crow', 'parrot', 'eagle')
def bird_guess():
bird_guess1=input('Enter the bird guess :')
return bird_guess1
def birdtest():
for count in range(1,4):
bird = bird_guess()
if(bird not in bird_names):
print('try', count, 'failed, ', end='')
if count < 3:
print('try again')
else:
print('no more guesses allowed.')
break
else:
print("correct, it is in the list")
break
但是,作为一名新程序员,您最好花时间遵循 Python教程 [
But, as a new programmer your time would be better spent following The Python Tutorial[^]
这篇关于在Python中的嵌套IF中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文