如何将函数与输入和输出相结合



我想让函数里面有输入。

我的问题是,如果我把输入放在函数内,程序想要值my_function(??,??),之后它也要求输入相同的值。

如果我移动输入到主程序,我如何处理Except值错误?

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 

您可以将input放在函数中,在这种情况下不需要参数:

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

或者在函数外

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

您可以使用def my_function(value1 = None, value2 = None)设置函数的默认值,然后在函数中检查这些值是否设置,否则使用input询问它们

最新更新