繁体   English   中英

我如何获得这个 while 循环来更新我的初始输入,以便我可以将 if 语句应用于 python 中的新值

[英]How do I get this while loop to update my initial input so I can apply the if statements to new values in python

我想每次输入一个新数字,将 integer 再次与当前变量进行比较,但也保存在原始变量之上,这样我就可以输入另一个数字再次进行比较。

我不确定为什么我不能用我输入的变量更新当前变量。 我将如何实现这一目标。

我当前的代码是:

print("give the first number: ", end = "")
g = input()
x = int(g)
finished = False
while not finished:
    print("enter the next number: ", end = "")
    k = input()
    h = int(k)
    if h == x and h != 0:
        print("same")
    elif h > x and h != 0:
        print("up")
    elif h < x and h != 0:
        print("Down")
    elif h != 0:
        h = x
    else:
        h == 0
        finished = True

如果程序正常工作,它将看起来像这样:

Enter the first number: 9
Enter the next number (0 to finish): 9
Same
Enter the next number (0 to finish): 8
Down
Enter the next number (0 to finish): 5
Down
Enter the next number (0 to finish): 10
Up
Enter the next number (0 to finish): 10
Same
Enter the next number (0 to finish): 0

每个条目都应替换下一个条目将与之进行比较的变量。 任何帮助,将不胜感激。 谢谢!

您必须更新x变量,而不是h变量。 另外,我修复了代码中的其他问题(见评论)

print("give the first number: ", end = "")
g = input()
x = int(g)
finished = False
while not finished:
    print("enter the next number: ", end = "")
    k = input()
    h = int(k)
    if h == 0:
        # Priority to the finish condition
        finished = True
    elif h == x:
        # No need to check that h != 0 because it's in the elsif
        print("same")
    elif h > x:
        print("up")
    elif h < x:
        print("Down")
        
    # Update the x variable, regardless of conditions. 
    x = h

这给出了您期望的 output。

give the first number: 9
enter the next number: 9
same
enter the next number: 8
Down
enter the next number: 5
Down
enter the next number: 10
up
enter the next number: 10
same
enter the next number: 0

您必须在 if 语句之外更新它。 所以而不是这个

elif h != 0:
        h = x

您可以像h = x一样在循环之外执行此操作,但没有 if 语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM