Joe Mas
Joe Mas

Reputation: 21

Help me make my Python 2 code work in Python 3

import math,sys,time;i=0
while 1: sys.stdout.write("\r"+':(_​_)'[:3+int(round(math.sin(​i)))]+'n'+':(__)'[3+int(ro​und(math.sin(i))):]);sys.s​tdout.flush();time.sleep(.​15);i+=0.5*math.pi

I wrote that simple program in Python 2 a long time ago and it worked fine but it has syntax errors in Python 3. I would greatly appreciate if someone could help me update it to be Python 3 compliant. Thanks.

Upvotes: 1

Views: 226

Answers (4)

Chris Gregg
Chris Gregg

Reputation: 2382

Indeed, @agf is correct. There was a weird character between the underscores in the first (__). Corrected (and works fine with Python 3):

import math,sys,time;i=0
while 1: sys.stdout.write("\r"+':(__)'[:3+int(round(math.sin(i)))]+'n'+':(__)'[3+int(round(math.sin(i))):]);sys.stdout.flush();time.sleep(.15);i+=0.5*math.pi

Upvotes: 1

unutbu
unutbu

Reputation: 880807

I pasted your code in a file, saved it, then opened it in a Python shell:

In [10]: f=open('test2.py')

In [11]: content=f.read()

In [12]: content
Out[12]: '#!/usr/bin/env python\n# coding: utf-8\n\nimport math,sys,time;i=0\nwhile 1: sys.stdout.write("\\r"+\':(_\xe2\x80\x8b_)\'[:3+int(round(math.sin(\xe2\x80\x8bi)))]+\'n\'+\':(__)\'[3+int(ro\xe2\x80\x8bund(math.sin(i))):]);sys.s\xe2\x80\x8btdout.flush();time.sleep(.\xe2\x80\x8b15);i+=0.5*math.pi\n'

Notice the '\xe2\x80\x8b' bytes sprinkled here and there. These are ZERO WIDTH SPACE characters encoded in utf-8:

In [24]: print(repr(u'\N{ZERO WIDTH SPACE}'.encode('utf-8')))
'\xe2\x80\x8b'

This is why your code is giving rise to SyntaxErrors.

Just retype it (or copy the code below) and it will run in Python3:

import math, sys, time; i=0
while 1: sys.stdout.write('\r'+':(__)'[:3+int(round(math.sin(i)))]+'n'+':(__)'[3+int(round(math.sin(i))):]); sys.stdout.flush(); time.sleep(0.15); i+=0.5*math.pi

Upvotes: 4

agf
agf

Reputation: 176960

The problems has nothing to do with your Python version. You've got weird characters in your code.

I pasted it in Metapad and a bunch of ? showed up, I assume meaning unprintable character.

Just retype it and it will work fine, or find a text editor which will show those characters and delete them, or use Python to delete any non-printable characters.

Upvotes: 1

AI Generated Response
AI Generated Response

Reputation: 8845

Use 2to3 on your python installation. It comes standard (I think) with 2.7.2+

Upvotes: 0

Related Questions