Home > Back-end >  How can i re-run a main() function in python, if one of its function throws an error?
How can i re-run a main() function in python, if one of its function throws an error?

Time:12-28

Here is a program to return percentage of fuel when entered in fraction where the input is passed on to the another function


def main():
    # taking input from user 'x/y'
    fuel = input("Fraction: ")
    print(convert(fuel),"%",sep="")
    

def convert(fraction):
    # extracting nominators
    fraction.split('/')
    x = int(fraction[0])
    y = int(fraction[2])
    # returning the percentage after calculating
    try:
        per = x / y * 100
        return round(per)
    # ignoring the errors
    except ZeroDivisionError or ValueError:
        pass

# re-run the main() function, if convert() throws errors
if __name__ == '__main__':
    main()

I got the results i was intended when i wrote the whole code similar to this:


def main():
    while True:
        try:
            fuel = input("Fraction: ")
            fuel.split('/')
            x = int(fuel[0])
            y = int(fuel[2])

            print(round(x / y * 100),"%",sep="")
            break
        except ZeroDivisionError or ValueError:
            pass


if __name__ == '__main__':
    main()


But i want to pass on the input ( fuel ) to another function( convert() ) .So, how can i re-run the main() function again, if it's expecting a ZeroDivisionError and ValueError from the convert(fraction) function?

CodePudding user response:

Once you have valid input from the user - i.e., something that you can express as a percentage, just return that value from the function and pass it to another as required.

Something like this:

def convert(fraction):
    pass

def main():
    while True:
        fraction = input('Fraction: ')
        try:
            a, b = map(float, fraction.split('/'))
            print(f'{round(a/b*100)}%')
            return fraction
        except (ValueError, ZeroDivisionError):
            print('Invalid input')


if __name__ == '__main__':
    fraction = main()
    convert(fraction)
  • Related