Friday, August 5, 2022

[FIXED] How to combine function with input and except

Issue

I am trying to make Function that has input inside function.

My issue is that if I put the input inside the function the program wants values my_function(??,??) and after that it also asks same values for input.

If I move input to main program how can I deal the Except value error?

def my_function(value1, value2)
try:
    value1 = float(input("enter float value 1: "))
    value2 = float(input("enter float value 2: "))

except ValueError:
    print("not a float value")

else:
    result = value2 + value2
    return result 

Solution

You can either have the input inside the function, in which case the parameters aren't required :

def my_function()
    try:
        value1 = float(input("enter float value 1: "))
        value2 = float(input("enter float value 2: "))
    except ValueError:
        print("not a float value")
    else:
        result = value2 + value2
        return result 

result = my_function()
if result is not None:
    #do something with the result

Or outside the function

def my_function(value1, value2):
    result = value2 + value2
    return result 

try:
    value1 = float(input("enter float value 1: "))
    value2 = float(input("enter float value 2: "))
    result = my_function(value1, value2)
    #do something with the result
except ValueError:
    print("not a float value")


Answered By - Xiidref
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.