Why does pylint think this variable is a constant?

I have tried different ways but still does not seem to work.

On any execution of that if block, final_grade is only given a value once, and never changed thereafter.

I would iterate down over the grades and cutoffs in the same order, and return the first, highest one for which the score is higher (>=) than the cutoff. The values could even be read in from whoever decides where the grade boundaries are. This way you don’t need to change your code when the examination board carries out normalisation.

Otherwise it would benefit from being wrapped in a function with each final_grade = replaced with return. The elifs could then be made into ifs, and the else removed too, if preferred.

2 Likes

Thank you very much! I will try as you have stated.

I personally think pylint’s idea of a Constant is overly broad and I would turn off rule C0103 at least for that block. (But I am not sure of the comment syntax for doing that._

4 Likes

Pylint still complains even if you do change the value of final_grade later. There seems to be no analysis beyond “a literal value is assigned to this name, so it must be a constant”.

1 Like

Oh, my mistake. Maybe it’s because final_grade is in global scope. Global variables are famous code smells. Wrapping it in a main function makes pylint happy:

"""
Docstring
"""

def main():
    """
    Docstring
    """
    score = float(input("Input score: "))

    if 0 <= score <= 1.0:
        if score >= 0.5:
            final_grade = "Pass"
        else:
            final_grade = "Fail"

        print(f'{final_grade=}')

if __name__ == '__main__':
    main()

>uvx pylint const_pylint.py

-------------------------------------------------------------------
Your code has been rated at 10.00/10 (previous run: 8.89/10, +1.11)

2 Likes