How do you use input function along with def function?

You never actually defined x and y globally. You only defined it in the function when you did def smaller_num(x, y).

When you do smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-")) , you aren't creating variables called x and y, you are just creating parameters for your function.

In order to fix your code, create the variable x and y before you call your function:

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

The other reason your code is not working is because you're not assigning the returned value of the function back into a variable. When you return something from a function, and again when you call the function, you need to assign the value to a variable, like I have: result = smaller_num(x, y).

When you called your function, you never assigned the value to a variable, so it has been wasted.


Also, are you using Python 3 or 2.7? In python 3 using input() will return a string, and to convert this to an integer, you can call int() around the input() function.


This will work:

def smaller_num(x,y):

    if x>y:
        number= y
    else:
        number= x
    return number


x = input("Enter first number:-")

y = input("Enter second number:-")

smaller = smaller_num(x,y)

print("The smaller number between " +  str(x) + " and " + str(y) + " is " + str(smaller))