Reputation: 51
Would student_name
be a constant or not?
student_name = ""
while len(student_name) > 1:
int(input(User input name of student and store this in variable student_name))
Upvotes: 2
Views: 55
Reputation: 43495
It depends on what you would call a constant. Python has immutable objects. like strings. Remember that in Python variables are basically labels on objects. So if you write
x = 'foo'
the label x
is used for the immutable string 'foo'
. If you then were to do
x = 'bar'
you haven't changed the string, you've just hung the label on a different string.
But immutable objects are not what we generally think of as constants. In Python a constant could be thought of as an immutable label; a variable (label) that cannot be changed once it is assigned.
Until recently, Python didn't really have those. By convention, an all-uppercase name signals that it shouldn't be changed. But this isn't enforced by the language.
But since Python 3.4 (and also backported to 2.7) we have the enum
module that defines different kinds of enumeration classes (singletons really). An enumeration can basically be used as group of constants.
Here is an example where a function to compare files returns an enum;
from enum import IntEnum
from hashlib import sha256
import os
# File comparison result
class Cmp(IntEnum):
differ = 0 # source and destination are different
same = 1 # source and destination are identical
nodest = 2 # destination doesn't exist
nosrc = 3 # source doesn't exist
def compare(src, dest):
"""
Compare two files.
Arguments
src: Path of the source file.
dest: Path of the destination file.
Returns:
Cmp enum
"""
xsrc, xdest = os.path.exists(src), os.path.exists(dest)
if not xsrc:
return Cmp.nosrc
if not xdest:
return Cmp.nodest
with open(src, 'rb') as s:
csrc = sha256(s.read()).digest()
if xdest:
with open(dest, 'rb') as d:
cdest = sha256(d.read()).digest()
else:
cdest = b''
if csrc == cdest:
return Cmp.same
return Cmp.differ
This saves you having to look up what the return value of compare
actually means every time you use it.
You cannot change existing attributes of the enum
after it has been defined. There is one surprise here; you can add new attributes later, and those can be changed.
Upvotes: 2
Reputation: 1057
No there is not. You cannot declare a variable or value as constant in Python. Just don't change it.
If you are in a class, the equivalent would be:
class Foo(object):
CONST_NAME = "Name"
if not, it is just
CONST_NAME = "Name"
The following code snippet might help you Link .
Upvotes: 0