Python: How to determine if a String can be converted to an integer with no issues

Question:

I am writing a program that has multiple functions to execute, and the user selects which one runs by inputting a number. I also want the user to be able to let the user cancel the request by typing "cancel".

Right now this is my code:

func = input("Requested Operation: ")
if func == 'Cancel' or func == 'cancel':
     break
elif func == '' or func == ' ' or func == '0':
     func = 0
elif type(int(func)) is int:
     func = int(func)
else:
     fail = True

Context: Function 0 displays a list of the available items to choose from, so I want whitespace or 0 to work as displaying the project list. If the user types "Cancel" or "cancel" it will end the program.

The problem I am having is line 6 (the 2nd elif). My goal is to set the fail variable to True if the user inputs a string that isn’t a cancel command, so the code breaks right there and starts over. The problem is, how do I preemptively check if a string can be converted to an integer in the first place? My current iteration returns the error invalid literal for int() with base 10: 'asdg' (asdg being the random nonsense that should make fail = True).

Also, I understand this method is probably super inefficient. Essentially, I want the conditional to be "if func is cancel, break. If func is whitespace or ‘0’, then it equals 0. If func is some non-0 integer, convert the string to an integer and continue. Otherwise, set fail to True and break."

My knowledge of python is minimal so I would very much appreciate a full explanation or link to documentation so I can learn as much as possible.

Thanks in advance 🙂

Edit: This is the entire module

import projects.dice_app as dice_app
import projects.text_to_math as text_to_math
def main():
    f = open("readme_files/index.txt")
    p = open("readme_files/projects.txt")

    print(f.read())

    func = 0
    while True:
        fail = False
        func = input("Requested Operation: ")

        if func == 'Cancel' or func == 'cancel':
            break
        elif func == '' or func == ' ' or func == '0':
            func = 0
        elif type(int(func)) is int:
            func = int(func)
        else:
            fail = True
            break

        if func == 0:
            p = open("readme_files/projects.txt")
            print(p.read())
        elif func == 1:
            dice_app.dice_func()
        elif func == 2:
            text_to_math.ttm_func()
        else:
            print("Invalid operation. Please try again.")

if __name__ == "__main__":
    fail = False
    main()
    while fail == True:
         main()
Asked By: Coder man

||

Answers:

elif func.isnumeric():
    func = int(func)
Answered By: SystemSigma_
try :
    func = int(func)
except ValueError:
    print('not a number')

This should work

Answered By: user18408929
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.