I follow a tutorial about Jupyter and Python, where it says that if two consecutive commands are the following:
in: x = 2
in: x
I should get
out: 2
as an result. However, the x on single line in a combined block like:
in: x = 2
in: if x == 2:
x
does not print the x variable. Is this x on single line somewhat different from x as a single command? When I write this I see, a line is different as whole command but what is the underlying concept or thing that makes the first two commands result 2 but the second three commands nothing?
This has to do with the difference between an expression and a statement (see below for links) in python.
An expression can only contain identifiers, literals and operators.
Statements can be significantly more complex. See simple statements and compound statements
The python shell will output the evaluation of an expression, but won't with a statement because there's no guarantee it evaluates to something that can be outputted. You should use print to output values from a statement.
Consider what would happen if you replaced x with its value (2):
if 2 == 2:
2
Would you expect the interpreter to output 2?
When you write a variable in a line and execute it jupyter notebook assumes that you want to know the value of the variable and implicitly converts it to print(variable) so the value of the variable is printed.
When you use multiple statement you will rarely want to print all variables used in the statements. So it is not implemented for this case
Related
I am trying to print values of two variables in Python. My question is when I am trying to print the values in this way like print(a),print(b) in Jupyter notebook, I am getting the values of the variables but the output is also giving a tuple type of result which is giving as (None,None). I want to know why it is giving that (None,None) output. I should have got result like (value1,value2). Someone please advise. Also, please let me know how to the result in tuple format like (2,5) where a=2,b=5. enter image description here
This is just a side effect of the command line. You wouldn't see this if you run a program. If you just type an expression in a command line:
>>> 3
3
Python shows you the result of that expression. If the expression returns None, Python shows you nothing. So:
>>> time.sleep(3)
>>> print("hello")
hello
>>>
time.sleep returns None, so you see nothing. You see the side effect of the print statement, but because the print statement returned None, it shows you nothing else. But when you do:
>>> print(a),print(b)
2
5
(None,None)
>>>
Both print statements return None, and because you've used a comma, the result of that expression is a tuple containing two None values. So, you see the side effect of the print statements, and because your expression ((None,None)) is not exactly the same as None, Python prints it for you.
The comma operator is NOT the right way to separate multiple statements, like you do in C. In Python, the comma operator builds tuples. If you want to separate multiple statements on a line, use semi-colon:
>>> print(a);print(b)
2
5
>>>
It's a part of Jupyter called autocall. There is some documentation on it here:
https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-autocall
To split up your call either ";" or print((a,b)). Not sure what you are trying to achieve.
Apologies for the poor title, I don't know how else to describe my situation.
I wrote a small pattern matching function.
def substrings(input_str):
'''Generate all leading substrings of an input string'''
for i in range(len(input_str)):
return input_str[:i]
It should return a series of slices of a string. If the input was ABCD, it should output ABCD, ABC, AB and A.
When I tested this function in the python console (shown below), it behaves correctly and outputs all the expected strings.
for i in range(len(input_str)):
print(input_str[:i])
But when used in the body of my program its returning nothing at all. For example;
test1 = substrings('ABCD')
print(test1)
Outputs blank lines and I'm struggling to figure out why.
In the console, your loop first prints out a blank string when i==0. Then it continues to loop and print out each of the characters in the string.
In the function, you are returning up to the 0th element in the array, which is the same blank string the console printed on the first time through the loop.
To see better what is happening in the console, you might print the index too:
for i in range(len(input_str)):
print('{0} {1}'.format(i, input_str[:i]))
That's because the first thing your functions returns is empty string ''. So you are exiting loop after first iteration for i = 0 and your variable is empty string because of the fact that:
>>> s = 'ABCD'
>>> s[:0]
''
You are returning in a loop. So the return is the last statement that would execute in a function. That is when a return statement is reached, the control leaves the function. So in the very first iteration i=0, the control returns '' and exits the function irrespective of for-loop. In console the output is obtained because I'm console each line is interpreted one-by-one unlike the program being compiled at once. So console shows the output. Hope this answer helps you
The issue is occurring because you are trying to return information in a loop. When the return statement is called, it exits the function. What you should do is use the yield keyword. Try doing this
def substrings(input_str):
for i in range(len(input_str)):
yield input_str[:i]
# Then iterate through the function like so
function = substrings()
for i in function:
print(i)
Your code should be working fine now!
I just realized that it's possible to stretch a statement across multiple lines when it's passed as a parameter to a function:
print(1 ==
1)
However, doing the same thing during a variable assignment raises a SyntaxError:
x = 1 ==
1
Why does the first example work but the second one yields a SyntaxError?
Python recognizes open brackets, braces, and parentheses as indicating that the statement is not finished. Thus, the function call "naturally" is allowed to span lines.
This parser convention doesn't apply to expressions in which there is not a required balanced enclosing punctuation.
Note that strings also cannot cross line boundaries.
One other way to do this is with the continuation character (\) as in...
x = 1 == \
1
I am using python 2.7. I am running a linux command using python which prints out the wifi ssid available. I need to compare if the ssid I am trying to connect is available or not. I am using the below command to print the ssid:
import commands
ret = commands.getstatusoutput("sudo iwlist wlan0 scan | grep ESSID")
print(ret)
#output:
(0, ESSID="SSID1"\n
ESSID="SSID2"\n
ESSID="SSID3")
if I print print(ret[1]) then it gives below output:
ESSID="SSID1"
ESSID="SSID2"
ESSID="SSID3"
Lets say I am trying to connect to SSID2, how can I put this in a condition to check if SSID2 is available at this moment or not. Something like if ret[1] == "SSID2". I am new to python programming.
Thanks
ret[1] is a newline-separated string. Each line has an equals sign in it. You need an expression that evaluates to True when "SSID2" appears on the right-hand side of any equals sign.
data = '''\
ESSID="SSID1"
ESSID="SSID2"
ESSID="SSID3"'''
if any(x.split('=')[1][1:-1]=="SSID2" for x in data.splitlines()):
print("yes")
data.splitlines() returns a sequence of the lines in data (you could use ret[1] for this). For each line x, x.split('=') returns a list where the first element is the string to the left of the equals sign and the second is that to the right. So x.split('=')[1] is the right-hand side, and x.split('=')[1][1:-1] removes the first and last (quote) characters.
This is wrapped up in a generator expression that produces a sequence of arguments to the built-in any function, which returns True as soon as it encounters an argument that evaluates true.
if "SSID2" in "ret[1].split("\n")[1]":
print "yes"
I am using ipython notebook in ubantu version 16.04 and I run this code,
word = 'Rushiraj'
length = 0
for char in 'rushiraj':
length = length + 1
print('There are', length,'character')
I get this output:
('There are', 8, 'character')
What is the reason for this single quotes and round braces in output ?It should not be there !
The output you are seeing is due to the fact that you are using Python 2, but you're using the print syntax from Python 3. In Python 3, print is a function and takes arguments like other functions (as in print(...)).
In Python 2, print is a statement, and by using parentheses you are actually passing it a tuple as its first argument (so you are printing out the Python representation of a tuple).
You can fix this in two ways.
If you add from __future__ import print_function to the top of your file, then print will behave like it does in Python 3.
Alternately, you can call it like:
print 'There are', length,'character'
You're printing a tuple (even though it may not appear that way at first glance), so the output is the repr of that tuple.