why the input process cannot go back after else in python

Viewed 49

I have 2 inputs for my app, a and b. I want to show the inputs if my initial variable is not 0. Here is my code:

import random
init = 100
while init > 0:
    x = random.randint(0,24)
    a = int(input("input value a:"))
    if a < 25:
        b = int(input("input value b"))
        if b <= init:
            init -= b
        else:
            print("b should smaller than init")
    else:
        print("a should between 0 and 24")

When I run and put a value for a more than 25, I got the else a < 25, and redirect again to input value a again until it is less than 25. When I put value b more than init, the output from else b <= init was printed but I was not redirected to input b again, instead to input value a after while. How do I redirect to the part where I input b?

1 Answers

The reason that b will not be redirected again if it is greater than init is that it's value is removed from init, so init > 0 becomes false.

I would recommend trying this:

import random
init = 100
a = 25
b = 101
while init > 0:
  x = random.randint(0,24)
  a = int(input("input value a:"))
  if a < 25:
    b = init + 1
    while b > init:
        int(input("input value b"))
        if b > init:
           print("b should smaller than init") 
  else:
    print("a should between 0 and 24")

Basically what this does is it sets b to be greater than init so the while b > init loop activates, and it keeps prompting the user with print("b should smaller than init") until they enter a value of b less than init.

Update

Here is the code to get out of the while loop, as OP asked in the comments:

import random
init = 100
while (a > 24 or a < 0) and b < init:
  x = random.randint(0,24)
  a = int(input("input value a:"))
  if a < 25 and a > 0:
    b = init + 1
    while b > init:
        int(input("input value b"))
        if b > init:
           print("b should smaller than init") 
  else:
    print("a should between 0 and 24")
Related