实际上,您从未全局定义过x和y。您只在执行def smaller_num(x, y)时在函数中定义它。
当你做smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))时,你不是在创建名为x和y的变量,你只是在为你的函数创建参数。
为了修复代码,请在调用函数之前创建变量x和y:def smaller_num(x, y): ## Can be rephrased to def smaller_num(x, y):
if x > y: ## if x > y:
number = y ## return y
else: ## else:
number = x ## return x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
result = smaller_num(x, y)
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(result))
代码无法工作的另一个原因是,您没有将函数的返回值重新分配给变量。当您从函数中return某些内容时,以及再次调用该函数时,您需要将值赋给变量,就像我所做的那样:result = smaller_num(x, y)。
调用函数时,从未将值赋给变量,因此它被浪费了。
另外,您使用的是Python3还是2.7?在python 3中,使用input()将返回一个字符串,若要将其转换为整数,可以围绕input()函数调用int()。