【发布时间】:2018-08-14 19:55:00
【问题描述】:
我的学生正在为课堂制作石头、纸、剪刀模拟。一组有一个错误,他们的一个函数不会返回任何东西。我已经检查过它是否所有分支都有返回语句,它们确实有。我也试过可视化工具,但功能停止了,我不知道为什么。
def Win_Loss(my_history, their_history):
if len(my_history) > 1 and len(their_history) > 1:
if (their_history[-1] == 's' and my_history[-1] == 'r'):
return 'p'
elif len(my_history) > 1 and len(their_history) > 1:
if (their_history[-1] == 'r' and my_history[-1] == 'p'):
return 's'
elif len(my_history) > 1 and len(their_history) > 1:
if (their_history[-1] == 'p' and my_history[-1] == 's'):
return 'r'
elif len(my_history) > 1 and len(their_history) > 1:
if (their_history[-1] == 's' and my_history[-1] == 'p'):
return 'r'
elif len(my_history) > 1 and len(their_history) > 1:
if (their_history[-1] == 'r' and my_history[-1] == 's'):
return 'p'
elif len(my_history) > 1 and len(their_history) > 1:
if (their_history[-1] == 'p' and my_history[-1] == 'r'):
return 's'
elif len(my_history) > 1 and len(their_history) > 1:
if (their_history[-1] == 's' and my_history[-1] == 's'):
return 'r'
elif len(my_history) > 1 and len(their_history) > 1:
if (their_history[-1] == 'r' and my_history[-1] == 'r'):
return 'p'
elif len(my_history) > 1 and len(their_history) > 1:
if (their_history[-1] == 'p' and my_history[-1] == 'p'):
return 's'
else:
return "p"
print(Win_Loss(['s','p','p'],['s','p','p']))
这应该是打印's',但它打印的是None。
【问题讨论】:
-
所以,所有的分支肯定没有有
return声明。所有elif分支都有一个if语句。如果其中任何一个ifs 不正确,该函数将返回None。 -
所有条件都一样:
elif len(my_history) > 1 and len(their_history) > 1:.....尝试删除每个elif -
另外,你所有的外部条件都是一样的:
len(my_history) > 1 and len(their_history) > 1所以只有第一个if块会执行... -
试着用简单的英语表达你想要的逻辑。
-
鉴于这个问题(和您的个人资料),听起来您也可以在这个社区中找到一些用途:Computer Science Educators。
标签: python python-3.x return