पाठ 6 / 49
डेटा टाइप्स
Python के मुख्य types के साथ काम करें: int, float, str, bool और None, साथ में lists, tuples, sets व dictionaries।
स्केलर
int (असीमित), float, complex, str (अपरिवर्तनीय), bool, और None।
चार कलेक्शन
list परिवर्तनीय/क्रमित · tuple अपरिवर्तनीय · set अद्वितीय/अक्रमित · dict की→मान।
nums = [1, 2, 3]
nums.append(4)
point = (10, 20)
tags = {"a", "b"}
person = {"name": "Ada", "age": 36}
person["age"] # 36संख्याएँ और बूलियन
int की कोई सीमा नहीं, float 64-बिट दशमलव का सन्निकटन है (इसलिए 0.1 + 0.2 ठीक 0.3 नहीं होता), और bool, int का उपवर्ग है जहाँ True == 1।
big = 2 ** 100 # int never overflows
price = 19.99 # float
active = True # bool
0.1 + 0.2 # 0.30000000000000004
True + True # 2
7 // 2, 7 % 2, 7 / 2 # (3, 1, 3.5)टाइप जाँचना: type() और isinstance()
type(x) सटीक टाइप बताता है; isinstance(x, T) को प्राथमिकता दें क्योंकि यह उपवर्गों को भी स्वीकार करता है।
type(42) # <class 'int'>
type("hi") # <class 'str'>
isinstance(3.5, float) # True
isinstance(True, int) # True (bool is an int)
isinstance(3, (int, float)) # True: any of several typesटाइप रूपांतरण
int(), float(), str() और bool() से स्पष्ट रूपांतरण करें। ग़लत इनपुट पर ValueError आता है। खाली मान (0, "", [], None) falsy होते हैं।
int("42") # 42
float("3.14") # 3.14
str(7) # "7"
int(3.9) # 3 (truncates, does not round)
bool("") # False
bool("0") # True (non-empty string)
int("abc") # ValueErrorत्वरित जाँच: int(3.9) क्या लौटाता है?
- 4
- 3
- 3.9
- ValueError
Answer
3 — int() शून्य की ओर काटता है; राउंड करने के लिए round() उपयोग करें।
त्वरित जाँच: कौन-सा कलेक्शन अपरिवर्तनीय है?
- list
- dict
- tuple
- set
Answer
tuple — tuple बनने के बाद बदला नहीं जा सकता।