Why is my function skipping the If statement? [duplicate] - python

This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 7 years ago.
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()

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

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.

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

Related

Print common letters from two string by calling only one print [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 8 months ago.
In my previous question, Andrew Jaffe writes:
In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return something.
When you create autoparts() or splittext(), the idea is that this will be a function that you can call, and it can (and should) give something back.
Once you figure out the output that you want your function to have, you need to put it in a return statement.
def autoparts():
parts_dict = {}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
print(parts_dict)
>>> autoparts()
{'part A': 1, 'part B': 2, ...}
This function creates a dictionary, but it does not return something. However, since I added the print, the output of the function is shown when I run the function. What is the difference between returning something and printing it?
print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:
def autoparts():
parts_dict = {}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict
Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as:
my_auto_parts = autoparts()
print(my_auto_parts['engine'])
See what happened? autoparts() was called and it returned the parts_dict and we stored it into the my_auto_parts variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key 'engine'.
For a good tutorial, check out dive into python. It's free and very easy to follow.
The print statement will output an object to the user. A return statement will allow assigning the dictionary to a variable once the function is finished.
>>> def foo():
... print "Hello, world!"
...
>>> a = foo()
Hello, world!
>>> a
>>> def foo():
... return "Hello, world!"
...
>>> a = foo()
>>> a
'Hello, world!'
Or in the context of returning a dictionary:
>>> def foo():
... print {'a' : 1, 'b' : 2}
...
>>> a = foo()
{'a': 1, 'b': 2}
>>> a
>>> def foo():
... return {'a' : 1, 'b' : 2}
...
>>> a = foo()
>>> a
{'a': 1, 'b': 2}
(The statements where nothing is printed out after a line is executed means the last statement returned None)
I think you're confused because you're running from the REPL, which automatically prints out the value returned when you call a function. In that case, you do get identical output whether you have a function that creates a value, prints it, and throws it away, or you have a function that creates a value and returns it, letting the REPL print it.
However, these are very much not the same thing, as you will realize when you call autoparts with another function that wants to do something with the value that autoparts creates.
you just add a return statement...
def autoparts():
parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict
printing out only prints out to the standard output (screen) of the application. You can also return multiple things by separating them with commas:
return parts_dict, list_of_parts
to use it:
test_dict = {}
test_dict = autoparts()
Major difference:
Calling print will immediately make your program write out text for you to see. Use print when you want to show a value to a human.
return is a keyword. When a return statement is reached, Python will stop the execution of the current function, sending a value out to where the function was called. Use return when you want to send a value from one point in your code to another.
Using return changes the flow of the program. Using print does not.
A function is, at a basic level, a block of code that can executed, not when written, but when called. So let's say I have the following piece of code, which is a simple multiplication function:
def multiply(x,y):
return x * y
So if I called the function with multiply(2,3), it would return the value 6. If I modified the function so it looks like this:
def multiply(x,y):
print(x*y)
return x*y
...then the output is as you would expect, the number 6 printed. However, the difference between these two statements is that print merely shows something on the console, but return "gives something back" to whatever called it, which is often a variable. The variable is then assigned the value of the return statement in the function that it called. Here is an example in the python shell:
>>> def multiply(x,y):
return x*y
>>> multiply(2,3) #no variable assignment
6
>>> answer = multiply(2,3) #answer = whatever the function returns
>>> answer
6
So now the function has returned the result of calling the function to the place where it was called from, which is a variable called 'answer' in this case.
This does much more than simply printing the result, because you can then access it again. Here is an example of the function using return statements:
>>> x = int(input("Enter a number: "))
Enter a number: 5
>>> y = int(input("Enter another number: "))
Enter another number: 6
>>> answer = multiply(x,y)
>>> print("Your answer is {}".format(answer)
Your answer is 30
So it basically stores the result of calling a function in a variable.
def add(x, y):
return x+y
That way it can then become a variable.
sum = add(3, 5)
print(sum)
But if the 'add' function print the output 'sum' would then be None as action would have already taken place after it being assigned.
Unfortunately, there is a character limit so this will be in many parts. First thing to note is that return and print are statements, not functions, but that is just semantics.
I’ll start with a basic explanation. print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.
On a more expansive note, print will not in any way affect a function. It is simply there for the human user’s benefit. It is very useful for understanding how a program works and can be used in debugging to check various values in a program without interrupting the program.
return is the main way that a function returns a value. All functions will return a value, and if there is no return statement (or yield but don’t worry about that yet), it will return None. The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user.
Consider these two programs:
def function_that_prints():
print "I printed"
def function_that_returns():
return "I returned"
f1 = function_that_prints()
f2 = function_that_returns()
print "Now let us see what the values of f1 and f2 are"
print f1 --->None
print f2---->"I returned"
When function_that_prints ran, it automatically printed to the console "I printed". However, the value stored in f1 is None because that function had no return statement.
When function_that_returns ran, it did not print anything to the console. However, it did return a value, and that value was stored in f2. When we printed f2 at the end of the code, we saw "I returned"
The below examples might help understand:
def add_nums1(x,y):
print(x+y)
def add_nums2(x,y):
return x+y
#----Function output is usable for further processing
add_nums2(10,20)/2
15.0
#----Function output can't be used further (gives TypeError)
add_nums1(10,20)/2
30
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-124-e11302d7195e> in <module>
----> 1 add_nums1(10,20)/2
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

Pass boolean argument by reference [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 9 months ago.
In C++ you can always pass something as reference and anything that happens within the callee would be known to caller by just examining the referenced variable.
Imagine this scenario:
def x():
a = f()
print(a)
def f():
return "hello"
What I want is add a boolean flag that returns from f to x. There are several ways to do that:
make f return a tuple (str,bool)
pass a reference to a boolean variable into f
option 1 is currently not possible since there are many callers to f() and I cant change them to accept tuple as return value, so it must stay as it is.
option 2 is not possible since boolean argument is immutable (as I've learned recently).
Only f can calculate the boolean value, and x needs to know about it.
Is there any good way to achieve that? Looking for something that is not bad practice in Python coding in general.
The option that's closest to passing a pointer/reference into f would be to pass it a mutable object, like a list:
def f(ok=None):
if isinstance(ok, list):
ok.append(True)
return "hello"
def x():
ok = []
a = f(ok)
print(a, ok.pop())
But the better solution IMO would be to return a tuple, and refactor that behavior into a new function so that you're sharing code without disturbing the existing API:
def f_with_flag():
return "hello", True
def f():
return f_with_flag()[0]
def x():
a, ok = f_with_flag()
print(a, ok)

How should I code a function to turn a parameter I input into 1? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 8 years ago.
I am the new to Python. Here is a problem that I have encountered.
Assume that there is a function called set1(x).
Here is the code:
def set1(x):
x = 1;
When I run this,
m = 5
set1(m)
m
the value of m is still 5.
So how should I code the function if I want the parameter to become 1 whenever I call the set1() function?
You can return the value
def set1():
return 1;
And call it as
m=5
m = set1()
print (m)
It will print 1
Another way but bad method is to make it global
def set1():
global m
m = 1
Functions use a local namespace in which they declare their variables, which means that in most cases when you pass an argument to a function, it will not effect the argument outside of the function (in the global namespace). So while the value changes within the function, it does not change outside of the function.
If you want the function to change the value, you need to return the value as such:
def set1(x):
x=1
return x
>>> m=5
>>> m = set1(m)
>>> m
1
This said, if your argument is mutable, it can change.
def set2(x):
x[0] = 1
>>> m = [2]
>>> set2(m)
>>> m[0]
1

How to get a closure to refer to the value that a variable had at the time of its definition [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Creating lambda inside a loop
In the code below, invoking any member of the returned array of closures
prints the number 4.
def go():
x = []
for i in range(5):
def y(): print i
x.append(y)
return x
I would like each member of the closure to print the number that i was when the closure was defined.
One way around this is to use default arguments:
def y(i=i):
print i
Default arguments are evaluated when the function is created, not called, so this works as you'd expect.
>>> i = 1
>>> def y(i=i): print i
...
>>> i = 2
>>> y()
1
A little extra info just for fun:
If you're curious what the defaults are, you can always inspect that with the .func_defaults attribute (__defaults__ in python3.x):
>>> y.func_defaults
(1,)
This attribute is also writeable, so you can in fact change the defaults after the function is created by putting a new tuple in there.

Difference between returns and printing in python? [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 7 years ago.
In python I don't seem to be understanding the return function. Why use it when I could just print it?
def maximum(x, y):
if x > y:
print(x)
elif x == y:
print('The numbers are equal')
else:
print(y)
maximum(2, 3)
This code gives me 3. But using return it does the same exact thing.
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
print(maximum(2, 3))
So what's the difference between the two? Sorry for the mega noob question!
The Point
return is not a function. It is a control flow construct (like if else constructs). It is what lets you "take data with you between function calls".
Break down
print: gives the value to the user as an output string. print(3) would give a string '3' to the screen for the user to view. The program would lose the value.
return: gives the value to the program. Callers of the function then have the actual data and data type (bool, int, etc...) return 3 would have the value 3 put in place of where the function was called.
Example Time
def ret():
return 3
def pri():
print(3)
4 + ret() # ret() is replaced with the number 3 when the function ret returns
# >>> 7
4 + pri() # pri() prints 3 and implicitly returns None which can't be added
# >>> 3
# >>> TypeError cannot add int and NoneType
What would you do if you need to save printed value? Have a look at good explanation in docs and cf.:
>>> def ret():
return 42
>>> def pri():
print(42)
>>> answer = pri()
42
>>> print(answer) # pri implicitly return None since it doesn't have return statement
None
>>> answer = ret()
>>> answer
42
It also is no different from return statement in any other language.
For more complex calculations, you need to return intermediate values. For instance:
print minimum(3, maximum(4, 6))
You can't have maximum printing its result in that case.
Remember that the interactive command line isn't the only place methods will be called from. Methods can also be called by other methods, and in that case print isn't a usable way to pass data between them
Honestly, it depends on what you need the function to do. If the function specification state that it will print out max term, then what you have is fine. What generally happens for a method like this is that the method should return the actual value which is larger. In the case they are equal, it doesn't matter which value is returned.

Categories

Resources