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

Python Variables

एक variable एक लेबल लगे डिब्बे की तरह है जिसमें आप जानकारी रखते हैं। आप डिब्बे में कुछ रख सकते हैं, उसे देख सकते हैं, या बाद में उसे किसी नई चीज़ से बदल सकते हैं।
Syntax
python
variable_name = value
variable_a, variable_b = value_a, value_b

Variable Assignment

Statically-typed भाषाओं के विपरीत, Python को अलग declaration step नहीं चाहिए — age = 25 लिखना एक ही line में variable age बनाता भी है और उसे value भी देता है, और interpreter value से ही उसका type समझ लेता है।

उदाहरण: Variable Assignment

python
age = 25
print(age)

Variables में Dynamic Typing

क्योंकि Python variables किसी निश्चित type से बँधे नहीं होते, वही नाम एक line में integer और कुछ lines बाद string रख सकता है, बिना किसी विशेष syntax के — variable अब बस उसी को दर्शाता है जो सबसे नए assignment ने तय किया।

उदाहरण: Dynamic Typing in Variables

python
value = 10  # value is currently an integer
print(value)
value = "ten"  # same name reassigned to a string, no error
print(value)

कई Variables

a, b, c = 1, 2, 3 लिखना तीनों variables को एक ही statement में assign करता है, जो कई संबंधित values को एक साथ initialize करने का आम, पठनीय तरीका है, तीन अलग assignment lines लिखने के बजाय।

उदाहरण: Multiple Variables

python
a, b, c = 1, 2, 3
print(a, b, c)

Local बनाम Global Variables

किसी function के अंदर बना variable केवल उसी function के local scope में मौजूद रहता है और function के लौटते ही गायब हो जाता है; किसी function के बाहर बने variables global होते हैं और हर जगह दिखते हैं।

Function के अंदर global keyword का उपयोग आपको उस बाहरी variable को दोबारा assign करने देता है, बजाय इसके कि गलती से नया local variable बन जाए।

उदाहरण: Local vs. Global Variables

python
count = 0  # global variable

def increment():
    global count  # refer to the outer count instead of creating a local one
    count += 1

increment()
print(count)

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

पूरे, वर्णनात्मक नाम चुनिए (tp की जगह total_price) ताकि पाठक को यह पीछे खोजे बिना कि variable पहली बार कहाँ assign हुआ, उसका उद्देश्य समझ आ जाए — script कुछ दर्जन lines से आगे बढ़ने पर इसका बहुत फ़ायदा मिलता है।

उदाहरण: Best Practices for Variables

python
total_price = 49.99
print(total_price)
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.