# Python's list slice syntax can be used without indices
# for a few fun and useful things:
# You can clear all elements from a list:
[]
# You can replace all elements of a list
# without creating a new list object:
[7, 8, 9]
[7, 8, 9]
True
# You can also create a (shallow) copy of a list:
[7, 8, 9]
False
# for a few fun and useful things:
# You can clear all elements from a list:
>>> lst = [1, 2, 3, 4, 5]
>>> del lst[:]
>>> lst[]
# You can replace all elements of a list
# without creating a new list object:
>>> a = lst
>>> lst[:] = [7, 8, 9]
>>> lst[7, 8, 9]
>>> a[7, 8, 9]
>>> a is lstTrue
# You can also create a (shallow) copy of a list:
>>> b = lst[:]
>>> b[7, 8, 9]
>>> b is lstFalse
# Python's list comprehensions are awesome.
# This is equivalent to:
# Example:
[0, 4, 16, 36, 64]
vals = [expression
for value in collection
if condition]# This is equivalent to:
vals = []
for value in collection:
if condition:
vals.append(expression)
# Example:
>>> even_squares = [x * x for x in range(10) if not x % 2]
>>> even_squares[0, 4, 16, 36, 64]
This media is not supported in your browser
VIEW IN TELEGRAM
# Python has a HTTP server built into the
# standard library. This is super handy for
# previewing websites.
# Python 3.x
# Python 2.x
# (This will serve the current directory at
# http://localhost:8000)
# standard library. This is super handy for
# previewing websites.
# Python 3.x
$ python3 -m http.server# Python 2.x
$ python -m SimpleHTTPServer 8000# (This will serve the current directory at
# http://localhost:8000)
# Python 3.5+ supports 'type
# annotations' that can be
# used with tools like Mypy
# to write statically typed Python:
# annotations' that can be
# used with tools like Mypy
# to write statically typed Python:
def my_add(a: int, b: int) -> int:
return a + b# itertools.permutations() generates
# permutations for an iterable.
# Time to brute-force those passwords
('A', 'B', 'C', 'D')
('A', 'B', 'D', 'C')
('A', 'C', 'B', 'D')
('A', 'C', 'D', 'B')
('A', 'D', 'B', 'C')
('A', 'D', 'C', 'B')
('B', 'A', 'C', 'D')
('B', 'A', 'D', 'C')
('B', 'C', 'A', 'D')
('B', 'C', 'D', 'A')
('B', 'D', 'A', 'C')
('B', 'D', 'C', 'A')
('C', 'A', 'B', 'D')
('C', 'A', 'D', 'B')
('C', 'B', 'A', 'D')
('C', 'B', 'D', 'A')
('C', 'D', 'A', 'B')
('C', 'D', 'B', 'A')
('D', 'A', 'B', 'C')
('D', 'A', 'C', 'B')
('D', 'B', 'A', 'C')
('D', 'B', 'C', 'A')
('D', 'C', 'A', 'B')
('D', 'C', 'B', 'A')
# permutations for an iterable.
# Time to brute-force those passwords
>>> import itertools
>>> for p in itertools.permutations('ABCD'):
... print(p)('A', 'B', 'C', 'D')
('A', 'B', 'D', 'C')
('A', 'C', 'B', 'D')
('A', 'C', 'D', 'B')
('A', 'D', 'B', 'C')
('A', 'D', 'C', 'B')
('B', 'A', 'C', 'D')
('B', 'A', 'D', 'C')
('B', 'C', 'A', 'D')
('B', 'C', 'D', 'A')
('B', 'D', 'A', 'C')
('B', 'D', 'C', 'A')
('C', 'A', 'B', 'D')
('C', 'A', 'D', 'B')
('C', 'B', 'A', 'D')
('C', 'B', 'D', 'A')
('C', 'D', 'A', 'B')
('C', 'D', 'B', 'A')
('D', 'A', 'B', 'C')
('D', 'A', 'C', 'B')
('D', 'B', 'A', 'C')
('D', 'B', 'C', 'A')
('D', 'C', 'A', 'B')
('D', 'C', 'B', 'A')
# When To Use repr vs str?
# Emulate what the std lib does:
# Result of str should be readable:
# Result of repr should be unambiguous:
# Python interpreter sessions use
# repr to inspect objects:
# Emulate what the std lib does:
>>> import datetime
>>> today = datetime.date.today()
# Result of str should be readable:
>>> str(today)
'2020-04-27’# Result of repr should be unambiguous:
>>> repr(today)
'datetime.date(2020,4,27)’# Python interpreter sessions use
# repr to inspect objects:
>>> today
datetime.date(2020,4,27)# You can use Python's built-in "dis"
# module to disassemble functions and
# inspect their CPython VM bytecode:
>>> def greet(name):
... return 'Hello, ' + name + '!'
>>> greet('Dan')
'Hello, Dan!'
>>> import dis
>>> dis.dis(greet)
# module to disassemble functions and
# inspect their CPython VM bytecode:
>>> def greet(name):
... return 'Hello, ' + name + '!'
>>> greet('Dan')
'Hello, Dan!'
>>> import dis
>>> dis.dis(greet)
2 0 LOAD_CONST 1 ('Hello, ')
2 LOAD_FAST 0 (name)
4 BINARY_ADD
6 LOAD_CONST 2 ('!')
8 BINARY_ADD
10 RETURN_VALUEBeware of nan!
😱#python
#pythontip
😱#python
>>> sorted([5.0, math.nan, 10.0, 0.0])
[5.0, nan, 0.0, 10.0]
>>> sorted([math.nan, 1.0])
[nan, 1.0]
>>> sorted([1.0, math.nan])
[1.0, nan]
>>> min(3, math.nan, 1)
1
>>> min(math.nan, 3, 1)
nan#pythontip
In the python document it says that
math.nan is the same as float("nan")Do you want to avoid problems with
math.nan? Then use #numpy!> np.sort([5., math.nan, 10., 0.])
array([ 0., 5., 10., nan])
> np.sort([math.nan, 1.])
array([ 1., nan])
> sorted([1., math.nan])
array([ 1., nan])
> np.max([3., math.nan, 1.])
nan
> np.nanmax([3., math.nan, 1.])
3.0# The lambda keyword in Python provides a
# shortcut for declaring small and
# anonymous functions:
8
# You could declare the same add()
# function with the def keyword:
8
# So what's the big fuss about?
# Lambdas are *function expressions*:
8
# • Lambda functions are single-expression
# functions that are not necessarily bound
# to a name (they can be anonymous).
# • Lambda functions can't use regular
# Python statements and always include an
# implicit
# shortcut for declaring small and
# anonymous functions:
>>> add = lambda x, y: x + y
>>> add(5, 3)8
# You could declare the same add()
# function with the def keyword:
>>> def add(x, y):
... return x + y
>>> add(5, 3)8
# So what's the big fuss about?
# Lambdas are *function expressions*:
>>> (lambda x, y: x + y)(5, 3)8
# • Lambda functions are single-expression
# functions that are not necessarily bound
# to a name (they can be anonymous).
# • Lambda functions can't use regular
# Python statements and always include an
# implicit
return statement.# @classmethod vs @staticmethod vs "plain" methods
# What's the difference?
Instance methods need a class instance and can access the instance through
"""
return 'instance method called', self
Class methods don't need a class instance. They can't access the instance (self) but they have access to the class itself via
"""
return 'class method called', cls
Static methods don't have access to
"""
return 'static method called'
# All methods types can be
# called on a class instance:
('instance method called', <MyClass instance at 0x1019381b8>)
>>>
('class method called', <class MyClass at 0x101a2f4c8>)
'static method called'
# Calling instance methods fails
# if we only have the class object:
('class method called', <class MyClass at 0x101a2f4c8>)
'static method called'
TypeError:
"unbound method method() must be called with MyClass "
"instance as first argument (got nothing instead)"
# What's the difference?
class MyClass:
def method(self):
"""Instance methods need a class instance and can access the instance through
self."""
return 'instance method called', self
@classmethod
def classmethod(cls):
"""Class methods don't need a class instance. They can't access the instance (self) but they have access to the class itself via
cls."""
return 'class method called', cls
@staticmethod
def staticmethod():
"""Static methods don't have access to
cls or self. They work like regular functions but belong to the class's namespace."""
return 'static method called'
# All methods types can be
# called on a class instance:
>>> obj = MyClass()
>>> obj.method()('instance method called', <MyClass instance at 0x1019381b8>)
>>>
obj.classmethod()('class method called', <class MyClass at 0x101a2f4c8>)
>>> obj.staticmethod()'static method called'
# Calling instance methods fails
# if we only have the class object:
>>> MyClass.classmethod()('class method called', <class MyClass at 0x101a2f4c8>)
>>> MyClass.staticmethod()'static method called'
>>> MyClass.method()TypeError:
"unbound method method() must be called with MyClass "
"instance as first argument (got nothing instead)"
Check yourself
Complexity : easy
CLOSING TIME: 30th April, 6PM
https://kahoot.it/challenge/07727305?challenge-id=4a3777ca-b8c9-4432-82d7-38e504fb31fc_1588074473234
Complexity : easy
CLOSING TIME: 30th April, 6PM
https://kahoot.it/challenge/07727305?challenge-id=4a3777ca-b8c9-4432-82d7-38e504fb31fc_1588074473234
Kahoot!
Play Kahoot! challenge: Duplicate of Python
Play this kahoot challenge about #Python #KS3 #If
If the local date format us DD/MM/YYYY, you can use the dayfirst=True argument in dateutil.parser.parse:
>>> from dateutil.parser import parse
>>> s = '6.5.2020'
>>> parse(s)
datetime.datetime(2020, 6, 5, 0, 0)
>>> parse(s, dayfirst=True)
datetime.datetime(2020, 5, 6, 0, 0)