1

I found the following code example online, which exits a while True loop by using a specific integer:

while True:
i = int(input('Please enter an integer (or 0 to exit):\n'))
if i == 0:
    print("Exiting the Program")
    break
print(f'{i} square is {i ** 2}')

I would like to know how to exit the loop using a str input (like "exit"), instead of a specific int (0 in this example). I messed around by creating one input per type:

while True:
    i_str = input('Please enter an integer ( or "exit" to exit): ')
    if i_str == "exit":
        print("Exiting the Program")
        break
    i_int = int(input('Please enter an integer (or "exit" to exit): '))
    print(f'{i_int} square is {i_int ** 2}')

...but it prints out smth every other try, and throws a ValueError when computing 'exit' on the wrong try.

I basically can't figure out how to implement this properly, neither am I sure that I should even be using two different input formats to solve this.

3 Answers 3

2

You can use if-else and convert to int if it is not exit as:

while True:
    i_str = input('Please enter an integer ( or "exit" to exit): ')
    if i_str == "exit":
        print("Exiting the Program")
        break
    else:
        i_int = int(i_str)
        print(f'{i_int} square is {i_int ** 2}')
Sign up to request clarification or add additional context in comments.

2 Comments

Glad to be of help, @Effojire, please consider accepting the answer if it resolved your problem.
Upvoted and accepted. Upvote won't show as I'm a newbie here. Thanks for letting me know abt the accepting option, had no idea there was such a thing.
0

you can just cast it to a string first and validate it then cast it to int and then put that all in a try-catch to catch any exceptions you can use the example below

while True:
try:
    i = str(input('Please enter an integer (or 0 to exit):\n'))
    if "exit" in i:
        print("Exiting the Program")
        break
    else:
        i = int(i)
    if i == 0:
        print("Exiting the Program")
        break
    print(f'{i} square is {i ** 2}')
except:
    print("Exiting the Program")

Comments

0

You can just use try-except, program will raise an exception if it is unable to convert the entered number to integer.

while True:
    try:
        i = int(input('Please enter an integer ( or "exit" to exit): '))
        print(f'{i} square is {i ** 2}')
    except:
        print("Exiting the Program")
        break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.