输入矩阵值后无法跳出 while 循环

我正在编写一个简单的程序来创建矩阵并对它们执行某些操作。我之前在 python 2.7 中编写了这个程序,它运行良好。但是,它似乎不适用于 python 3.7。提示用户输入矩阵的行和列,输入两者的值(浮点数)。但是每当用户输入“quit”时,它都会要求用户再次输入行和列。如果有人能告诉我为什么它没有跳出 while 循环“while value != quit1:”,那将不胜感激。


There also is a ValueError (cannot convert string to float: 'quit')


每当我在程序后键入“退出”时,因为在键入值时该值被转换为浮点数。我注释掉了 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: "))


摇曳的蔷薇
浏览 212回答 1
1回答

慕标琳琳

所以看起来你的问题由两部分组成。该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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python