Skip to content

Commit 90fe7c9

Browse files
committed
update
1 parent 03d42ba commit 90fe7c9

File tree

1 file changed

+342
-2
lines changed

1 file changed

+342
-2
lines changed

Chapter_02: Functions, File IO, Generators.md

Lines changed: 342 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,7 @@ These functions are grouped together in the `__builtins__` module.
475475

476476
**import**
477477

478-
`import` is used to import a module from a given list.
478+
It is used to import a module from a given list.
479479

480480
```python
481481
>>> help(__import__)
@@ -515,12 +515,13 @@ It returns the absolute value of a given number(reel or complex).
515515
>>> help(all)
516516
all(iterable, /)
517517
Return True if bool(x) is True for all values x in the iterable.
518-
519518
If the iterable is empty, return True.
520519

521520
>>> list_ = [1,'2',3]
522521
>>> all([isinstance(e, int) for e in list_])
523522
False
523+
>>> all([])
524+
True
524525
```
525526

526527
**any**
@@ -536,6 +537,7 @@ any(iterable, /)
536537
>>> any([isinstance(e, int) for e in list_])
537538
True
538539
```
540+
539541
**ascii**
540542

541543
```python
@@ -571,5 +573,343 @@ ascii(obj, /)
571573
015 13 0D CR '\r' (carriage ret) 115 77 4D M
572574
```
573575

576+
**bin**
577+
578+
```python
579+
bin(number, /)
580+
Return the binary representation of an integer.
581+
582+
>>> bin(8)
583+
'0b1000'
584+
>>> int('0b1000',2)
585+
8
586+
```
587+
588+
**bool**
589+
590+
```python
591+
>>> help(bool)
592+
Returns True when the argument is true, False otherwise.
593+
594+
>>> bool([])
595+
False
596+
>>> bool(())
597+
False
598+
>>> bool(1)
599+
True
600+
>>> bool("")
601+
False
602+
>>> bool([""])
603+
True
604+
>>> bool((''))
605+
False
606+
>>> bool(('',))
607+
True
608+
```
609+
610+
**breakpoint**
611+
612+
This function was introduced in Python 3.7 which does the job of importing pdb and calling pdb.set_trace().
613+
614+
```python
615+
>>> help(breakpoint)
616+
breakpoint(...)
617+
breakpoint(*args, **kws)
618+
619+
Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept
620+
whatever arguments are passed.
621+
622+
By default, this drops you into the pdb debugger.
623+
624+
-------without breakpoint----
625+
# file.py
626+
import pdb
627+
x = 1
628+
y = 2
629+
print ( x )
630+
pdb.set_trace()
631+
print ( y )
632+
z = x + y
633+
-------with breakpoint----
634+
# file.py
635+
x = 1
636+
y = 2
637+
print ( x )
638+
breakpoint()
639+
print ( y )
640+
z = x + y
641+
642+
$ python3 file.py
643+
644+
-> print ( y )
645+
(Pdb) l (l stands for list)
646+
1 x = 1
647+
2 y = 2
648+
3 print ( x )
649+
4 breakpoint()
650+
5 -> print ( y )
651+
6 z = x + y
652+
[EOF]
653+
(Pdb) x
654+
1
655+
(Pdb) y
656+
2
657+
(Pdb) z
658+
*** NameError: name 'z' is not defined
659+
(Pdb) n (n stands for next)
660+
2
661+
-> z = x + y
662+
(Pdb) n
663+
--Return--
664+
-> z = x + y
665+
(Pdb) z
666+
3
667+
(Pdb) n
668+
```
669+
670+
**bytearray**
671+
672+
Construct a **mutable** bytearray object.
673+
674+
```python
675+
bytearray(iterable_of_ints) -> bytearray
676+
>>> bytearray([1,2,3])
677+
bytearray(b'\x01\x02\x03')
678+
679+
bytearray(string, encoding[, errors]) -> bytearray
680+
>>> bytearray("123",'utf-8')
681+
bytearray(b'123')
682+
683+
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
684+
>>> bytearray(b'123')
685+
bytearray(b'123')
686+
687+
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
688+
>>> bytearray(2)
689+
bytearray(b'\x00\x00')
690+
691+
bytearray() -> empty bytes array
692+
>>> bytearray()
693+
bytearray(b'')
694+
695+
>>> a = bytearray(b'123')
696+
>>> a[1] = 3 # mutable
697+
>>> a
698+
bytearray(b'1\x033')
699+
```
700+
701+
**bytes**
702+
703+
Construct an **immutable** array of bytes.
704+
705+
```python
706+
bytes(iterable_of_ints) -> bytes
707+
bytes(string, encoding[, errors]) -> bytes
708+
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
709+
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
710+
bytes() -> empty bytes object
711+
712+
>>> a = bytes([1,2,3])
713+
>>> a
714+
b'\x01\x02\x03'
715+
>>> a[1] = 1
716+
Traceback (most recent call last):
717+
File "<stdin>", line 1, in <module>
718+
TypeError: 'bytes' object does not support item assignment
719+
```
720+
574721
**callable**
575722

723+
Returns True if the passed object is a function or a method.
724+
725+
```python
726+
>>> callable(callable)
727+
True
728+
>>> def func():
729+
... print("hi there!")
730+
...
731+
>>> callable(func)
732+
True
733+
>>> string = 'abc'
734+
>>> callable(string)
735+
False
736+
```
737+
738+
**chr**
739+
740+
Returns a string that represents the character whose ASCII code is the integer argument.
741+
742+
```python
743+
>>> help(chr)
744+
chr(i, /)
745+
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
746+
747+
>>> chr(65)
748+
'A'
749+
>>> chr(50 + 15)
750+
'A'
751+
>>> ord('A')
752+
65
753+
```
754+
755+
** classmethod**
756+
757+
Converts a function to a class method. A class method is a method which is associated with a class and not with its instances.
758+
759+
```python
760+
>>> class car:
761+
... def __init__(self, speed, model):
762+
... self.speed = speed
763+
... self.model = model
764+
... def run(cls, speed, model):
765+
... return cls( speed, model)
766+
... def print(self):
767+
... print(self.model + "'s speed is: " + str(self.speed))
768+
... run = classmethod(run)
769+
...
770+
>>> car0 = car(50,'mercedes')
771+
>>> car0.print()
772+
mercedes's speed is: 50
773+
>>> car1 = car.run(60,'bmw')
774+
>>> car1.print()
775+
bmw's speed is: 60
776+
```
777+
778+
You can use the `classmethod` as a decorator.
779+
780+
```python
781+
>>> class car:
782+
... def __init__(self, speed, model):
783+
... self.speed = speed
784+
... self.model = model
785+
... @classmethod
786+
... def run(cls, speed, model):
787+
... return cls( speed, model)
788+
```
789+
790+
**compile**
791+
792+
Python allows source code to be compiled on the fly. The result of this compilation can then be interpreted using the exec() or eval() methods.
793+
794+
```python
795+
>>> help(compile)
796+
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
797+
Compile source into a code object that can be executed by exec() or eval().
798+
The mode must be 'exec' to compile a module, 'single' to compile a
799+
single (interactive) statement, or 'eval' to compile an expression.
800+
>>> bytes_ = compile("print('Hi There!')", '/dev/null','eval')
801+
>>> exec(bytes_)
802+
Hi There!
803+
```
804+
805+
**complex**
806+
807+
Returns a complex number.
808+
809+
```python
810+
>>> help(complex)
811+
class complex(object)
812+
complex(real=0, imag=0)
813+
>>> complex(3,4)
814+
(3+4j)
815+
```
816+
817+
**credits**, **copyright**
818+
819+
```python
820+
>>> credits()
821+
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
822+
for supporting Python development. See www.python.org for more information.
823+
>>> copyright()
824+
Copyright (c) 2001-2019 Python Software Foundation.
825+
All Rights Reserved.
826+
827+
Copyright (c) 2000 BeOpen.com.
828+
All Rights Reserved.
829+
830+
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
831+
All Rights Reserved.
832+
833+
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
834+
All Rights Reserved.
835+
```
836+
837+
**delattr**
838+
839+
Removes an attribute from an object. Equivalent to del object.attribute_name.
840+
841+
```python
842+
>>> class car:
843+
... speed = 10
844+
...
845+
>>> car.speed
846+
10
847+
>>> delattr(car,'speed')
848+
>>> car.speed
849+
Traceback (most recent call last):
850+
File "<stdin>", line 1, in <module>
851+
AttributeError: type object 'car' has no attribute 'speed'
852+
>>> class car:
853+
... speed = 10
854+
...
855+
>>> del car.speed
856+
>>> car.speed
857+
Traceback (most recent call last):
858+
File "<stdin>", line 1, in <module>
859+
AttributeError: type object 'car' has no attribute 'speed'
860+
```
861+
862+
**dict**
863+
864+
Creates a dictionary object.
865+
866+
```python
867+
>>> dict([('key0','val0'),('key1','val1')])
868+
{'key0': 'val0', 'key1': 'val1'}
869+
```
870+
871+
**dir**
872+
873+
Returns a list of the object's attributes.
874+
875+
```python
876+
>>> dir() # attributes of the namespace
877+
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'byte_code', 'bytes_', 'car']
878+
>>> class car:
879+
... speed = 10
880+
... model = 'mercedes'
881+
...
882+
>>> dir(car)
883+
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'model', 'speed']
884+
>>> car. # using the <tab> key
885+
car.model car.speed
886+
```
887+
888+
**divmod**
889+
890+
Returns the tuple: ((a-a% b) / b, a% b) which is an integer division followed by modulo.
891+
892+
```python
893+
>>> divmod(10,3)
894+
(3, 1)
895+
>>> divmod(1,3)
896+
(0, 1)
897+
```
898+
899+
**enumerate**
900+
901+
Returns an object of type enumerate from an iterable(e.g. lists or tuples).
902+
903+
```python
904+
>>> enumerate(range(10))
905+
<enumerate object at 0x7fd271b73f00>
906+
>>> for index, element in enumerate([1, 2, 3]):
907+
... print(index, element)
908+
...
909+
0 1
910+
1 2
911+
2 3
912+
```
913+
914+
**eval**
915+

0 commit comments

Comments
 (0)