【发布时间】:2019-08-14 22:23:18
【问题描述】:
我正在尝试编写一个程序,该程序在一个while循环中修改给定用户输入的矩阵,并继续接收输入,直到用户输入一个字符串。
这基本上是我的最终目标:
for a matrix i=[[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]
user input:
2
3
3
3
t
for user inputs, the first integer specifies the row, and the next one following it specifies the column.
expected output: i=[[0,0,0,0,0], [0,0,1,0,0], [0,0,1,0,0], [0,0,0,0,0]]
我尝试了几种方法,但仍然没有得到我想要的:
while True:
x=input()
y=input()
if type(y)==int and type(x)==int:
i[x][y]=1
else:
break
print(i)
This outputs original configuartion [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]
我也试过这个:
while True:
x=input()
y=int(input())
i[x][y]=1
if x=="t":
break
print(i)
outputs TypeError: list indices must be integers or slices, not str
【问题讨论】:
-
if type(y)==int将总是失败,因为用户输入总是一个字符串。您需要try/except来查看输入字符串是否可以转换 -
带有
try/except这个评论意义不大,但你也应该使用isinstance来检查类型
标签: python python-3.x loops input while-loop