← Back to Python Course | Chapter 1: Basics | Lesson 10 of 14

Python Constants

एक constant वह value है जिसे आप कभी न बदलने का वादा करते हैं, जैसे आपकी जन्मतिथि। Python इसे lock नहीं करता, इसलिए हम इसका नाम बड़े अक्षरों (capital letters) में लिखते हैं ताकि याद रहे कि इसे छेड़ना नहीं है।
Syntax
python
CONSTANT_NAME = value  # UPPER_CASE by convention

वैचारिक Constants

Python में कोई समर्पित const keyword नहीं है — परंपरा के अनुसार, developers किसी variable को ALL_CAPS में नाम देते हैं (जैसे MAX_RETRIES) ताकि दूसरे पाठकों को संकेत मिले कि "इस value को बदलना नहीं है," भले ही interpreter खुद आपको इसे दोबारा assign करने से न रोके।

उदाहरण: Conceptual Constants

python
MAX_RETRIES = 5
print(MAX_RETRIES)
MAX_RETRIES = 10  # interpreter allows this even though the name signals "don't change me"
print(MAX_RETRIES)

Constant Modules

संबंधित constants को config.py जैसे अलग module में समूहित करना और जहाँ ज़रूरत हो वहाँ import करना, सेटिंग्स को एक ही जगह केंद्रित रखता है, इसलिए API URL जैसी value बदलने का मतलब पूरे codebase में खोजने की बजाय एक line edit करना होता है।

उदाहरण: Constant Modules

python
# config.py would hold:
# API_URL = "https://api.example.com"
# Importing it elsewhere: from config import API_URL
API_URL = "https://api.example.com"
print(API_URL)

Numeric Constants

बार-बार आने वाले संख्यात्मक literal को नाम देना — जैसे अपने code में जगह-जगह बिखरे 100 की जगह MAX_USERS = 100 — बिना समझाई "magic number" को खुद-समझाने वाला नाम बना देता है और भविष्य के बदलाव को एक line का edit बना देता है।

उदाहरण: Numeric Constants

python
MAX_USERS = 100
print(f"Server allows up to {MAX_USERS} users")

String Constants

error messages, status labels या welcome banner जैसे निश्चित text values नामित string constants के अच्छे उम्मीदवार हैं, क्योंकि एक ही string को कई जगह hardcode करने पर खतरा रहता है कि एक को edit करने और बाकियों को न करने पर प्रतियाँ आपस में मेल खोने लगें।

उदाहरण: String Constants

python
ERROR_NOT_FOUND = "Resource not found"
print(ERROR_NOT_FOUND)

Constants के सर्वोत्तम तरीके

सभी constant परिभाषाओं को file के ऊपर, बाकी logic से पहले रखना उन्हें ढूँढना और बदलना आसान बनाता है, असंबंधित code में scroll किए बिना — एक छोटी परंपरा जिसका फ़ायदा उसी क्षण मिलता है जब किसी और को file maintain करनी पड़े।

उदाहरण: Best Practices for Constants

python
MAX_RETRIES = 3  # constants defined near the top of the file
TIMEOUT_SECONDS = 30

def connect():
    print("Connecting with timeout", TIMEOUT_SECONDS)

connect()
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.