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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With