Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use input function along with def function?

I'm new to programming. I have a bit of problem with python coding (with def function).

So basically the code has to give the smaller number out of 2 numbers.

Question: Write codes to perform the following tasks:

  1. Define a function smaller_num that takes in two numbers to determine and return the smaller number of the two.
    Ask user for two numbers
    Use the function to determine the smaller number and display the result

So I had user input instead of calling the function and adding value inside the variable.

This is how my code looks like:

def smaller_num(x,y):
    if x>y:
        number= y
    else:
        number= x
    return number

smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))

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

How do I correct it? For now it's not working because "x" is not defined. But I feel that I defined them clearly both in def function and input function. So how do I fix this?

Thanks for those who respond to this question.

like image 969
petrichor-vellichor Avatar asked Jun 09 '15 10:06

petrichor-vellichor


1 Answers

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.

like image 87
TerryA Avatar answered Oct 20 '22 01:10

TerryA