This happens when your script is being run by a shell, not a Python interpreter at all.
Put a shebang on the first line of the script:
…or, as appropriate,
…to specify to the operating system that it should be run with a Python interpreter.
You may indeed need to install some 3rd-party packages, but you’ll get an error specific to the imports that fail after fixing your interpreter; at that point you can use either the same package manager you used to install Python 3 (if it was installed via MacPorts or Homebrew or similar), or use PyPi, virtualenv, or similar.