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.
Related
message = "Hello World!"
vs
message = ("Hello World!")
As far as I have tested, both get interpreted with the same output. I've just started to learn python and wondering if those parentheses have any impact.
Both the implementations are same.
message= "Hello World!"
print(type(message))
Output: <class 'str'>
message = ("Hello World!")
print(type(message))
Output: <class 'str'>
Adding parenthesis to a string don't automatically make them tuples. You need to add a comma after the string to indicate to python that it should be a tuple.
message = ("Hello World!",)
print(type(message))
Output:<class 'tuple'>
Just like in a mathematical expression, parentheses don't always change the output in Python.
5 + 4 == (5 + 4) == ((5) + ((4)))
It isn't necessary to use parentheses to assign values to variables like in your question. In general however, its not always a bad idea to use parentheses even if they don't change the output of the code - if the order of operations is not perfectly clear, parentheses will make it obvious.
As one of the answers above mentioned tuples and you indicated you are new to python; I might add that in python having something to the right of an equals sign in parentheses often indicates you are trying to make a tuple. However a tuple requires at least one comma so the interpreter can figure out you are in fact making a tuple, even with only one entry.
In your example putting a string in parentheses has no effect, and probable should not done just because it would not be expected by other python developers. (Not pythonic)
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 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
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.
Python 2.7 on Windows 10
So, I've started trying to use a function that, in all of my examples, locates the first iterance in a string of the requested word.
Example:
message = "Hello, World."
print(message.find('World'))
and it will return:
7
This works for me. However I'm trying to give a string, then ask if the user would like to locate a word within that string. If the answer is yes, the program is asking which word and the input from the user is being assigned the variable dokokotoba and then I'm trying to find the word dokokotoba.
The program runs fine in all aspects save that every time I try to find a word, it returns -1, which indicates failure. I don't understand why. Is it because I can't use a variable there? If so, I can't see why not.
You have .find('dokokotoba') instead of .find(dokokotoba).
You are looking for the string 'dokokotoba', not the value of the variable. That string is not present in message, no.
Pass in the variable, not a string literal:
message.find(dokokotoba)
Note the lack of quotes there.
Demo:
>>> message = 'foo bar baz'
>>> message.find('bar')
4
>>> dokokotoba = 'bar'
>>> message.find(dokokotoba)
4
>>> message.find('dokokotoba')
-1
The proper way is
message.find(dokokotoba)
and not
message.find('dokokotoba')
In the second case you are simply searching for the string "dokokotoba" in the message.