Python: Printing value after .upper - python

I am trying to print a string in all uppercase letters. When I run the print command it prints the type of x and the location.
Why does it print the operation instead of the result?
x = 'bacon'
x = x.upper
print x
>>>
<built-in method upper of str object at 0x02A95F60>

upper (and all other methods) is something like "function ready to use", that way you can do:
x = 'bacon'
x = x.upper
print x()
But the most common to see, and the way I think you want is:
x = 'bacon'
x = x.upper()
print x
"Ridiculous" example using lambda:
upper_case = lambda x: x.upper()
print(upper_case) # <function <lambda> at 0x7f2558a21938>
print(upper_case('bacon')) # BACON

Everything in Python is an object, including functions and methods. x.upper is the upper attribute of x, which happens to be a function object. x.upper() is the result of trying to call that attribute as a function, so you are trying to do
print x.upper()
As an aside, you can try to call any object in Python, not just functions. It will not always work, but the syntax is legitimate. You can do
x = 5
x()
or even
5()
but of course you will get an error (the exact same one in both cases). However, you can actually call objects as functions as long as they define a __call__ method (as normal functions do). Your example can actually be rewritten as
print x.upper.__call__()

Related

why append(function()) return None after revealing the values? [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'

Is it possible to define a functionn as a variable?

working on some code has a func. that goes through if statements I want to assign this to a vaiable that i can use to redefine a list.
everything! cries in python
Code here
Expected : Works
Actual: don't Works
Because of the fact that functions are a type of object (a callable object) a variable can be assigned an instance of that object.
def bar():
return 'foo'
x = bar
print(x) #O <function at #number>
print(x()) #Output: 'foo'
Yeah you can define a function and assign that function to a variable. Then you can call that variable by providing args like any other function.
For example.
>>> def example_function(x, y):
... return x + y
...
>>> func_var = example_function
>>> func_var(10, 20)
30
Will work. It doesn't really accomplish anything though.
If you provide an example of what you want to accomplish I can give a better example.

python integer argument value is not changing even though id() is same in calling and called functions

def func(x):
print "inside function" ,id(x)
x = 2
x = 50
print "outside function" ,id(x)
print 'Value of x before function call is', x
func(x)
print 'Value of x after function call is', x
output:
outside function 6486996
Value of x before function call is 50
inside function 6486996
Value of x after function call is 50
Assuming that id() gives memory location of object. Even though both are saving at the same location, if x value is changed in func(), it is not effected outside.
Ah, but the id(x) call in the function references the global x that was passed to the function, but the x = 2 creates a new local x. Try this:
def func(x):
print "inside function", id(x)
x = 2
print "still inside function", id(x)
x = 50
print "outside function" , id(x)
print 'Value of x before function call is', x
func(x)
print 'Value of x after function call is', x
typical output
outside function 168950596
Value of x before function call is 50
inside function 168950596
still inside function 168951172
Value of x after function call is 50
An assignment usually changes the binding between name and object (if you don't do sth like x = x, of course). It doesn't do any alterations on the object (which wouldn't work on ints anyway as they are immutable, but just as a side note)
So in this case your x inside the function points to the 50 object until you change it. Then it points to a different object. The object itself is not affected.
To point out what happens step by step:
outside x points to int object with value 50
function call: inside x points to same object
inside x is changed to point to different object, having value 2
return: outside x still points to 50.
if u want know more about it, i think u need understand basic python fully.
point about your question:
mutable object as parameter
The function gets a reference to that object and could mutate it, but if you re-bind the reference in the method, outer scope know nothing,after done, the outer reference would still point the original object.
immutable object as parameter
Still can't re-bind the outer reference, and can't even mutate this object.
update for comments: so u pass x(Integer immutable) to function call, you can't mutate this object. and u you re-bind the x refer in the function, outer scope know nothing,after done, the outer reference would still point the original integer 50 object.

Assigning a function to a variable

Let's say I have a function
def x():
print(20)
Now I want to assign the function to a variable called y, so that if I use the y it calls the function x again. if i simply do the assignment y = x(), it returns None.
You simply don't call the function.
>>> def x():
>>> print(20)
>>> y = x
>>> y()
20
The brackets tell Python that you are calling the function, so when you put them there, it calls the function and assigns y the value returned by x (which in this case is None).
When you assign a function to a variable you don't use the () but simply the name of the function.
In your case given def x(): ..., and variable silly_var you would do something like this:
silly_var = x
and then you can call the function either with
x()
or
silly_var()
when you perform y=x() you are actually assigning y to the result of calling the function object x and the function has a return value of None. Function calls in python are performed using (). To assign x to y so you can call y just like you would x you assign the function object x to y like y=x and call the function using y()
The syntax
def x():
print(20)
is basically the same as x = lambda: print(20) (there are some differences under the hood, but for most pratical purposes, the results the same).
The syntax
def y(t):
return t**2
is basically the same as y= lambda t: t**2. When you define a function, you're creating a variable that has the function as its value. In the first example, you're setting x to be the function lambda: print(20). So x now refers to that function. x() is not the function, it's the call of the function. In python, functions are simply a type of variable, and can generally be used like any other variable. For example:
def power_function(power):
return lambda x : x**power
power_function(3)(2)
This returns 8. power_function is a function that returns a function as output. When it's called on 3, it returns a function that cubes the input, so when that function is called on the input 2, it returns 8. You could do cube = power_function(3), and now cube(2) would return 8.
lambda should be useful for this case.
For example,
create function y=x+1
y=lambda x:x+1
call the function
y(1)
then return 2.
I don't know what is the value/usefulness of renaming a function and call it with the new name. But using a string as function name, e.g. obtained from the command line, has some value/usefulness:
import sys
fun = eval(sys.argv[1])
fun()
In the present case, fun = x.
def x():
print(20)
return 10
y = x
y()
print(y)
gives the output
20
<function x at 0x7fc548cd3040>
so it does not actually assign the value returned by x() to the variable y.

Why doesn't print work in a lambda?

Why doesn't this work?
lambda: print "x"
Is this not a single statement, or is it something else?
The documentation seems a little sparse on what is allowed in a lambda...
A lambda's body has to be a single expression. In Python 2.x, print is a statement. However, in Python 3, print is a function (and a function application is an expression, so it will work in a lambda). You can (and should, for forward compatibility :) use the back-ported print function if you are using the latest Python 2.x:
In [1324]: from __future__ import print_function
In [1325]: f = lambda x: print(x)
In [1326]: f("HI")
HI
In cases where I am using this for simple stubbing out I use this:
fn = lambda x: sys.stdout.write(str(x) + "\n")
which works perfectly.
what you've written is equivalent to
def anon():
return print "x"
which also results in a SyntaxError, python doesn't let you assign a value to print in 2.xx; in python3 you could say
lambda: print('hi')
and it would work because they've changed print to be a function instead of a statement.
The body of a lambda has to be an expression that returns a value. print, being a statement, doesn't return anything, not even None. Similarly, you can't assign the result of print to a variable:
>>> x = print "hello"
File "<stdin>", line 1
x = print "hello"
^
SyntaxError: invalid syntax
You also can't put a variable assignment in a lambda, since assignments are statements:
>>> lambda y: (x = y)
File "<stdin>", line 1
lambda y: (x = y)
^
SyntaxError: invalid syntax
You can do something like this.
Create a function to transform print statement into a function:
def printf(text):
print text
And print it:
lambda: printf("Testing")
With Python 3.x, print CAN work in a lambda, without changing the semantics of the lambda.
Used in a special way this is very handy for debugging.
I post this 'late answer', because it's a practical trick that I often use.
Suppose your 'uninstrumented' lambda is:
lambda: 4
Then your 'instrumented' lambda is:
lambda: (print (3), 4) [1]
The body of a lambda has to be a single expression. print is a statement, so it's out, unfortunately.
Here, you see an answer for your question. print is not expression in Python, it says.
in python3 print is a function, and you can print and return something as Jacques de Hooge suggests, but i like other approach: lambda x: print("Message") or x
print function returns nothing, so None or x code returns x
other way around: lambda x: x or print("Message") would print message only if x is false-ish
this is widely used in lua, and in python you can too instead of a if cond else b write cond and a or b
If you want to print something inside a lambda func In Python 3.x you can do it as following:
my_func = lambda : print(my_message) or (any valid expression)
For example:
test = lambda x : print(x) or x**x
This works because print in Python 3.x is a function.

Categories