I'm a beginner in python and using v2.7.2 here's what i tried to execute in the command prompt
p = 2
while(p>0):
for i in range(10):
print i+1 , p
p-=1
The expected output was
1 2
2 1
However the actual output is
1 2
2 1
3 0
4 -1
5 -2
6 -3
7 -4
8 -5
9 -6
10 -7
Why does this happen? and How do i achieve the expected behavior?
Python code is translated into intermediate code, which has to be executed by a virtual machine, known as the PVM, the Python Virtual Machine. This is a similar approach to the one taken by Java. There is even a way of translating Python programs into Java byte code for the Java Virtual Machine (JVM).
To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program from running. It is the most reliable, cross-platform way of stopping code execution.
In short, “pythonic” describes a coding style that leverages Python's unique features to write code that is readable and beautiful.
However, Python interpreter runs the code right from the first line. The execution of the code starts from the starting line and goes line by line.
The while condition is only tested again after the for loop finishes. You could do this instead
p = 2
for i in range(10):
if p <= 0:
break
print i+1 , p
p-=1
This is the output I get:
1 2
2 1
3 0
4 -1
5 -2
6 -3
7 -4
8 -5
9 -6
10 -7
Your question as to why it runs. Your outer most conditional is a while
loop, which is true upon the first execution, however it runs right into a nested for loop. When this happens the while
, will not be checked until the for
loop finishes its first execution (which is why p = -7).
What you want is this:
p = 2
for i in range(10):
if p <= 0:
break
print i+1 , p
p-=1
which gives output:
1 2
2 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With