function print in python shell - python

Can anyone explain me difference in python shell between output variable through "print" and when I just write variable name to output it?
>>> a = 5
>>> a
5
>>> print a
5
>>> b = 'some text'
>>> b
'some text'
>>> print b
some text
When I do this with text I understand difference but in int or float - I dont know.

Just entering an expression (such as a variable name) will actually output the representation of the result as returned by the repr() function, whereas print will convert the result to a string using the str() function.>>> s = "abc"
Printing repr() will give the same result as entering the expression directly:
>>> "abc"
'abc'
>>> print repr("abc")
'abc'

Python's shell always returns the last value evaluated. When a is 5, it evaluates to 5, thus you see it. When you call print, print outputs the value (without quotes) and returns nothing, thus nothing gets produced after print is done. Thus, evaluating b results in 'some test' and printing it just results in some text.

Related

Python equivalent of omitting second part of ternary operator (a if a else b)

In some languages (I think php and Java) you can omit the second part of the ternary operator as such:
a = "This is a string"
result = a ? : False
The above should be equivalent to
a = "This is a string"
result = a ? a : False
I want to shorten the ternary operator in the following (simplified) python code:
def myFunc():
return "This string could be empty, but now it's not."
result = myFunc() if myFunc() else False
print(result)
This will print the string if it's not empty, but print False when it is empty.
The reason why I want it shorter is because now, I have to call myFunc() two times instead of just once if you were able to omit one of them as is possible in other languages.
Of course I could just assign myFunc() to a variable and use the variable twice in the ternary operator but this would make it bigger again.
Is there any easy way to do this in python? Or is this just not possible?
You can use or here as an empty string evaluates as a Falsey value:
result = myFunc() or False
Refer to Truth Value Testing

Internal working of strings with null characters

I just tried replacing a character in a python string with a null ('') character. Some weird things are happening. Can someone please explain me why is all this happening?
>>> a = "SampleText"
>>> a
'SampleText'
>>> a.replace('a','\0')
'S\x00mpleText'
>>> len(a)
10
>>> a.replace('\0','a')
'SampleText'
>>> len(a)
10
>>> a.replace('a','')
'SmpleText'
>>> len(a)
10
>>> a.replace('','a')
'aSaaamapalaeaTaeaxata'
>>> len(a)
10
The replace function returns the new string and therefore you need to asign it to a variable again. if you write a = a.replace('a','\0') it'll work as you expect it.

Skip new line while printing with ternary operator in python

To print a statement and to prevent going into the new line one could simply add a comma in the end:
print "text",
But how can I do the same using a ternary operator? This one causes invalid syntax:
print ("A", if True else "B", )
[...] to prevent going into the new line one could simply add a comma in the end
The solution is in your question already. One could simply add a comma in the end:
print "A" if True else "B",
However Python 3 has been out for closer to a decade now so I will shamelessly plug the new print function that has much saner syntax:
from __future__ import print_function
print('A' if True else 'B', end=' ')
Future imports/Python 3 solved your problem efficiently, and the strange statement syntax is just a bad memory from past. As a plus, you're now forward-compatible!
print "A" if True else "B",
print "Hi"
Output: A Hi
I guess you can look at it this as one statement:
"A" if True else "B"
Then your print statement becomes:
print "A" if True else "B",
That should print "A" without the newline character (or "B" if the condition is False).
Instead of using just ugly hacks, we can define function called below as special_print which every print locates in the same line:
import sys
def special_print(value):
sys.stdout.write(value)
special_print('ab')
special_print('cd')
Result:
abcd
You can even mix normal print with special_print:
print('whatever')
special_print('ab')
special_print('cd')
Result:
whatever
abcd
Of course you cannot use any expression as argument of special_print, but with displaying variable it just works.
Hope that helps!
You can use the or operator as well, like this:
a = None
b = 12
print a or b,
print "is a number"
# prints: 12 is a number
Just note that the expression above is evaluated lazily, meaning that if bool(a) is False, print will return b even if that evaluates to False too since it wouldn't bother checking (therefore a or b is not equal to b or a generally speaking). In the above example for instance, if b = "" it would just print "is a number" (example).

counting the number of vowels in a word in a string

I am a beginner, and I am trying to find out the number of vowels in each word in a string. So for instance, if I had "Hello there WORLD", I want to get an output of [2, 2, 1].
Oh, and I am using Python.
I have this so far
[S.count(x) in (S.split()) if x is 'AEIOUaeiou']
where S="Hello there WORLD"
but it keeps saying error. Any hints?
x is 'AEIOUaeiou'
This tests whether x is precisely the same object as 'AEIOUaeiou'. This is almost never what you want when you compare objects. e.g. the following could be False:
>>> a = 'Nikki'
>>> b = 'Nikki'
>>> a is b
False
Although, it may be True as sometimes Python will optimise identical strings to actually use the same object.
>>> a == b
True
This will always be True as the values are compared rather than the identity of the objects.
What you probably want is:
x in 'AEIOUaeiou'
Obviously, S in S.count and S in S.split cannot be the same S. I suggest using more semantic names.
>>> phrase = 'Hello there WORLD'
>>> [sum(letter.casefold() in 'aeiouy' for letter in word) for word in phrase.split()]
[2, 2, 1]

Python - How to get a function to actually return `None`? [duplicate]

This question already has an answer here:
Why do I get extra output from code using 'print' (or output at all, using 'return') at the REPL, but not in a script?
(1 answer)
Closed 26 days ago.
Output for:
def test(c):
if c == 4:
return None
return 'test'
returns 'test' given anything I put in such as test(500) but when I try test(4) the function simply skips and pretends I never ran it, but I want it to show None. So,
>> test(500)
'test'
>> test(4)
>>
is what happens. My goal is for a None to return without having to use print in the function:
>> test(4)
None
Help!
It is returning None. Nothing is printed, because the output shows the result, which is None, which is nothing, so it is not shown.
It is returning None. If you want to see that this is true without putting print in the method definition, you can do this:
print test(4)
> None
None is the result returned by things that "don't return anything", like list.sort or the Python 3 print function. If an expression you type at the interactive prompt evaluates to None, Python won't automatically print it, since it thinks you probably called a "doesn't return anything" function, and it would be confusing to have sessions like
>>> l = [3, 2, 1]
>>> l.sort()
None
>>> print(l)
[1, 2, 3]
None
If you want to print it anyway, you need to explicitly print it.

Categories

Resources