我目前正在尝试用Eric编写的Python速成课程来教自己Python,而且我似乎在使用if测试测试空列表的节选5-9方面遇到了困难。
这里有个问题:
5-9.没有用户:向hello_admin.py添加一个if测试,以确保用户列表不是空的。
如果列表为空,请打印消息--我们需要找到一些用户!
·从列表中删除所有用户名,并确保正确的消息被打印出来。
这里是我来自hello_admin.py:的代码
usernames = ['admin', 'user_1', 'user_2', 'user_3', 'user_4']
for username in usernames:
if username is 'admin':
print("Hello admin, would you like to see a status report?")
else:
print("Hello " + username + ", thank you for logging in again.")现在这里是我的5-9代码,它没有输出任何内容:
usernames = []
for username in usernames:
if username is 'admin':
print("Hello admin, would you like to see a status report?")
else:
print("Hello " + username + ", thank you for logging in again.")
if usernames:
print("Hello " + username + ", thank you for logging in again.")
else:
print("We need to find some users!")是否有人对我的代码没有输出有任何反馈:“我们需要找到一些用户!”谢谢您抽时间见我。:)
发布于 2016-08-30 23:18:52
它没有输出任何东西,因为您的if和else块位于在usernames上迭代的for循环中。因为usernames是一个空列表,所以它不会迭代任何东西,因此不会到达任何这些条件块。
你可能会想要把:
usernames = []
for username in usernames:
if username is 'admin':
print("Hello admin, would you like to see a status report?")
else:
print("Hello " + username + ", thank you for logging in again.")
if usernames:
print("Hello " + username + ", thank you for logging in again.")
else:
print("We need to find some users!")不过,这将在usernames列表中打印两次最后一个用户名。
发布于 2016-08-30 23:36:27
第一个if- for应该在for循环中。第二个(如果是其他的话)应该出现在外面。
usernames = []
for username in usernames:
if username is 'admin':
print("Hey admin")
else:
print("Hello " + username + ", thanks!")
if usernames:
print("Hello " + username + ", thanks again.")
else:
print("Find some users!")https://stackoverflow.com/questions/39238469
复制相似问题