Python Forum

Full Version: Different outputs in Python2 and Python3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
(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.
(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.
(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.