Evan
Evan

Reputation: 25

while loops proper nesting

I am seeking assistance on properly using the following 3 while loops:

while choice is None:  ...
while not isinstance (choice, int):  ...
while int(choice) not in range(0,1):  ...

Something like this perhaps:

while choice is None and not isinstance (choice, int) and int(choice) not in range(0,1):
    print("Invalid option!")
    choice = input("Choose key: ")

How would I properly nest this?

choice = None
choice = input("Choose key: ")

while choice is None:
    choice = input("Choose key: ")

while not isinstance (choice, int):
    print("choice is an integer and I equal 0 or 1")
    print("Also if I am None or not an int, I will loop until I meet I am")

while int(choice) not in range(0,1):
    choice = input("Choose key: ")
    choice = int(choice)

Upvotes: 0

Views: 104

Answers (5)

Vex -
Vex -

Reputation: 19

choice = None
while choice not in range(0,1):
    choice = int(input("Choose key: "))

I don't know if that's what you were trying to do

Upvotes: 0

Bernd
Bernd

Reputation: 112

If I understand corrently this is less about nesting and more about ordering, right? How about:

In [10]: choice = None

In [11]: while (
...:     not choice or
...:     not choice.isdigit() or
...:     int(choice) not in range(0,2)
...: ):
...:     print("Invalid option!")
...:     choice = input("Choose key: ")

Upvotes: 0

chris
chris

Reputation: 2063

You can condense this nicely by moving everything into one loop:

while True:
    choice = input("Choose key: ")
    if choice in ("0", "1"):
        choice = int(choice)
        break

Upvotes: 5

chepner
chepner

Reputation: 531205

input returns a str object, period. It will never return None, it will never return an int. Just (try to) convert choice to an int, then check the resulting value, breaking only when a 0 or 1 is entered.

while True:
    choice = input("Choose key: ")
    try:
        choice = int(choice)
    except ValueError:
        continue
    if choice in (0, 1):
        break

Upvotes: 3

N Chauhan
N Chauhan

Reputation: 3515

If you need an integer input...

while True:
    try:
        choice = int(input('Enter choice: '))
    except ValueError:
        print('Invalid choice')
    else:
        # add an if statement here to add another condition to test the int against before accepting input
        break
# .... do whatever next with you integer

Upvotes: 1

Related Questions