[Tex/LaTex] Color of Python Comment Keywords in Latex

python

if have the following problem.

I have to insert Python Code in Latex.
I copied a nice code for Latex which creates a good looking Python output for my purposes.

Now I have the problem that I defined a certain color for programming keywords like "for, and,…"
But Latex, of course, displays also the and's and for's that I used in the comment section in Python after the # sign in this color.
Is there any way to change this?

Best

Felix

enter image description here

Best Answer

Use \lstset. Here is a MWE:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{keywords}{RGB}{255,0,90}
\definecolor{comments}{RGB}{0,0,113}
\definecolor{red}{RGB}{160,0,0}
\definecolor{green}{RGB}{0,150,0}

\begin{document}

\lstset{language=Python, 
        basicstyle=\ttfamily\small, 
        keywordstyle=\color{keywords},
        commentstyle=\color{comments},
        stringstyle=\color{red},
        showstringspaces=false,
        identifierstyle=\color{green},
        keywords=[2]{pow},
        keywordstyle=[2]{\color{orange}},
}

\begin{lstlisting}
#This is a comment with keywords: and or for in range
n = 5
for i in range(0, n): 
    print( pow(i,3) )
#Over and out
\end{lstlisting}    

\end{document}

The above code will give you this: enter image description here