Web Programming Course
SUT • Fall 2018
Sequences
lists
strings
tuples
Dictionaries
Functions
More on Functions
Anonymous Functions
Variable Arguments
Type | Object |
---|---|
Strings | 'Ali' |
Lists | [110, 'me', 5] |
Tuples | (3, 7) |
my_list = ['ali', 20, 14]
for x in my_list:
print(x)
We can directing index items in a sequence, or
slice a subsequence
In [1]: s = 'Python'
In [2]: s[0]
Out[2]: 'P'
In [3]: s[0:2]
Out[3]: 'Py'
In [4]: s[:2]
Out[4]: 'Py'
In [5]: s[2:]
Out[5]: 'thon'
In [6]: s[:]
Out[6]: 'Python'
In [7]: s[-1]
Out[7]: 'n'
Operators
+: concatenation
*: repetition/duplication
in: membership
not in: non-membership
Functions
len
max, min, sum
sorted
list is a Python type that acts most like other
languages’ arrays
Useful methods
append, extend, insert, remove, pop, index, count, sort, reverse
In [1]: a = [20, 14]
In [2]: a.append(10)
In [3]: a
Out[3]: [20, 14, 10]
In [4]: a.sort()
In [5]: a
Out[5]: [10, 14, 20]
In [1]: evens = [x for x in range(10) if x % 2 == 0]
In [2]: evens
Out[2]: [0, 2, 4, 6, 8]
In [1]: (x for x in range(1000) if x % 2 == 0)
Out[1]: <generator object <genexpr> at 0x7f19a532a570>
function | description |
---|---|
count | Number of occurrences of substring in string |
find | Search for substring [also index, rfind, rindex] |
join | Merge substrings into single delimited string |
replace | Search and replace (sub)string |
split | Split string into substrings [also splitlines] |
startswith | Does string start with substring [also endswith] |
strip | Remove whitespace around [also rstrip, lstrip] |
upper | UPPERCASE string [also lower] |
isupper | Is string all UPPERCASE? [also islower] |
In [1]: 'Number of {0} is {1}'.format('steps', 100)
Out[1]: 'Number of steps is 100'
In [2]: person = {'name': 'Eric', 'age': 74}
In [3]: "Hello, {name}. You are {age}.".format(name=person['name'],
age=person['age'])
Out[3]: 'Hello, Eric. You are 74.'
In [4]: name = "Eric"
In [5]: age = 74
In [6]: f"Hello, {name}. You are {age}."
Out[6]: 'Hello, Eric. You are 74.'
In [1]: print('C:\some\name') # here \n means newline!
C:\some
ame
In [2]: print(r'C:\some\name') # note the r before the quote
C:\some\name
# define a point
point = (3, -7)
# swap variables
a, b = b, a
# return more than a value
return a, b
# one-item lists
x = (10,)
In [1]: a = [110, 'Ali', 'test']
In [2]: for i, value in enumerate(a):
...: print(i, value)
0 110
1 Ali
2 test
student = {
'name': 'Ali',
'id': 110
}
Python's sole mapping type
keys: any immutable type
values: any type
Useful sting methods
Method | Description |
---|---|
keys | Keys |
values | Values |
items | Key-value pairs |
get | Get value given key else default (also see in) |
pop | Remove key from dict and return value |
update | Update dict with contents of (an)other dict |
copy | Make a shallow copy of dict |
deepcopy | Make a deep copy of dict |
def greet(name, family):
print('Hi', name, family)
greet('Ali', 'Ajami')
greet(family='Alavi', name='Zahra')
def greet(name, family=''):
print('Hi', name, family)
greet('Ali', 'Ajami')
greet('Ali')
def f(x):
''' Just do something on x '''
pass
print(f.__doc__)
help(f)
f = lambda x: x ** 2
# is equivalent to
def f(x):
return x ** 2
# another example
f = lambda x, y: x + y
def greet(name, family=''):
print('Hi', name, family)
person = ['Ali', 'Orouji']
greet(person[0], person[1])
greet(*person)
person = {
'name': 'Ali',
'family': 'Orouji'
}
greet(**person)
greet(name='Ali', family='Orouji')
def average(*args):
sum = 0
for x in args:
sum += x
return sum / len(args)
average(2, 3, 5)
#----------------------------------------
def f(*args, **kwargs):
print(args, kwargs)
f(2, 3, k=5, n=10)
def sortwords(*wordlist, case_sensitive=False):
...
def compare(a, b, *, key=None):
...
def compare(a, b, key=None):
...
def compare(a, b, *ignore, key=None):
...
def compare(a, b, *ignore, key=None):
if ignore: # If ignore is not empty
raise TypeError
def greeting(name: str) -> str:
return 'Hello ' + name
def retry(url: Url, retry_count: int) -> None: ...
def fib():
a, b = 0, 1
while 1:
yield b
a, b = b, a+b
@deco
def foo():
pass
# is equivalent to
foo = deco(foo)
def log(func):
def wrapped_func():
print("-- Inside %s --" % func.__name__)
return func()
return wrapped_func
@log
def foo():
pass
foo()
@decomaker(deco_args)
def foo():
pass
# is equivalent to:
func = decomaker(deco_args)(foo)
def div_wrap(class_name):
def decorator(function):
def wrapper(*args, **kwargs):
text = function(*args, **kwargs)
tmpl = '<div class="{0}">{1}</div>'
return tmpl.format(class_name, text)
return wrapper
return decorator
@div_wrap('my_class')
def foo():
return 'Some text!'
def cache(f):
cache = dict()
def wrapper(*args):
if args in cache:
return cache[args]
cache[args] = f(*args)
return cache[args]
return wrapper
@cache
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
fib(100)
class Person:
version = 1.2
def __init__(self, name, phone):
self.name = name
self.phone = phone
def update_phone(self, phone):
self.phone = phone
a = Person('Ali', '0912-112-2030')
b = Person('Mahsa', '6616-6645')
b.update_phone('6616-6695')
class Student(Person):
def __init__(self, name, phone, id):
Person.__init__(self, name, phone)
self.id = id
a = Student('Reza', '4460-3220', '901002188')
outer class
class MainClass(object):
class InnerClass:
pass