Is there a workaround to create a Constant in Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Is there a workaround to create a Constant in Python?

It might be sth. like myname = ("Frogged", ) print(*myname * 3) but it fails for numeric types https://code.sololearn.com/c1JlfSxtGEbp/?ref=app

21st Apr 2021, 6:50 PM
Oma Falk
Oma Falk - avatar
5 Answers
21st Apr 2021, 7:16 PM
Coding Cat
Coding Cat - avatar
+ 2
Python doesn't have constants. There is only a convention to write them in upper case and not to change those. Wrapping them in a tuple prevents changes as your code shows, but complicates usage a little
21st Apr 2021, 7:30 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 2
Lisa That was my idea too at first but it still can be modified. Then I've read about defining a function on stackoverflow. Not very elegant, but it does the job i.e. workaround: https://code.sololearn.com/cVZpz6PUv77p/?ref=app
22nd Apr 2021, 6:04 PM
Mihai Apostol
Mihai Apostol - avatar
12th Aug 2022, 10:08 AM
Mihai Apostol
Mihai Apostol - avatar
+ 1
What about creating an extra file for the constants and then importing your "constants" from there? # In an extra myconst.py MYNAME = "Lisa" # then in script: from my constant import MYNAME print(MYNAME)
22nd Apr 2021, 5:50 PM
Lisa
Lisa - avatar