-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuilt_in_function.py
More file actions
747 lines (504 loc) · 14.7 KB
/
Built_in_function.py
File metadata and controls
747 lines (504 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
'''
abs() in Python:
abs() ek built-in function hai jo kisi number ka absolute value return karta hai.
Agar number positive hai → wohi number return hoga.
Agar number negative hai → uska positive version return hoga.
'''
x = 5
y = 10
result = abs(x -y)
print(result)
print()
'''
all() in Python: AND
all() ek built-in function hai jo iterable (list, tuple, set, etc.) check karta hai.
Agar saray elements True hain → True return karega.
Agar koi ek bhi False ho → False return karega.
Agar iterable empty ho → True return karega.
'''
# Example 1: List of booleans
l = [True, True, True]
print(all(l))
l1 = [True, False, True]
print(all(l1))
# Example 2: Numbers
# Python mein 0 = False aur non-zero = True
l = [0, 1, 3]
print(all(l))
l = [2, 1, 3]
print(all(l))
# Example 3: Strings
# Empty string = False, non-empty string = True
print(all(["Ali", "Sara", ""]))
print(all(["Ali", "Sara", "Ahmed"]))
print()
'''
any() in Python: OR
any() bhi ek built-in function hai jo iterable (list, tuple, set, etc.) check karta hai.
Agar koi ek element bhi True ho → True return karega.
Agar saray elements False ho → False return karega.
Agar iterable empty ho → False return karega.
'''
print(any([False, False, True])) # True (kyunki ek True hai)
print(any([False, False, False])) # False (sab False)
print(any([0, 0, 5])) # True (5 non-zero hai)
print(any([0, 0, 0])) # False (sab 0 hain)
print(any(["", "", "Hello"])) # True (ek string non-empty hai)
print(any(["", "", ""])) # False (sab empty strings)
# text = "Python ♥"
# print(ascii(text)) Output: 'Python \u2665'
print()
'''
bin() Function in Python
bin() ka kaam hota hai kisi integer ko binary string me convert karna.
'''
print(bin(5))
print(bin(10))
print(bin(255))
# 10 / 2 = 5 reminder 0
# 5 / 2 = 2 reminder 1
# 2 / 2 = 1 reminder 0
# 1 / 2 = 0 reminder 1
# count from end 1010
print()
'''
bytearray() kya karta hai?
Python mein bytearray() ek list jaisa box banata hai jisme sirf bytes (0–255 numbers) rakhe ja sakte hain.
Ye mutable hai → matlab aap iske andar values change kar sakte ho.
bytes -> immutable hota hy
'''
# Example 1: Simple banate hain
arr = bytearray([65, 66, 67])
print(arr)
print(arr.decode())
# 👉 65 = A, 66 = B, 67 = C (ASCII codes).
# Example 3: Change karna
arr = bytearray(b"HI")
arr[0] = 65
print(arr)
print(arr.decode())
print()
'''
callable() in Python:
callable() ek built-in function hai.
Ye check karta hai ke koi object function ki tarah call ho sakta hai ya nahi.
Agar object ko () (brackets) laga kar call kar sakte ho → True.
Agar call nahi kar sakte → False.
'''
# Example 1: Normal function
def hello():
return "HI"
print(callable(hello))
print(callable(5))
print()
# Example 2: Class
class MyClass:
pass
print(callable(MyClass))
obj = MyClass() # yeh call hai
print(callable(obj)) # False (object ko call nahi kar sakte)
print()
# Example 3: Special __call__ method
# Agar class ke andar __call__ method likh do,
# to uska object bhi callable ban jaata hai:
class MyClass:
def __call__(self):
return "Object called!"
print(callable(MyClass))
obj = MyClass()
print(callable(obj)) # True (kyunki __call__ hai)
print()
'''
chr() in Python:
chr() ek built-in function hai.
Ye ek number (Unicode code point) ko uska character bana deta hai.
'''
print(chr(65)) # A
print(chr(66)) # B
print(chr(97)) # a
print(chr(36)) # $
print(chr(64)) # @
print(chr(35)) # #
print(chr(8364)) # €
print(chr(128512)) # 😀
print()
'''
classmethod() in Python:
classmethod() ek built-in decorator hai (@classmethod).
Ye function ko class se bind karta hai, object se nahi.
Matlab: is method ko class ke through bhi call kar sakte ho, aur object ke through bhi.
Pehla parameter hamesha cls hota hai (class ko represent karta hai), jaise self object ko karta hai.
'''
class Student:
school = "ABC School"
def __init__(self,name):
self.name = name
# normal method
def show(self):
return f"Student: {self.name}, School: {Student.school}"
@classmethod
def change_school(cls, new_school):
cls.school = new_school
s1 = Student("Ali")
print(s1.show()) # Student: Ali, School: ABC School
# Class method call through class
Student.change_school("XYZ School")
print(s1.show()) # Student: Ali, School: XYZ School
print()
'''
compile() in Python:
compile() ek built-in function hai.
string code ko Python ke samajhne layak banata hai (bytecode).
Bytecode wo hota hai jo Python internally run karta hai.
compile(source, filename, mode)
mode → teen options hote hain:
"exec" → multiple lines of code (statements)
"eval" → single expression
"single" → single interactive statement (jaise Python shell input).
'''
# Example 1: Using "eval"
x = 5
code = "x + 10"
compiled = compile(code, "", "eval")
print(eval(compiled))
# Example 2: Using "exec"
code = """
for i in range(3):
print("Hello", i)
"""
compiled = compile(code, "", "exec")
exec(compiled)
# Example 3: Using "single"
code = "print('Hi!')"
compiled = compile(code, "", "single")
exec(compiled)
print()
'''
Python ka round() ek built-in function hai jo numbers ko round off (gola karna) karne ke liye use hota hai.
number → jis number ko round karna hai
ndigits (optional) → kitne decimal places tak round karna hai (agar na do to default 0 hota hai)
Point ke baad 0.5 ya us se zyada ho to next number, warna pichla number.
Syntax:
round(number, ndigits)
'''
print(round(4.3))
print(round(4.6))
print(round(3.14159, 2)) # 3.14
print(round(2.71898, 3)) # 3 tk dekhny k bad agla digit 5 ze zayada hy to next value degy
print()
'''
max() : find the max no
min() : find the minimum
'''
print(max(10,121,34,56))
print(min(10,121,34,56))
print()
'''
sum() → list ka total sum
'''
print(sum([1, 3, 4, 5]))
print()
'''
len() → length (string, list, tuple, etc.)
'''
print(len([1, 3, 4, 5]))
print()
'''
type() → object ka type batata hai
'''
l = {'naam':"xeeshan", "kam":"insta reels dekhna"}
print(type(l))
print()
'''
str() kisi bhi number ya object ko string (text) mein convert karta hai.
'''
x = 2
y = 3
print(str(x + y))
print(type(str(x + y)))
print()
'''
int() → Integer Conversion:
int() kisi number ya string ko integer (whole number) mein convert karta hai.
Decimal part hata deta hai (round nahi karta, flooring karta hai).
String tabhi convert hogi agar usme sirf number ho.
'''
print(int(3.99)) # 3
print(int("42")) # 42
print(int(True)) # 1
print(int(False)) # 0
# print(int("42abc")) # ❌ Error
print()
'''
float() → Floating Point Conversion
float() kisi integer ya number-string ko decimal number (float) bana deta hai.
'''
print(float(5)) # 5.0
print(float("3.14")) # 3.14
print(float("10")) # 10.0
print()
'''
list() → List Conversion
Kisi bhi iterable (string, tuple, set, dict) ko list mein convert karta hai.
Dict ko list mein convert karne par sirf keys aati hain.
'''
print(list(("Xeeshan")))
print(list((1, 2, 4, 5))) # tupple
print(list({1, 2, 4, 5})) # set
print(list({"a": 1, "b": 2})) # dict
print()
'''
tuple() → Tuple Conversion
Kisi iterable ko tuple mein convert karta hai.
'''
print(tuple(("Xeeshan")))
print(tuple([1, 2, 4, 5])) # list
print(tuple({1, 2, 4, 5})) # set
print(tuple({"a": 1, "b": 2})) # dict
print()
'''
set() → Set Conversion:
Iterable ko set mein convert karta hai.
Duplicate values hata deta hai aur unordered hota hai.
'''
print(tuple(("Xeeshan")))
print(tuple([1, 2, 4, 5, 5])) # list
print(tuple((1, 2, 4, 5, 5))) # tuple
print(tuple({"a": 1, "b": 2})) # dict
print()
'''
dict() → Dictionary Conversion:
Special case: Dict banane ke liye input key-value pairs hone chahiye.
Iterable ke andar har element ek pair (2 values) hona zaroori hai.
'''
# List of Tuples → Dict
data = [("a", 1), ("b", 2)]
print(dict(data))
# List of Lists → Dict
data = [["x", 10], ["y", 20]]
print(dict(data))
# Tuple of Tuples → Dict
data = (("id", 101), ("name", "Ali"))
print(dict(data))
# Tuple of Lists → Dict
data = (["age", 25], ["city", "Lahore"])
print(dict(data))
# set of tuples
print(dict({("a", 1), ("b", 2)}))
# Example Mix:
data = (("id", 101),["age", 25])
print(dict(data))
print()
'''
Python ka isinstance() ek built-in function hai
jo check karta hai ke koi object kis class (ya data type) ka instance hai.
Syntax:
isinstance(object, classinfo)
object → jis variable ya value ko check karna hai
classinfo → class ya "data_type" jisme check karna hai (ek single type ho sakta hai, ya types ka tuple bhi de sakte ho)
'''
x = 5
print(isinstance(x, int)) # True
print(isinstance(x, float)) # False
print(isinstance("hello", str))# True
x = 3.14
print(isinstance(x, (int, float)))
class Animal:
pass
class Dog(Animal):
pass
d = Dog()
print(isinstance(d, Dog)) # True
print(isinstance(d, Animal)) # True (kyunki Dog ne Animal se inherit kiya hai)
print(isinstance(d, str)) # d ik dog hy string ni
print()
'''
Python ka id() ek built-in function hai jo kisi bhi object ka unique identity number
(memory address ka representation) return karta hai.
'''
x = 10
y = 10
print(id(x))
print(id(y))
# 👉 Dono ka id same hoga, kyunki Python optimization me small integers (-5 se 256 tak) ko memory me reuse karta hai.
print()
a = [1, 2, 3]
b = [1, 2, 3]
print(id(a))
print(id(b))
print()
a = [1, 2, 3]
b = a
print(id(a))
print(id(b))
# 👉 Dono ka id same hoga, kyunki b sirf a ka reference hai (dono ek hi list ko point kar rahe hain).
print()
'''
Python ka range() ek built-in function hai jo numbers ki sequence banata hai (step by step).
Ye aksar for loop ke sath use hota hai.
Syntax:
range(start, stop, step)
'''
# Sirf stop
for i in range(5):
print(i)
print()
# start aur stop
for x in range(2,11):
print(x)
print()
# start, stop, step
for x in range(2,10,2):
print(x)
print()
# Negative Step (reverse counting)
for x in range(10,0,-3):
print(x)
print()
# with list
print(list(range(5)))
print(list(range(2, 7)))
print(list(range(1, 10, 3)))
print()
'''
Python ka enumerate() ek built-in function hai
jo iteration ke time pe index + value dono deta hai
Syntax:
enumerate(iterable, start=0)
'''
# Without enumerate()
fruits = ['apple', 'banana', 'orange']
i = 0
for fruit in fruits:
print(i, fruit)
i += 1
print()
# With enumerate()
fruits = ['apple', 'banana', 'orange']
for i, fruit in enumerate(fruits, start=1): # by default 0 se start
print(i, fruit)
print()
# Example with String
for index, char in enumerate("HELLO", start=2):
print(index, char)
print()
'''
Python ka zip() ek built-in function hai jo
multiple iterables (list, tuple, etc.) ko element-wise combine karta hai
aur unka pair bana kar deta hai.
'''
names = ["Ali", "Sara", "John"]
ages = [25, 30, 22]
zipped = zip(names, ages)
print(list(zipped))
print()
# Different Length Lists
names = ["Xeeshan", "Eisa", "Dani","imran"]
ages = [25, 30]
print(list(zip(names, ages)))
print()
# With 3 Iterables
names = ["Ali", "Sara", "John"]
ages = [25, 30, 22]
cities = ["Lahore", "Karachi", "Multan"]
print(list(zip(names, ages, cities)))
print()
# Unzipping (zip * with star)
pairs = [('Ali', 25), ('Sara', 30), ('John', 22)]
letters, numbers = zip(*pairs)
print(letters)
print(numbers)
print()
# loop with zip
names = ["Ali", "Sara", "John"]
marks = [85, 90, 78]
for Name, Marks in zip(names,marks):
print(f"{Name} -> {Marks}")
print()
'''
Python ka map() ek built-in function hai jo ek function ko iterable (list, tuple, etc.) ke
har element par apply karta hai, aur ek iterator return karta hai.
Syntax:
map(function, iterable)
function → wo function jo har element par apply hoga
iterable → list, tuple, set, string etc.
Return → ek map object (iterator) → isko list(), tuple() ya loop ke through access karna padta hai
'''
# Square of Numbers
nums = [1, 2, 3, 4, 5]
squares = map(lambda x : x**2 , nums)
print(list(squares))
print()
# Convert Strings to Uppercase
names = ["xeshan", "imran", "eisa"]
uper_case = map(str.upper , names)
print(list(uper_case))
print()
# Multiple Iterables
# Agar function multiple arguments leta hai,
# to map() multiple iterables par bhi kaam kar sakta hai.
a = [1, 2, 3]
b = [4, 5, 6]
sums = map(lambda x,y : x + y, a,b)
print(list(sums))
print()
'''
Syntax:
slice(start, stop, step)
'''
# Normal Slice with list
nums = [10, 20, 30, 40, 50]
s = slice(1, 4)
print(nums[s])
print()
# Slice with Step
nums = [10, 20, 30, 40, 50, 60]
s = slice(0,6,2)
print(nums[s])
# Normally hum directly slicing operator (:) use karte hain:
nums = [10, 20, 30, 40, 50]
print(nums[1:4])
print(nums[0:6:2])
print()
'''
reversed() ek built-in function hai jo kisi bhi sequence (list, tuple, string, range, etc.)
ko ultee direction (reverse order) me iterate karne ke liye use hota hai.
Return → ek iterator jo sequence ke elements ko ulta (reverse) karke deta hai
'''
# List Reverse
nums = [10, 20, 30, 40, 50]
reserved = reversed(nums)
print(list(reserved))
# String Reverse
text = "PYTHON"
print("".join(reversed(text)))
# Agar list ko inplace reverse karna ho to:
nums = [4, 3, 2, 1]
nums.reverse() # inplace reverse
print(nums)
print()
'''
Python ka super() ek built-in function hai jo inheritance ke time use hota hai.
Ye parent class (superclass) ke methods/properties ko child class (subclass) ke andar access karne ke liye use hota hai.
'''
class Animal:
def speak(self):
print("Animal Speak")
class Dog(Animal):
def speak(self):
super().speak() # parent class ka method call
print("Dog barks")
obj = Dog()
obj.speak()
# __init__ ke sath
class Person:
def __init__(self, name):
self.name = name
print("Person init called")
class Student(Person):
def __init__(self, name, roll_no):
super().__init__(name)
self.Roll_no = roll_no
print("Student init called")
s = Student("Ali", 101)
print(s.name, s.Roll_no)