I have read that python generates a .pyc file when we execute a python script for the first time and stores it in a _pycache directory but what will happen if python script has an error at some line. will it generate bytecode?
Python never deletes a cache (bytecode) file, so if it gets written it stays.  It gets written after compilation (if there are no SyntaxErrors) and before execution—even before finding out that, say, an import foo on the first line refers to a nonexistent module.
So you can almost say that the file is written unless a SyntaxError is raised, except that other things can raise that: an import inside the first module, an exec/eval/compile, or an explicit raise.  It is possible to distinguish these programmatically if needed by counting traceback frames to see if the (first) module ever began execution.
what happens if a python program contains an error, will it generate a .pyc file?