Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Constant variables

Hello! I see that if I want to create a constant variable I have to write it in capital letters. The problem is that the code doesn't work as expected, as it lets me change the value for that constant variable:

import sys
PASSWORD_MASTER='123456789'
password=input("Please enter the password: ")
nr=0
while password!=PASSWORD_MASTER:
    if nr==3:
        sys.exit("Account locked. Please contact Customer Service.")
    print("[Attempt number {}]".format(nr+1))
    password=input("Invalid password, please try again: ")
    nr+=1
    PASSWORD_MASTER=PASSWORD_MASTER+'1'

print("Welcome to secret town!")

If I run this code, there is no error message and the program keeps adding 1 to PASSWORD_MASTER. Aren't the constant variables supposed to remain the same during the entire program? If we can change them, what's the point of using them in the first place? Thank you so much in advance!

2 Answers

mouseandweb
mouseandweb
13,758 Points

they are not constant variables, variables are by definition not constant. Constants are not variable, by definition. In Python there is a convention to treat a variable like a constant by naming the variable with all caps. The only thing keeping this variable constant is you! So if you want a constant, give a variable a name with all caps and don't change the value! All caps helps others understand that you meant to treat that variable as a constant. It may also help in 'translating' your code from python to another that has constants.

Brandon White
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brandon White
Full Stack JavaScript Techdegree Graduate 35,771 Points

Hi mouseandweb,

I changed your comment to an answer, because that’s exactly what this is (hopefully, that’s OK by you).

Ondina,

mouseandweb is exactly right. Albeit in some languages (like Javascript) declaring a variable as a constant lets the interpreter—or compiler for the language—throw an error when of some other piece of code tries to change its value, Python is not like that. I believe Python probably takes the convention of using all caps for constants from C, but it’s up to the user to make sure to follow through.

Great response, mouseandweb. Good question, Ondina.

mouseandweb
mouseandweb
13,758 Points

Brandon White,

Yes that is definitely ok by me and thank you!