【发布时间】:2021-03-18 15:55:33
【问题描述】:
我有这段代码可以打印输入值的矩阵。现在值是一一输入的,但我想将其转换为以空格分隔的输入。试了很多方法,都不行,怎么办?
print("This program prints a matrix in aligned rows and columns")
while True:
try:
nbrRows = int(input("What is the number of rows: "))
if nbrRows <= 0:
print("The number of rows cannot be negative or zero")
continue
else:
break
except:
print("You did not enter an integer value")
continue
while True:
try:
nbrCols = int(input("What is the number of columns: "))
if nbrCols <= 0:
print("The number of columns cannot be negative or zero")
continue
else:
break
except:
print("You did not enter an integer value")
continue
print("Please enter the elements one by one at the prompts")
nbrElements = nbrRows * nbrCols
count = 0
outputString = ""
for i in range(nbrRows):
for j in range(nbrCols):
while True:
try:
elem = int(input("? "))
break
except:
print("Please enter an integer value")
outputString += str(elem) + "\t"
outputString += "\n"
print(outputString)
感谢您的帮助。
【问题讨论】:
-
看起来您的代码运行良好。它产生分隔的输出空间。
标签: python python-3.x loops matrix