Python 102

Web Programming Course

SUT • Fall 2018

Outline

  • Sequences

    • lists

    • strings

    • tuples

  • Dictionaries

  • Functions

  • More on Functions

    • Anonymous Functions

    • Variable Arguments

Sequences

Sequences

  • Python sequence types:

 

 

 

 

  • Sequences are iterable: you can traverse their
    items one at a time
Type Object
Strings 'Ali'
Lists [110, 'me', 5]
Tuples (3, 7)
my_list = ['ali', 20, 14]
for x in my_list:
    print(x)

Indexing and Slicing

  • 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'

Sequence Operators

  • 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

 

 

 

 

 

  • We can use lists as stacks and queues (or
    alternatively, use deque)
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]
  • A list comprehension is a list defined by a "logic" that builds the list values/objects

 

 

  • A generator expression is almost the same,
    except it performs "lazy-evaluation" of objects
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>
  • Useful sting methods

 

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]
  • Using format method and F string

 

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.'
  • The r prefix tells the interpreter not to transform
    any special characters inside the string
  • Useful, in particular, for filenames and regular
    expressions

 

Raw Strings

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

  • Tuples are immutable lists
  • Sample usages:

 

# 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,)
  • The enumerate built-in function enables us to
    iterate and count at the same time (the latter is
    not possible with for by itself)

Enumerate

In [1]: a = [110, 'Ali', 'test']                                                                                                                                                                            

In [2]: for i, value in enumerate(a): 
   ...:     print(i, value)                                                                                                                                                                                 
0 110
1 Ali
2 test

Dictionaries

Dictionaries

student = {
'name': 'Ali',
'id': 110
}
  • Python's sole mapping type

    • keys: any immutable type

    • values: any type

  • Dictionaries (a.k.a. hashes) are unordered,
    mutable, resizable, and iterable

Methods

  • 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

Functions

Declaring and Calling

  • Functions are defined using def keyword
def greet(name, family):
    print('Hi', name, family)

greet('Ali', 'Ajami')

greet(family='Alavi', name='Zahra')

Default Arguments

  • Parameters can have default values
def greet(name, family=''):
    print('Hi', name, family)

greet('Ali', 'Ajami')

greet('Ali')

Document Strings

  • A document string (aka docstring) is a string
    literal that occurs as the first statement in a
    function, and is available via __doc__ attribute
def f(x):
    ''' Just do something on x '''
    pass

print(f.__doc__)
help(f)

Anonymous Functions

  • Anonymous functions are defined using lambda
    keyword
    • Syntax: lambda args: expression
f = lambda x: x ** 2

# is equivalent to

def f(x):
    return x ** 2

# another example
f = lambda x, y: x + y

Packed Arguments

  • Upon function calls, we can unpack lists and tuples with *, and unpack dictionaries with **
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')

Variable Arguments

  • We can define variable arguments using a
    single * representing a tuple, or ** representing a
    dictionary
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)
  • arguments that can only be supplied by keyword and which will never be automatically filled in by a positional argument.
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

Type Hints

  • PEP 3107 introduced syntax for function annotations
  • Providing typing information
    • Type checking ([3], [4])
    • Let IDEs show what types a function expects and returns ([17])
    • Predicate logic functions
    • Database query mapping
    • ...
def greeting(name: str) -> str:
    return 'Hello ' + name

def retry(url: Url, retry_count: int) -> None: ...

Generator

  • producer function
  • maintaining state between values produced
def fib():
    a, b = 0, 1
    while 1:
       yield b
       a, b = b, a+b

Decorators

  • A decorator is a “function wrapper” that
    "decorates” the behavior of a function to
    perform somewhat differently than designed, or
    to do something in addition to its native task
@deco
def foo():
    pass

# is equivalent to
foo = deco(foo)

Defining Decorators

  • Decorators are simply functions that take a function and return a decorated version of it
def log(func):
    def wrapped_func():
        print("-- Inside %s --" % func.__name__)
        return func()
    return wrapped_func

@log
def foo():
    pass

foo()

Decorators with Arguments

  • Decorators can take arguments
  • In this case, a “decorator-maker” takes the
    arguments and returns a decorator that takes
    foo as the function to wrap
@decomaker(deco_args)
def foo():
    pass

# is equivalent to:
func = decomaker(deco_args)(foo)

Decorator Example

  • Here is a sample decorator with arguments
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!'

Decorator Example

  • Here is a sample decorator with arguments
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)

Classes and Objects

Class Definition

  • We can define a class using class keyword
class Person:
    version = 1.2

    def __init__(self, name, phone):
        self.name = name
        self.phone = phone
    
    def update_phone(self, phone):
        self.phone = phone

Instantiation

  • Instances are created by simply calling the class as if it was a function
  • This creates the object, automatically calls __init__ with the given arguments, and then returns the newly created object back to you
a = Person('Ali', '0912-112-2030')
b = Person('Mahsa', '6616-6645')

b.update_phone('6616-6695')

Inheritance

  • For creating a subclass, we only need to provide one or more base classes upon defining the subclass
class Student(Person):
    def __init__(self, name, phone, id):
        Person.__init__(self, name, phone)
        self.id = id

a = Student('Reza', '4460-3220', '901002188')

Inner Classes

  • We can define classes inside other classes
  • The inner class is only visible to instances of the

outer class

class MainClass(object):
    class InnerClass:
        pass

Title Text

Python 102

By Behnam Hatami

Python 102

python / Web Programming Course @ SUT, Fall 2018

  • 1,422