我正在编写一个简单的程序来创建矩阵并对它们执行某些操作。我之前用 python 2.7 编写了这个程序,并且运行良好。但是,它似乎不适用于 python 3.7。系统会提示用户输入矩阵的行和列,并输入两者的值( float )。但每当用户输入“quit”时,它都会要求用户再次输入行和列。如果有人能告诉我为什么它没有跳出 while 循环“while value != quit1:”,那将不胜感激。
还有一个 ValueError (cannot conversion string to float: 'quit')
每当我在程序后输入“quit”时,因为在输入值时该值被转换为 float 。我注释掉了 value = float(value) 行,以测试它是否会跳出 while 循环。当该行取消注释时,它会返回 ValueError
。谢谢
def main():
print("Welcome to the matrix program!")
print("Enter the number of dimensions: ")
m = int(input("Enter number of rows: "))
n = int(input("Enter number of columns: "))
matrix = []
for i in range(m):
matrix.append([])
for j in range(n):
matrix[i].append(0)
print(matrix)
value = 0
quit1 = str("quit").upper
while value != quit1:
row_loc = int(input("Enter a row location: "))
col_loc = int(input("Enter a column location: "))
value = input("Enter a value for the matrix of QUIT to stop: ")
if value != quit1:
value = float(value)
matrix[row_loc-1][col_loc-1] = value
else:
value = quit1
print(matrix)
choices = "What would you like to do? \n(1) APPLY \n(2) TRANSPOSE \n(3) PRINT \n(4) QUIT"
print(choices)
choice = int(input("Choice: "))
最佳答案
看来您的问题由两部分组成。出现 ValueError
是因为 value = float("QUIT")
正在 if 语句中运行。然而,它首先将其放入 if 语句的原因是 quit1
在 upper
函数调用中缺少 ()
,并且您可能应该标准化输入。像这样的东西应该有效:
def main():
print("Welcome to the matrix program!")
print("Enter the number of dimensions: ")
m = int(input("Enter number of rows: "))
n = int(input("Enter number of columns: "))
matrix = []
for i in range(m):
matrix.append([])
for j in range(n):
matrix[i].append(0)
print(matrix)
value = 0
quit1 = str("quit").upper()
while value != quit1:
row_loc = int(input("Enter a row location: "))
col_loc = int(input("Enter a column location: "))
value = input("Enter a value for the matrix of QUIT to stop: ")
if value.upper() != quit1:
value = float(value)
matrix[row_loc-1][col_loc-1] = value
else:
value = quit1
print(matrix)
choices = "What would you like to do? \n(1) APPLY \n(2) TRANSPOSE \n(3) PRINT \n(4) QUIT"
print(choices)
choice = int(input("Choice: "))
您还可以通过修改 while
语句中的相同内容并删除 else
来进一步简化逻辑
关于python - 输入矩阵值后无法跳出 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53114000/