为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

摇曳的蔷薇 2021-08-05 16:29:39
我正在编写一个简单的程序来创建矩阵并对它们执行某些操作。我之前在 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: "))
查看完整描述

1 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

所以看起来你的问题由两部分组成。该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


查看完整回答
反对 回复 2021-08-05
  • 1 回答
  • 0 关注
  • 211 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号