python 3空字符串错误

卡尔佩什

在此代码中,我希望如果用户在问题中输入空字符串,则应弹出最后一项。但在输出中,它将空字符串添加为列表值。

our_list = []
n=int(input("how many values are there in the list?"))
for i in range(0,n):
  x=str(input("enter names of animals for the list"))
  our_list.append(x)
print(our_list)



y=str(input("enter the name of an animal "))

if y in our_list:
  our_list.remove(y)
elif y not in our_list:
  our_list.append(y)
elif len(y)==0:
  our_list.pop()

print(our_list)
胡杰

@sshashank124 是完全正确的,我会冒昧地详细说明一下。你的前两个 if 已经用尽了所有的可能性,因此“len(y)==0:”永远不会被执行。通过“if y”或“if not y”而不是“len(y) == 0”来检查 y 是否存在是一个很好的做法,因此当您获得 None 类型时,您的代码不会崩溃。

if not y:
    our_list.pop()
elif y in our_list:
    our_list.remove(y)
elif y not in our_list:
    our_list.append(y)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章