python - 验证字符串输入并将其连接到列表
问题描述
studentNumber = len(age) - 1
age[studentNumber] = 0
house[studentNumber] = ''
reactionTime[studentNumber] = 0
while True:
try:
age[studentNumber] = int(input("What is the age of the student: "))
except ValueError:
age[studentNumber] = int(input("What is the age of the student: "))
if age[studentNumber] in range(12, 17):
break
house[studentNumber] = input("Which house is the student in (Saturn/Mars): ").lower()
while house[studentNumber] not in {"saturn", "mars"}:
house[studentNumber] = input("Which house is the student in (Saturn/Mars): ").lower()
age.append(0)
house.append('')
reactionTime.append(0)
print(age + " " + house + " " + reactionTime)
我正在尝试将输入验证为“saturn”或“mars”的字符串,但是TypeError: can only concatenate list (not "str") to list
当我尝试将其添加到我的列表时收到错误消息
命令行:
What would you like to do:
1. Enter new information
2. House-based statsitics
3. Specific Criteria statistics
Enter 1 2 or 3: 1
What is the age of the student: 12
Which house is the student in (Saturn/Mars): saturn
Traceback (most recent call last):
File "python", line 46, in <module>
File "python", line 32, in newInfo
TypeError: can only concatenate list (not "str") to list
解决方案
age
,house
和reactionTime
是列表,不能与字符串连接。
您应该压缩三个列表并遍历项目以进行输出。
改变:
print(age + " " + house + " " + reactionTime)
到:
for a, h, r in zip(age, house, reactionTime):
print(a, h, r)