Python Forum
Different outputs in Python2 and Python3 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Different outputs in Python2 and Python3 (/thread-3608.html)



Different outputs in Python2 and Python3 - MikeHill - Jun-06-2017

Hi All,
I am new to coding
When I run the following code in python2 and python3 I get different outputs
Can someone please explain this phenomenon

>>> a = [1,2,3,4,"hello"]
   >>> for i in a:
   ...     try:
   ...             print(i)
   ...             i+1
   ...             print (("i is : %d") %(i))
   ...     except:
   ...             print ("nope " + i + " is a string")


**Python 2 output**

   1
   2
   i is : 1
   2
   3
   i is : 2
   3
   4
   i is : 3
   4
   5
   i is : 4
   hello
   nope hello is a string

**Python 3 output**

   1
   i is :  1
   2
   i is :  2
   3
   i is :  3
   4
   i is :  4
   hello
   nope hello is a string



RE: Different outputs in Python2 and Python3 - nilamo - Jun-06-2017

(Jun-06-2017, 07:46 PM)MikeHill Wrote:    ...             i+1
That line does nothing, which leads me to believe that it isn't actually the same script you're running with both versions of python.


RE: Different outputs in Python2 and Python3 - Ofnuts - Jun-07-2017

(Jun-06-2017, 08:04 PM)nilamo Wrote:
(Jun-06-2017, 07:46 PM)MikeHill Wrote:    ...             i+1
That line does nothing, which leads me to believe that it isn't actually the same script you're running with both versions of python.
It triggers the exception if i is not a number.


RE: Different outputs in Python2 and Python3 - Ofnuts - Jun-07-2017

(Jun-06-2017, 07:46 PM)MikeHill Wrote: Hi All,
I am new to coding
When I run the following code in python2 and python3 I get different outputs
Can someone please explain this phenomenon

>>> a = [1,2,3,4,"hello"]
   >>> for i in a:
   ...     try:
   ...             print(i)
   ...             i+1
   ...             print (("i is : %d") %(i))
   ...     except:
   ...             print ("nope " + i + " is a string")


**Python 2 output**

   1
   2
   i is : 1
   2
   3
   i is : 2
   3
   4
   i is : 3
   4
   5
   i is : 4
   hello
   nope hello is a string

**Python 3 output**

   1
   i is :  1
   2
   i is :  2
   3
   i is :  3
   4
   i is :  4
   hello
   nope hello is a string

I get the same output (that looks like your Python2 output) with both versions. I use the plain interpreter for both versions. Obviously your Python3 interactive interpreter doesn't display the result of unassigned expressions (i+1) when they happen in the middle of other code. This is possible. If you put your code in a file and run it with either version, you won't get these lines either because displaying the result of unassigned expressions only happens in interactive execution.