我正在编写一个简单的程序来创建矩阵并对其执行某些操作。我以前用python 2.7编写了该程序,并且运行良好。但是,它似乎不适用于python 3.7。提示用户输入矩阵的行和列,输入两者的值(浮点数)。但是,只要用户输入“退出”,它就会再次要求用户输入行和列。如果有人能告诉我为什么它不退出while循环“ while value!= quit1:”,那将不胜感激。
There also is a ValueError (cannot convert 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: "))
答案 0 :(得分:0)
因此,看来您的问题由两部分组成。之所以出现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