Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Functions and Looping Expecting Exceptions

i got this error ImportError: bad magic number in 'math': b'\x03\xf3\r\n'

in this code

import math

def split_check(total, number_of_people):
    return math.ceil(total / number_of_people)

total = float(input("What is the total? "))
number_of_peoples = int(input("How many poeple? "))

amount_due = split_check(total,number_of_peoples)
print("Each person owns ${}".format(amount_due))

i got this error

    import math
ImportError: bad magic number in 'math': b'\x03\xf3\r\n'

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

Hey Anshuman Nag, very interesting question!

The bad magic number refers to the number encoded in the compiled .pyc files to indicate Python version:

>>> int.from_bytes(b'\x03\xf3', "little")
62211

Then decode from here, says the math.pyc file was compiled using Python 2.7.

Your virtual environment might be incorrect (running Python 3.x but seeing Python 2.7 libs), or you might need to remove the .pyc files (possibly in __pycache__ directory) and rerun.

To inspect the magic number in a pyc file, you can use:

>>> path_to_file = '__pycache__/dice_hand_file.cpython-38.pyc'
>>> with open(path_to_file, 'r+b') as f:
...     magic = f.read(2)
... 
>>> magic
b'U\r'
>>> int.from_bytes(magic, "little")
3413

# python 3.8 b4

Post back if you need more help. Good luck!!

should i update my python version?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,457 Points

The answer is more complicated. It depends knowing why the python version and the pyc file versions differ.

What is your setup?

  • which OS are you using?
  • how do you invoke python?
  • what does python --version return?
  • are you using a virtual environment?