close

How do you use input function along with def function?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do you use input function along with def function in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do you use input function along with def function?

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

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

Method 1

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.

Method 2

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

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read