Python 3.2 idle : range function - print or list? - python

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)

Related

How do I call a function in vs code using python?

I'll want to know how to call a function in vs code. I read the answer to similar questions, but they don't work:
def userInput(n):
return n*n
userInput(5)
And appends nothing
def Input(n):
return n*n
And in the terminal:
from file import *
from: can't read /var/mail/file
Can somebody help me?
You are doing everything correctly in the first picture. In order to call a function in python on vs code you first have to define the function, which you did by typing def userInput(n):. If you want to see the result of your function, you should not use return, you should use print instead. Return is a keyword- so when your computer reaches the return keyword it attempts to send that value from one point in your code to another. If you want to see the result of your code, typing print (n) would work better.
Your code should look like this:
def userInput(n):
print (n * n)
userInput(5)
The code would print the result 25
Your terminal is your general way to access your operating system, so you have to tell it that you want it to interpret your Python code first.
If you want to run the file you're typing in, you have to first know the location of that file. When you type ls in your terminal, does the name of your Python file show up? If not, hover over the tab in VSCode (it's close to the top of the editor) and see what path appears. Then in your terminal type cd (short for "change directory") and then the path that you saw, minus the <your filename here>.py bit. Type ls again, and you should see your Python file. Now you can type python <your filename here>.py to run it (provided you have Python installed).
You could also run the IDLE by just typing python in your terminal. This will allow you to write your code line-by-line and immediately evaluate it, but it's easier to write in VSCode and then run it with the method I described before.

Python Return Command In Recursion Function

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.

Simulate shell behavior (force eval of last command to be displayed)

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.

Equivalent of matlab "ans" and running shell commands

These days, I'm transitiong from Matlab to Python after using Matlab/Octave for more than ten years. I have two quick questions:
In the Python interactive mode, is there anything corresponding to Matlab's ans?
How can I run shell commands in the Python interactive mode? Of course, I can use os.system(), but in Matlab we may run shell commands just by placing ! before the actual command. Is there anything similar in Python?
Python interactive mode is Python. You will need to use os.system or an equivalent. Alternately, you can suspend Python with Ctrl-Z, and get back into it with fg. (Assuming UNIX-like environment.)
The last evaluated expression is saved in the variable _:
>>> 1 + 2
3
>>> _ * 4
12
The Python equivalent of the Matlab ans is as follows:
ans = (your_expression)
In other words, the most recent expression is not always automatically saved to a default reference, so just save it manually as normal. As #Amadan points out, expressions are sometimes saved to _, but not always. The best practice for reliability and clarity is to save it yourself.
To run shell commands, you can use os.system() as you suggested. However, that is deprecated, so you should look into the subprocess module.
You probably want to use the IPython shell (now part of the jupyeter project). In the IPython shell you can also run system commands using !, although many basic commands (like ls or cd) work without even needing to !. Unlike in MATLAB, you don't need to pass it as a string (although you can). So !ls works fine in IPython, while in MATLAB you would need to do !'ls'. Further, you can assign the results to a variable in IPython, which you can't do in MATLAB. So a = !ls works in IPython but not in MATLAB. Further, if you use !!, the result is returned in a form easily usable in Python. So !!ls returns a list of file names.
IPython still uses the _ notation for getting the previous result (except, as with Python, None is counted as "no result" and thus is not recorded). You can also get the second-to-last result with __ and the third-to-last with ___. Further, IPython puts a number next to each line in the command prompt. To get the result of a particular line, just do _n where n is the number. So to get the result of the 3rd command, which has the number 3 next to it, just do _3. This still doesn't work if the result is None, though.
It has a ton of features. You can get the previous input (as a string) with _i (and so on, following the same pattern as with the outputs). You can time code with %timeit and %%timeit. You can jump into the debugger after encountering an error.

How to access the calling source line from interactive shell

I want to make a function that can determine the source code of how it was called. I'm aware of how to do this generally with the inspect module. For example, this question, works well and provides my desired output in the lines variable as shown below:
def hello(x):
frame,filename,line_number,function_name,lines,index=\
inspect.getouterframes(inspect.currentframe())[1]
print(frame,filename,line_number,function_name,lines,index)
The problem is that this solution doesn't work in an interactive command line session. For example, from a command line, the result looks like:
>>> y = hello(7)
(<frame object at 0x01ECA9E8>, '<stdin>', 1, '<module>', None, None)
The problem is that the source file is '<stdin>', so the lines variable is None. How can I access the calling line to find the result containing the string y = hello(7) during an interactive session?
It may not be possible, as #abarnert says. There are at least partial workarounds, however.
Getting source code lines isn't the biggest problem; modules like readline keep track of them. Interactive Python and iPython expose their lines slightly differently (sigh), but that too can be equalized. (My show package, for example, does this; its linecacher module puts a veneer on to equalize source access for normal Python and the different interactive flavors.)
The bigger problem is that, even once you have the source code, inspect doesn't provide legitimate line numbers (e.g. inspect.currentframe().f_back.f_lineno works great in normal code, but gives values like 1 or the point of the call in <stdin> when called interactively.)
But I'm not quite ready to call it impossible. Based on tracebacks generated by interactive Python and iPython, it appears that there may be sufficient information available to reconstruct "where did this call come from?" How much effort that would take, and how robust the answers would be...those are open questions.

Categories