Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why does this code execute?

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?

like image 776
Josyula Krishna Avatar asked Jun 28 '13 11:06

Josyula Krishna


People also ask

How does Python code execute?

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).

How do I stop a Python executing?

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.

What makes a code Pythonic?

In short, “pythonic” describes a coding style that leverages Python's unique features to write code that is readable and beautiful.

Where does the Python code start executing from?

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.


2 Answers

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
like image 142
John La Rooy Avatar answered Oct 13 '22 20:10

John La Rooy


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
like image 43
Woot4Moo Avatar answered Oct 13 '22 22:10

Woot4Moo