While learning Python and browsing the internet I stumble upon a piece of code in w3schools.com. I tried to run it using their built-in site Python IDLE and using my own Python 3.9.0 Shell. What I got is two different outputs.
I want to know which output is the correct output and why is it providing two different outputs.
The Codes and Its Output
Built in site Python IDLE
Python 3.9.0 Shell
Notice that the number 21 is only printed(outputted) once when running the code using Built-in site Python IDLE, while it is printed(outputted) twice when running the code using Python 3.9.0 Shell.
My Own Debugging
I have tried a simple print statement debugging. Checking the result there is only one different, using Python 3.9.0 Shell the last return line is executed and it outputted the last result while using the Built-in site Python IDLE the last return is either not executed or not outputted, in this case, I believe it is the former, and I believe the correct output is the Python 3.9.0 Shell, but I have no idea why are there two different output.
Print Statement Using Python 3.9.0 Shell Result Part 1 Result Part 2
Print Statement Using Built-in site Python IDLE Result Part 1 Result Part 2
Source Code
def tri_recursion(k):
if(k>0):
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
tri_recursion(6)
You have added a return result statement at the end. For any IDE, unless you print that value, it wouldn't be displayed. However, IDLE prints the return value as well. Technically, both outputs are correct, since both interpreters are configured to do different actions. As a small example,
def foo():
return(1)
Running foo() on IDLE gives >>> 1, whereas it gives nothing on other IDE's, as there is no print statement
Both are correct.
The built-in python on the site is showing you the output of the execution of your program. This is equivalent to running the following program:
if __name__ == '__main__':
tri_recursion(6)
add this at the end of your code, save it as test.py and run it like this:
python test.py
the results will be the same
The python shell is showing you the output of the REPL (Read-Eval-Print-Loop), the print statement will print to the screen, but the return value of the function is also printed, because of the REPL, there's no way to avoid this, it is so by design.
You could design your function to not return anything, but it wouldn't be recursive anymore.
both are correct you need to understand that the python shell is printing statement's output.
when you write :
>>> tri_recursion(6)
it will execute first all the print inside function then it prints value that the last call returns.
Related
I'm taking a Udemy course on Python (my first language) and the environment of choice is Jupyter. When I try to write that code in Sublime, I can't get the same output (there are no errors).
def splicer(mystring):
if len(mystring)%2 == 0:
return "Even"
else:
return "Odd"
names = ["Andy", "Eve", "Sally"]
list(map(splicer,names))
You need to print the result!
print(list(map(splicer,names)))
In Jupyter, it automatically prints the representation of a statement, where as when you're writing applications, you need to print if you want the result to be shown on the screen.
jupyter acts as a python interpreter, so if you enter an object it automatically prints the result underneath. Sublime is a text editor, so it is only executing the code you are giving it. It is running list(map(splicer,names)) but it is not displaying the object because you are not telling it to.
So the interpreter (jupyter) is executing your python code in real time and interpreting (printing to screen). The text editor is only executing your python code. Therefore, you need to add a print statement to your object to have the editor print the object to screen:
print(list(map(splicer,names)))
I am trying to write a program to find the sum of a list using recursion in python and my code is this
value = 0
def sum_list(alist):
global value
if len(alist) == 0:
return value
value += alist.pop()
return sum_list(alist)
print sum_list(range(10))
But when i am executing this script I am getting a weired error.
Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/%{ <-- HERE (.*?)}/ at /usr/bin/print line 528.
Error: no "print" mailcap rules found for type "text/x-python"
I searched for it but couldn't get why this error is coming.
Help will be appreciated
Your code is valid Python 2. (It's not valid Python 3 because the print statement would have to be different.)
You don't say how you are actually running this code, but it looks like it is not actually being interpreted as a Python program. The error message is coming from /usr/bin/print, so I think you have managed to get this interpreted as a shell script somehow, and the "print" on your final line is running /usr/bin/print. That's obviously not what you want.
If you are executing this inside a source file, try putting the following line at the top of it, to tell the shell to run this as a Python program:
#!/usr/bin/env python
Alternatively, run it using
python myfile.py
I had this problem, it was an oversight at the terminal prompt. I was typing print instead of python
$ print sum.py
$ Error: no "print" mailcap rules found for type "text/x-python"
Correct way:
$ python sum.py
$ program runs successfully...
The error message comes from Perl. No idea how you managed to call it with this Python code.
see also http://www.perlmonks.org/?node_id=113525
I've tried to run multiple python functions on mac terminal and they all return syntax error, for this program
def spam():
print "R"
spam()
it returned the error:
./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `def spam():'
this is really the simplest function I could find.
Just to be clear terminal is running the rest of the program but it can't handle functions.
#!/usr/bin/python
import math
number = int(raw_input("What's your surd?"))
print type(number)
#Just to let us know what the input is
if type(number) == int:
print "Number is an integer"
else:
print "Please enter a number"
value = math.sqrt(number)
#Takes the number and square roots it
new_value = int(value)
#Turns square root of number into an integer
if type(new_value) == int:
print "Surd can be simplified"
print new_value
else:
print "Surd cannot be simplified"
print value
This program runs fine even if it is a bit buggy at the moment but the following program returns the same error as the previous function.
# define a function
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = int(input("What's your number? "))
print_factors(num)
Why terminal is returning a syntax error where there isn't one?
The problem here (at least for that first example) is that you're not using a python interpreter. The terminal is using a bash interpreter for your python code and getting very confused. Use a command like this to execute your code python spam.py . Or first enter the python command interpreter by running python, then entering your code in the command line interpreter.
What might be even easier while getting started is to get an IDE like PyCharm (https://www.jetbrains.com/pycharm/) and running through a couple of their tutorials to get the feel of it.
Your issue is that your shell doesn't know you are running a Python script. You need to make it clear that you should be using the Python interpreter. You can either do this by:
1) Call python test.py at your terminal.
2) Add #!/usr/bin/python at the top of your Python script (you may need to alter the path to the Python executable on your system). Make the script executable, and call ./test.py at your terminal.
The benefits of 2) are that you know what version of Python you will be running your script with (Python 2.x in your case?).
Method 1) will use whatever Python version is encountered first in your PATH, which may be Python 3 or Python 2, depending on whether you have installed Python 3 at some point. The code you have written will work with Python 2.7, but not Python 3.x. Of course you can always explicitly call python2.7 ./test.py.
In a python shell, if I type a = 2 nothing is printed. If I type a 2 gets printed automatically. Whereas, this doesn't happen if I run a script from idle.
I'd like to emulate this shell-like behavior using the python C api, how is it done?
For instance, executing this code PyRun_String("a=2 \na", Py_file_input, dic, dic); from C, will not print anything as the output.
I'd like to simulate a shell-like behavior so that when I execute the previous command, the value "2" is stored in a string. Is it possible to do this easily, either via python commands or from the C api? Basically, how does the python shell do it?
To compile your code so expression statements invoke sys.displayhook, you need to pass Py_single_input as the start parameter, and you need to provide one statement at a time.
I know this is wrong thing to do, but I am using python 3 but studying it with python 2 book.
it says,
>>>range(2,7)
will show
[2,3,4,5,6]
but I know it won't show the output above, THAT I figured. so I tried:
>>>>print(range(2,7))
and ta-da- it shows follow:
range(2,7)
looks like this is the one of changes from P2 to P3 so I tried:
list(range(2,7))
this one works ok on IDLE but not ok on notepad for long coding. so finally I tried:
print(list(range(2,7)))
and it showed something similar to what I intended... Am I doing right? Is this the only way to write it?
In your IDLE case, you are running the code in IDLE's PyShell window. This is running the interactive interpreter. In interactive mode, Python interprets immediately each line you type in and it displays the value returned by evaluating the statement you typed plus anything written to standard output or standard error. For Python 2, range() returns a list and, as you discovered, in Python 3, it returns an iterable range() object which you can use to create a list object or use elsewhere in iteration contexts. The Python 3 range() is similar to Python 2's xrange().
When you edit a file in an editor like Notepad, you are writing a script file and when you run the file in the Python interpreter, the whole script is interpreted and run as a unit, even if it is only one line long. On the screen, you only see what is written to standard output (i.e. "print()") or standard error (i.e. error tracebacks); you don't see the results of the evaluation of each statement as you do in interactive mode. So, in your example, when running from a script file, if you don't print the results of evaluating something you won't see it.
The Python tutorial talks a bit about this here.
If your only goal is to get back the list representation, what you're doing is correct. Python 3.0 now treats range as returning an iterator (what xrange used to do)