How to properly nest a for loop into a while loop in Python

Viewed 54

So I am learning python and there is something that bothers me. For the chunk of sample code below:

print("Test")

while True:
    print("statement0")

    x = input()
    print(x)

    if x == 1:
        print("statement1")
        y += input()
        print(y)

    elif x == 2:
        print("statement2")
        y += input()
        print(y)
    elif x == 3:
        print("statement3")
        y += input()
        print(y)
    elif x == 4:
        print("statement4")
        break

The if statements don't seem to be able to execute. After the value of x is printed it will loop back to statement0.

2 Answers

While taking the input, use x = int(input())

And, also y is not defined in this case, before doing something like y+=int(input()), you have to declare y above like y = 0

Thank you!

You have to first specify what will be the data type of the variable x.

  • Now as you are equating x to integers, you need to add int before the input() function.
  • Also, you have not initialized the variable y before, so python will throw an error. Define y beforehand with any integer value.
  • And try to keep the expressions inside parenthesis as it helps in easier understanding.

So, your final code becomes:

print("Test")

while True:
    print("statement0")

    x = int(input())
    print(x)

    y = 0  # initialize y with any value 

    if (x == 1):  # edit
        print("statement1")
        y += int(input())
        print(y)

    elif (x == 2):  # edit
        print("statement2")
        y += int(input())
        print(y)
    elif (x == 3):  # edit
        print("statement3")
        y += int(input())
        print(y)
    elif (x == 4):  # edit
        print("statement4")
        break
Related