Home > Blockchain >  How do I get this while loop to update my initial input so I can apply the if statements to new valu
How do I get this while loop to update my initial input so I can apply the if statements to new valu

Time:10-03

I would like to input a new number each time which will compare the integer again the current variable but also save on top of the original variable after so I can input another number to compare again.

I'm not sure why I cant update the current variable with the one I input. How would I acheive this.

My current code is:

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

If the pgrogram worked correctly it would look something like this:

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

Each entry should replace the variable the next entry will be compared against. Any help would be appreciated. Thanks!

CodePudding user response:

You have to update the x variable, not the h one. Also, I fixed other issues in the code (see comments)

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

This gives the output you expect.

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

CodePudding user response:

You have to update it outside of the if loop. So instead of this

elif h != 0:
        h = x

you can do it outside of loop like h = x but without the if statement.

  • Related