0

It accepts the inputs ok, but doesn't go on to the if statement. Can I not define a variable in a function argument?

def maximum(one = int(input("Enter first Number: ")),
            two = int(input("Enter second Number: "))):  
    if one > two:  
        return one  

    else:  
        return two


maximum()
André Laszlo
  • 15,169
  • 3
  • 63
  • 81
Boogz
  • 9
  • 4
  • 1
    That's a *really* strange way of doing things. `input` only gets called **once**, when the function *is defined*. Why not move the user input to the *call* to `maximum`? However, the function will work just fine; did you mean to `print` the returned value? – jonrsharpe Jul 03 '15 at 10:13
  • Default values for function arguments are evaluated *when creating the function object*, not when calling the function. – Martijn Pieters Jul 03 '15 at 10:15
  • While all said about the arguments above and below is valid, you don't seem to be using the result of the function, and therefore, not able to check whether it really goes inside `if`. – bereal Jul 03 '15 at 10:17
  • 1
    @bereal: more likely that the return value is ignored; a simple `print(maximum())` would fix that part. – Martijn Pieters Jul 03 '15 at 10:18

3 Answers3

1

You can "define variables" in the argument list. The problem is that the expression is only evaluated once, when the function is declared.

To give an example, in this interactive (IPython!) session I'm declaring two functions. Note that "Doing something" is only printed once, just as I declare test():

In [86]: def something():
   ....:     print "Doing something"
   ....:     return 10
   ....: 

In [87]: def test(x=something()):
   ....:     print "x is %s" % x
   ....:     
Doing something

In [88]: test()
x is 10

In [89]: test()
x is 10

For the above reason, the following pattern is pretty common for default arguments in Python, try to use it in your function.

def foo(arg=None):
    if arg is None:
        arg = "default value" # In your case int(input(...))
André Laszlo
  • 15,169
  • 3
  • 63
  • 81
0

Don't use default argument's values in such way. They evaluated only once during function creation. So your function will always receive the same input that will be equal to first time received data.

Ivan Velichko
  • 6,348
  • 6
  • 44
  • 90
0

Default value for the parameters is evaluated when the def statement they belong to is executed (that is they are only executed when the function is defined) .

They are not recalculated when the function they belong to is called.

Example -

>>> def hello(one = print("Hello")):
...     print("Bye")
...
Hello
>>> hello()
Bye
>>>
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176