【问题标题】:Python: 2-input-variable loop that operates until the user tells it to stop?Python:在用户告诉它停止之前一直运行的 2 输入变量循环?
【发布时间】:2018-11-03 17:19:46
【问题描述】:

循环从两个变量开始,我们称它们为 X 和 Y,都为 0。系统会提示用户输入要添加到 X 的数字,然后输入要添加到 Y 的数字。循环重复自身,让用户继续添加到这两个变量,直到用户希望它停止 - 我猜他们可以输入“添加”作为输入之一?

如果用户输入的不是数字,我还需要它再次要求输入,但前提是它也不是“添加”。如果是“添加”,则循环结束,并显示两个总数。如果输入是浮点数或整数,则循环继续。否则,它会再次提示输入。这适用于两个输入中的每一个。

我可以分别做这些事情中的任何一个,但我无法将这两个要求合并到同一个循环结构中。

到目前为止,我的代码基本上是这样的:

while (x != 'add') and (y != 'add'):
    # ask input for x
    if x != 'add':
        #ask input for y
        if (x != 'add') and (y != 'add'):
            # operations that add inputs to running variables
        else:
            pass
    else:
        pass
# print both variable totals here

我的第一个问题是用户应该输入数字,而代码也在检查字符串。我将如何解决这个问题?我的第二个问题是,如果输入不是数字或“添加”,我不确定如何重新提示每个输入。

【问题讨论】:

    标签: python


    【解决方案1】:

    欢迎来到 SO!

    您的想法通常是正确的,以下是您可以如何将其转换为代码的方法。

    x_total = 0
    y_total = 0
    
    while True:
        first_input = input('Enter the next value of x: ')
        if first_input == 'add':
            break
        x_total += float(first_input)
    
        second_input = input('Enter the next value of y: ')
        if second_input == 'add':
            break
        y_total += float(second_input)
    
    print('x = ', x_total)
    print('y = ', y_total)
    

    请注意,在 Python 中,我们可以通过将类型 float 称为 number = float(number_string ) 来将字符串 number_string = '1239' 转换为浮点数。对于整数,这同样适用于 intdocumentation 包含有用的食谱和使用示例,通常是我不确定自己需要什么时开始的地方。

    既然您提到您是 Python 新手,那么我要提一下,与其他语言相比,Python 中存在强大的习语。 Zen of Python 是对这个想法的一种介绍。询问“这是 Pythonic 吗?”通常很有用。当你第一次开始时,因为可能有既定的方法来做你正在做的任何事情,这些方法会更清晰,更不容易出错,并且可能运行得更快。

    slide deck 很好地介绍了一些 Pythonisms,它是为 Python 2.x 量身定制的,因此一些语法有所不同,但这些想法在 3.x 中同样适用。

    满足您原始请求的更 Pythonic(尽管对于新 Python 用户可能不太容易理解的方式)是使用任何意外值或转义字符来退出添加过程。

    x_total = 0
    y_total = 0
    
    while True:
    
        try:
    
            first_input = input('Enter the next value of x: ')
            x_total += float(first_input)
    
            second_input = input('Enter the next value of y: ')
            y_total += float(second_input)
        except (ValueError, EOFError):
            break
        except KeyboardInterrupt:
            print()
            break
    
    print('x =', x_total)
    print('y =', y_total)
    

    现在您的程序的用户可以键入任何非浮点值来退出,甚至可以使用键中断(例如 ctrl + Z 或 ctrl + C)。我在PowerShell中运行它给你一些使用示例:

    退出,一个常见的成语:

    Enter the next value of x: 1
    Enter the next value of y: 2
    Enter the next value of x: 3
    Enter the next value of y: exit
    x = 4.0
    y = 2.0
    

    您的原始案例,添加:

    Enter the next value of x: 1
    Enter the next value of y: 2
    Enter the next value of x: 3
    Enter the next value of y: add
    x = 4.0
    y = 2.0
    

    使用 ctrl + Z:

    Enter the next value of x: 1
    Enter the next value of y: 2
    Enter the next value of x: 3
    Enter the next value of y: ^Z
    x = 4.0
    y = 2.0
    

    使用 ctrl + C:

    Enter the next value of x: 1
    Enter the next value of y: 2
    Enter the next value of x: 3
    Enter the next value of y:
    x = 4.0
    y = 2.0
    

    【讨论】:

      【解决方案2】:

      你可以应用一个“无限”循环,并用一个字符串输入来打破它,例如“add”或任何其他,或者按 Enter:

      while True:
               try:
                  x=float(input("give x or enter to stop: "))
                  X+=x
                  y=float(input("give y or enter to stop: "))
                  Y+=y
               except ValueError:
                   print(X,Y)
                   break
      

      【讨论】:

        【解决方案3】:

        我知道您要求在循环之后输出结果,但我决定在 Python 中断循环之前执行此操作。这是代码:

        print("If you want to end the program input 'add'.")
        x_value = 0
        y_value = 0
        while True:
            x_input = str(input("Value of X:"))
            if x_input != 'add':
                y_input = str(input("Value of Y:"))
                if (x_input != 'add') and (y_input != 'add'):
                    x_value += int(x_input)
                    y_value += int(y_input)
                elif y_input == "add":
                    x_value += int(x_input)
                    print("Value of X:", str(x_value))
                    print("Value of Y:", str(y_value))
                    break
            elif x_input == "add":
               print("Value of X:", str(x_value))
               print("Value of Y:", str(y_value))
               break
        

        希望对你有帮助:)

        【讨论】:

          猜你喜欢
          • 2018-07-18
          • 1970-01-01
          • 2013-08-25
          • 1970-01-01
          • 2019-09-30
          • 1970-01-01
          • 2014-08-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多