User input within a function
I have defined a function which checks if user input is 0. If yes then prevent exception and ask for user input again. Lastly return the new user input. But somehow the new user input is not taken and 0 is returned. Please guide as to how to solve this problem.
3/31/2017 9:44:17 AMBobby Joseph
5 AnswersNew Answer
Please post your code for inspection.
The function only checks if the value is zero and does not assign back its value to the argument. So after executing it, num1 stays exactly as it was before the checkup. To be honest, I would write it completely differently, but you may try this: num1 = ZeroDivisionChecking(num1) num2 = ZeroDivisionChecking(num2) Should do the trick.
No problem, man. I hope my answer was the best answer, if you know what I mean ;)
Thank you Kuba... I understood :-)
def ZeroDivisionChecking(x): while x==0: try: print("checking") print(1/x) except ZeroDivisionError: print("you should not enter zero") finally: print("program will continue to run \n") x= float(input("enter number other than zero: ")) return x print ("enter the num1") num1=float(input(": ")) # the below is calling the function 'ZeroDivisionChecking' to check the input is not 0 ZeroDivisionChecking(num1) print ("enter the num2") num2=float(input(": ")) # the below is calling the function 'ZeroDivisionChecking' to check the input is not 0 ZeroDivisionChecking(num2) ans = num1/num2 print("\n >>>ANS is below<<<") print(ans) print("\n")