如何在单行中获取多个输入

时间:2019-05-05 16:42:43

标签: python-3.x

我希望用户输入一个数字。然后将某些值添加到列表中,该列表的长度将等于先前输入的数字。

players=int(input("Enter players:"))  
"""First input i.e. length of list"""
home = [int(home) for players in input("Enter home team runs: ").split()]  """Values to be captured on the list"""

Enter players: 3 

Enter home team runs: 10 20 60

我收到错误消息:

  

NameError:未定义名称“家”

2 个答案:

答案 0 :(得分:0)

正如错误所述,您需要在使用home之前定义它,因此错误NameError: name 'home' is not defined
另外,您的声明players in input("Enter home team runs: ").split()没有任何意义。您在此处覆盖players变量,循环变量也为players,但是您引用的是home

一种更好的方法是

#Take players as input
players=int(input("Enter players:"))

#Take runs as input
runs = input("Enter home team runs: ")

#Make home list via list-comprehension
home = [int(run) for run in runs.split()]
print(home)

输出将为

Enter players:3
Enter home team runs: 10 20 60
[10, 20, 60]

答案 1 :(得分:0)

=