Resumen Python
Resumen Python
import this
The Zen of Python, by Tim Peters
print(2 - 2)
print(3 * 3)
print(5 / 4)
print(2 ** 10)
print(5 // 4)
print(5 % 4)
2
0
9
1.25
1024
1
1
In [27]:
## Casting
### Integer -> Float
print(float.__doc__)
print(float(3))
print(3 / 1)
print(float("3.14"))
float(x) -> floating point number
In [6]:
## Length
print(len(s1)) # 2
2
In [4]:
## Slicing
s = 'study and practice'
print('{0}:{1}'.format(s[:5], s[-8:])) # study:practice
study:practice
In [48]:
## Operator: +
print("abc" + "." + "xyz")
abc.xyz
In [47]:
## Casting
print(str.__doc__)
print(str(3.14))
print(str(3))
print(str([1,2,3]))
print(str((1,2,3)))
print(str({1,2,3}))
print(str({'python': '*.py', 'javascript': '*.js'}))
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
l.extend(['!', '!'])
print(l)
# l == ['python', 3, '.4.1', 'in', 'one', 'pic', '!', '!']
['python', 3, 'in', 'one', 'pic']
['python', 3, '.4.1', 'in', 'one', 'pic']
['python', 3, '.4.1', 'in', 'one', 'pic', '!', '!']
In [16]:
print(l.pop()) # '!'
print(l)
# l == ['python', 3, '.4.1', 'in', 'one', 'pic', '!']
print(l.pop(2)) # '.4.1'
print(l)
# l == ['python', 3, 'in', 'one', 'pic', '!']
l.remove("in")
print(l)
# l == ['python', 3, 'one', 'pic', '!']
del l[2]
print(l)
# l == ['python', 3, 'pic', '!']
!
['python', 3, '.4.1', 'in', 'one', 'pic', '!']
.4.1
['python', 3, 'in', 'one', 'pic', '!']
['python', 3, 'one', 'pic', '!']
['python', 3, 'pic', '!']
In [17]:
print(l.index('pic')) # 2
2
Tuple
In [18]:
tp = (1, 2, 3, [4, 5])
print(type(tp)) # <class 'tuple'>
<class 'tuple'>
In [19]:
## Length
print(len(tp)) # 4
print(tp[2]) # 3
tp[3][1] = 6
print(tp) # (1, 2, 3, [4, 6])
4
3
(1, 2, 3, [4, 6])
In [20]:
## Single element
tp = (1, ) # Not tp = (1)
print(tp)
(1,)
In [21]:
## Assign multiple values at once
v = (3, 2, 'a')
(c, b, a) = v
print(a, b, c) # a 2 3
a 2 3
Set
In [22]:
st = {'s', 'e', 'T'}
print(type(st)) # <class 'set'>
<class 'set'>
In [23]:
## Length
print(len(st)) # 3
3
In [24]:
## Empty
st = set()
print(len(st)) # 0
0
In [25]:
st = {}
print(type(st)) # <class 'dict'>
<class 'dict'>
In [5]:
## Alter
st = set(['s', 'e', 'T'])
st.add('t') # st == {'s', 'e', 't', 'T'}
st.add('t') # st == {'s', 'e', 't', 'T'}
st.update(['!', '!'])
print(st)
# st == {'s', 'e', 't', 'T', '!'}
st.clear() # st == set()
print(st)
{'T', '!', 's', 't', 'e'}
{'s', 'e'}
set()
Dict
In [2]:
dic = {}
print(type(dic)) # <class 'dict'>
dic['k2'] = 'v3'
print(dic) # {'k1': 'v1', 'k2': 'v3'}
print(f())
print(f.__doc__)
Hello, World!
return 'Hello, World!'
Arguments
In [69]:
## default arguments
def f(name = "World"):
"""return 'Hello, $name'"""
return "Hello, {}!".format(name)
print(f())
print(f("Python"))
Hello, World!
Hello, Python!
In [74]:
## keyword arguments
def f(v, l = "Python"):
"""return '$v, $l'"""
return "{}, {}!".format(v, l)
print(f("Hello"))
print(f("Bye", "C/C++"))
Hello, Python!
Bye, C/C++!
In [102]:
## arbitrary arguments
def f(*args, con = " & "):
print(isinstance(args, tuple))
print("Hello", con.join(args))
@log
def fa():
print("This is fa!")
# Equal to...
def fb():
print("This is fb!")
fb = log(fb)
fa()
print("*"*10)
fb()
Hey log~
This is fa!
Bye log~
**********
Hey log~
This is fb!
Bye log~
V. Class(OOP)
class
In [10]:
class Animal:
"""This is an Animal"""
def fly(_):
print("I can fly!")
a = Animal()
a.fly() # I can fly!
print(a.__doc__) # This is an Animal
I can fly!
This is an Animal
__init__ & self
In [15]:
class Animal:
"""This is an Animal"""
def __init__(self, can_fly = False):
print("Calling __init__() when instantiation!")
self.can_fly = can_fly
def fly(self):
if self.can_fly:
print("I CAN fly!")
else:
print("I can not fly!")
a = Animal() # Calling __init__() when instantiation!
a.fly() # I can not fly!
# smo.py
def run():
print("Running MyModule.SubModuleOne.smo!")
"""
from MyModule.SubModule import smo
smo.run()
# Running MyModule.SubModuleOne.smo!
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-40-c2d8d80de486> in <module>()
9 print("Running MyModule.SubModuleOne.smo!")
10 """
---> 11 from MyModule.SubModule import smo
12 smo.run()
13 # Running MyModule.SubModuleOne.smo!