[Tex/LaTex] Issue with special characters in Python code

pythonsymbolsverbatim

I am trying to insert a Python code into a LaTeX document. The Python code (an example) is the following and contains many special characters (>, <, °):

valeur = input('Veuillez entrer une valeur numérique ° : ')

if '.' in valeur
    print('Hourra')

        if x<0 or x>10:

Here is a MWE:

\documentclass{article}

\usepackage[latin1]{inputenc} 
\usepackage[T1]{fontenc} 
\usepackage[francais]{babel} 

\usepackage{fancyvrb}

\begin{document}

\inputencoding{utf8}
\begin{otherlanguage*}{english}
\VerbatimInput[frame=single, numbers=left, numbersep=2pt]{test.py}
\end{otherlanguage*}
\inputencoding{latin1}

\end{document}

Because of the special characters, I am getting this error:

enter image description here

How can I fix it?

This question is closely related to the post Issue with accents from Python source code but it is no duplicate since I was dealing with accents and now I am seemingly dealing with mathematical symbols used outside math mode…

The answer to Issue with accents from Python source code does not solve my current problem.

Best Answer

You have to declare that you want to use UTF-8. For the degree symbol you also need textcomp.

\documentclass{article}

\usepackage[T1]{fontenc} 
\usepackage[utf8,latin1]{inputenc}  % last one is default
\usepackage[english,francais]{babel}
\usepackage{textcomp}

\usepackage{fancyvrb}

\begin{document}

\inputencoding{utf8}
\begin{otherlanguage*}{english}
\VerbatimInput[frame=single, numbers=left, numbersep=2pt]{test.py}
\end{otherlanguage*}
\inputencoding{latin1}

\end{document}

enter image description here

Why not using UTF-8 also for the other files?