How to print after a while loop - python

I have Python 3.8(32-bit) installed, and I am using Atom to write my attempts and then copy-pasting them into the Python terminal.
The following code is copied directly from the very beginning of an introductory Python course I am taking "for fun":
n = 5
while n > 0:
print(n)
n=n-1
print('Blastoff!')
The code works in every sandbox I can find, and the last line works on its own in my terminal. But when I copy it to my terminal, I get an invalid syntax error that points to the word print. I can fix this and get the desired output by changing my code to:
n = 5
while n > 0:
print(n)
n=n-1
else:
print('Blastoff!')
But I have three issues with this:
Why does my original code not work, as it is copied directly from the course?
I need to hit Enter twice after copying in that second block of code for it to run. Why is that?
Why does Atom insist on indenting the last print farther than my other indents?
Here is what I am seeing when entering my first code brick:
>>> n = 5
>>> while n > 0:
... print(n)
... n=n-1
... print('Blastoff!')
File "<stdin>", line 4
print('Blastoff!')
^
SyntaxError: invalid syntax

Since you're entering code into the Python interpreter, it'll interpret the code line-by-line. This is great for quick tests and checks, but for larger code, you'll want to run an entire file.
You can achieve this a couple different ways:
Running it from the command prompt/terminal. If your Python executable is in your PATH, you can open a command prompt and navigate to your file and run python myfile.py. See "How to add Python to Windows PATH".
If you've installed Python from python.org, you may have IDLE installed. You can run the IDLE application and open your file from the menu File > Open. From there, you can run the file from the menu Run > Run Module.
I'd suggest the second option since you are learning and it will help you focus on coding instead of fighting your code environment. However, feel free to revisit option #1 in the future. It is definitely helpful to know your way around the command line (if you work on a machine without IDLE installed, this would be the proper way to run Python files).
Also "How to Run Your Python Scripts" is a great resource for learning more about how running scripts in Python works.

Related

Confused by print function using Sublime Text 3 with Python build

I have configured Sublime text 3 to compile and execute Python 3.5 code and have successfully run several small programs. However when I try and run this simple code to calculate the square of a number the user can input, the console will not return the final answer:
def square():
num = int(input("Please enter the number you wish to square: "))
answer = num ** 2
print (answer)
square()
In Sublime Text 3 it will ask the user for input but then not print the answer. If I run it in IDLE though it will print the answer. As I said I can run other small programs involving print (like Hello World for example) so I am not sure what is wrong. All help appreciated I am just starting out so please forgive my lack of experience.
I was able to run your code through my terminal. It ran perfectly. I wrote the same code in Sublime Text 3 as I use the same editor. I don't think there is any input/output exception for sublime. You might want to restart the terminal and then try creating a new .py file to run this code.

How does python interpreter run the code line by line in the following code?

I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file ex1.py,
print "Hello world"
12variable = 'bye'
print 12variable
Now according to the working of interpreter, the interpreter would run the first line i.e. it prints hello world first and then show the syntax error in the next line (line-by-line working). Hence the expected output is:
Hello world
12variable = 'bye'
^
SyntaxError: invalid syntax
But the actual output is -
12variable = 'bye'
^
SyntaxError: invalid syntax
Why it is not printing Hello World at the first?
It depends on how you run the Python interpréter. If you give it a full source file, it will first parse the whole file and convert it to bytecode before execution any instruction. But if you feed it line by line, it will parse and execute the code bloc by bloc:
python script.py : parse full file
python < script.py : parse and execute by bloc
The latter is typically the way you use it interactively or through a GUI shell like idle.
It's a myth that Python is a fully interpreted language. When CPython runs a script the source code is parsed (this is where it will catch syntax errors), and compiled into bytecode (sometimes these are cached in your directory as .pyc files) before anything is executed. In this regard Python is not all that fundamentally different than Java or C# other than that it doesn't spend much time doing any optimizations, and I believe the bytecode is interpreted one instruction at a time, instead of being JITed to machine code (unless you're using something like PyPy).
Because your understanding of the interpreter is faulty. While it is possible for the behaviour you are describing to occur for a subset of errors it is not the common case for many (most?) errors.
If the interpreter can construct what it thinks is a valid program but there is an error at run time then what you are describing will happen.
Since the case you are pointing at is a syntax error that prevents a valid program being constructed the behaviour is as you see it.
I understand it that way:
Python runs the code line by line after it's in byte code state.
The difference between this thing and compilation (in other languages like C++) is that you have to do this process of interpretation each time you run the script.
Python interpreter interprets the code each time you run the script.
In C++ you compile the program and you can execute it without having to compile it again unless you want to change the system.
Step 1:
The interpreter reads a python code or instruction. Then it verifies that the instruction is well-formatted, i.e. it checks the syntax of each line. If it encounters an error, it immediately halts the translation and shows an error message.
Step 2:
If there is no error, i.e. if the python instruction or code is well-formatted then the interpreter translates it into its equivalent form in an intermediate language called “Byte code”.Thus, after the successful execution of Python script or code, it is completely translated into Byte code.
Step 3:
Byte code is sent to the Python Virtual Machine(PVM).Here again, the byte code is executed on PVM. If an error occurs during this execution then the execution is halted with an error message.
So in your case, the "invalid syntax" error is thrown because of step1. But, the actual print function gets executed at step 3. step 3 comes only after step 1 right... I think got it now.

Running a .py file in a loop

I am currently trying to run a .py file but in a loop.
Just for a test I am using
I = 0
while I<10:
os.pause(10)
open(home/Tyler/desktop/test.py)
I = I + 1
I am sure this is a very simple question but I can't figure this one out.
I would also like to add in the very end of this I have to make this run infinitely and let it run for some other things.
There are a few reasons why your code isn't working:
Incorrect indentation (this may just be how you copied it on to StackOverflow though).
Using os without importing it.
Not using quotes for a string.
Mis-using the open function; open opens a file for reading and/or writing. To execute a file you probably want to use the os.system.
Here's a version that should work:
import os
i = 0
while i < 10:
os.pause(10)
os.system("home/Tyler/desktop/test.py")
i += 1
Python is indentation-sensitive, and your code is missing indentation
after the while statement!
Running the open command will not run the Python script. You can
read what it does here in the docs:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
This stack overflow question talks about how to run Python that's
stored in another file
How can I make one python file run another?
I recommend wrapping the code you want to run in a function, e.g.
def foo():
print 'hello'
and then saving this in foo.py. From your main script, you can then do:
import foo
i = 0
while i < 10:
foo.foo()
i += 1
If you want to run something in an infinite loop, you need the condition for the while loop to always be true:
while True:
# do thing forever
A note on importing: The example I have given will work if the foo.py file is in the same directory as the main Python file. If it is not, then you should have a read here about how to create Python modules http://www.tutorialspoint.com/python/python_modules.htm

pycharm track 'print' output in debug mode

I am new to python and pycharm.
I am writing a program that takes years to run, so I want to see the iteration number while debugging.
this is my code:
import urllib2
for i in range(n):
print i
responses[i]=u2.urlopen(urls[i])
(I have an array of n urls)
so, when I run it I see the outputs:
0
1
2
3
etc
but when I am debugging I don't see the output.
any idea anyone?
Its a simple code block and there should not be any problem with Pycharm debugger. I suggest to use latest PyCharm version 5.0.
Right click on your python file and select 'Debug yourPythonFile.py'.It should print value of i.
Just a small suggestion, use (responses.append(u2.urlopen(urls[i])) instead of responses[i]=u2.urlopen(urls[i])

Run .py file until specified line number

In a linux terminal typing
python script.py
Will run run script.py and exit the python console, but what if I just want to run a part of the script and leave the console open? For example, run script.py until line 15 and leave the console open for further scripting. How would I do this?
Let's say it's possible, then with the console still open and script.py run until line 15, can I then from inside the console call line fragments from other py files?
...something like
python script.py 15 #(opens script and runs lines 1-15 and leaves console open)
Then having the console open, I would like to run lines 25-42 from anotherscript.py
>15 lines of python code run from script.py
> run('anotherscript.py', lines = 25-42)
> print "I'm so happy the console is still open so I can script some more")
I'm so happy the console is still open so I can script some more
>
Your best bet might be pdb, the Python debugger. You can start you script under pdb, set a breakpoint on line 15, and then run your script.
python -m pdb script.py
b 15 # <-- Set breakpoint on line 15
c # "continue" -> run your program
# will break on line 15
You can then inspect your variables and call functions. Since Python 3.2, you can also use the interact command inside pdb to get a regular Python shell at the current execution point!
If that fits your bill and you also like IPython, you can check out IPdb, which is a bit nicer than normal pdb, and drops you into an IPython shell with interact.
if you want to run script.py from line a to line b, simply use this bash snippet:
cat script.py|head -{a+b}|tail -{b-a}|python -i
replace {a+b} and {b-a} with their values
You could use the python -i option to leave the console open at the end of the script.
It lets your script run until it exits, and you can then examine variables, call any function and any Python code, including importing and using other modules.
Of course your script needs to exit first, either at the end or, if your goal is to debug that part of the script, you could add a sys.exit() or os._exit() call where you want it to stop (such as your line 15).
For instance:
import os
print "Script starting"
a=1
def f(x):
return x
print "Exiting on line 8"
os._exit(0) # to avoid the standard SystemExit exception
print "Code continuing"
Usage example:
python -i test_exit.py
Scrit starting
Exiting on line 8
>>> print a
1
>>> f(4)
4
>>>
You cannot do that directly but you can do something similar from inside Python console (or IDLE) with exec :
just open you favorite Python console
load wanted lines into a string and exec them :
script = 'script.py'
txt = ''
with open(script) as sc:
for i, line in enumerate(sc):
if i >= begline and i<= endline:
txt = txt + line
exec(txt)
You can even write your own partial script runner based on that code ...
EDIT
I must admit that above answer alone really deserved to be downvoted. It is technically correct and probably the one that most closely meet what you asked for. But I should have warned you that it is bad pratice. Relying on line numbers to load pieces of source files is error prone and you should avoid it unless you really know what you are doing and why you do it that way. Python debugger at least allows you to control what are the lines you are about to execute.
If you really have to use this solution be sure to always print and double check the lines that you are about to execute. IMHO it is always both simpler and safer to copy and past lines in an IDE like IDLE that is packaged into any standard Python installation.

Categories

Resources