gpt4 book ai didi

Python 2.7.5,列表基础,正确显示列表输入

转载 作者:太空宇宙 更新时间:2023-11-04 10:42:28 24 4
gpt4 key购买 nike

刚开始使用 python 2.7.5 尝试数组。我的目标是要求用户输入并将输入存储在多个数组中。

到目前为止,就用输入存储多个数组而言,这就是我所拥有的。尝试在末尾打印输入时遇到错误。

这是我目前的代码。

# want user to enter a list of employee names, error occurs when trying to recall user entry

emp_name = [0]
emp_name = raw_input("please enter employee name")

while emp_name !="neg":
emp_name = raw_input("please enter employee name,enter neg to exit")

print "employee 2 is:", emp_name[1] #I want the 2nd name entered to appear

最佳答案

然后你会想要:

  1. 更改变量的名称,使列表与输入的名称不同。
  2. 将您获得的每个名称附加到列表中。

这应该是你想要的:

employees = []
name = raw_input("Please enter an employee name: ")

while name != "neg":
# Append the previous name.
employees.append(name)
# Get a new name.
name = raw_input("Please enter an employee name or 'neg' to exit: ")

# You need a try/except here in case there is no second employee.
# This can happen if the user types in "neg" to begin with or only 1 name.
try:
print "Employee 2 is: ", employees[1]
except IndexError:
print None

另外,我稍微更改了您的输入提示,使它们更清晰、更人性化。

下面是一个正在运行的脚本示例:

Please enter an employee name: Bob
Please enter an employee name or 'neg' to exit: Joe
Please enter an employee name or 'neg' to exit: neg
Employee 2 is: Joe

这是一个没有第二名员工的人:

Please enter an employee name: Joe
Please enter an employee name or 'neg' to exit: neg
Employee 2 is: None

关于Python 2.7.5,列表基础,正确显示列表输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19710331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com