Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

elif func.isnumeric():
    func = int(func)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading