Download presentation
Presentation is loading. Please wait.
1
Python Programming Language
Lecture 16 Python Programming Language
2
Python An open-sourced programming language Interpreted –
No compilation needed Python uses an interpreter to translate and run its code! The interpreter reads and executes each line of code one at a time Memory managed – manages creation and deletion of objects Object oriented – objects, inheritance Functional oriented – pure functions, lambda, map, filer, reduce, list comprehensions Dynamically typed – Type check is done during runtime Strongly typed – once the type is detected, operations can be executed only for the detected type
3
Python: Types Dynamically Typed: Strongly Typed: This works!
This fails - combining string with integer! 1 2 x = 32 x = "hi" 1 2 x = "hi" y = x + 2
4
Python: Functions & Indentation
Instead of brackets, python uses indentation And inner scope is indented using one tab in comparison to the outer scope Be sure to use tabs and not spaces! Otherwise the interpreter will throw an error Functions are defined using def keyword Python is a scripting language, it does not require a main function to run! def function1: print ("I am function 1") def function2: print ("I am function 2") function1() function2()
5
Python: if-statements
Just like any other programming language, python has if-statements. Instead of using else if, elif is used! Acts exactly like other programming languages if-statements def print_median(x, y, z): if x < y < z : print("y is median") elif y < x < z: print("x is median") else : print("z is median")
6
Python: Slicing Slicing in python is the ability to return a range of elements out of some defined container of elements Containers: arrays, strings, lists, tuples, etc… Python also supports string slicing: String slicing is returning sub-string out of the original string Strings in python are considered array of characters H llo llo World! Hello World!Hello World! Hello World!TEST str = 'Hello World!' print (str) # Prints complete string print (str[0]) # Prints first character of the string print (str[2:5]) # Prints characters starting from 3rd to 5th print (str[2:]) # Prints string starting from 3rd character print (str * 2) # Prints string two times print (str + "TEST") # Prints concatenated string
7
Python: Lists li = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tiny_list = [123, 'john'] print (li) # Prints complete list print (li[0]) # Prints first element of the list print (li[1:3]) # Prints elements starting from 2nd till 3rd print (li[2:]) # Prints elements starting from 3rd element print (tiny_list * 2) # Prints list two times print (list + tiny_list) # Prints concatenated lists Line 7, 8: Python lists are objects with overloaded operations such as operator+, and operator* How to multiply each element by 2? How to add 1 to each element? Syntax: li = [x * 2 for x in li] li = [x + 1 for x in li] 1 2 some_var = list(value_1, value_2, …, value_n) some_var = [value_1, value_2, …, value_n]
8
Python: Tuples tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tiny_tuple = (123, 'john') print (tuple) # Prints complete tuple print (tuple[0]) # Prints first element of the tuple print (tuple[1:3]) # Prints elements from 2nd till 3rd print (tuple[2:]) # Prints elements from 3rd element print (tiny_tuple * 2) # Prints tuple two times print (tuple + tiny_tuple) # Prints concatenated tuple Tuples behave exactly like lists – only difference, immutable! Any attempt to modify tuples, results in an error Syntax: 1 2 some_var = tuple(value_1, value_2, …, value_n) some_var = (value_1, value_2, …, value_n)
9
Why Tuples? Iteration speed!
$ python3 -mtimeit -s'x,y,z=1,2,3' '[x,y,z]' loops, best of 3: usec per loop $ python3 -mtimeit '[1,2,3]' loops, best of 3: usec per loop $ python3 -mtimeit -s'x,y,z=1,2,3' '(x,y,z)' loops, best of 3: usec per loop $ python3 -mtimeit '(1,2,3)' loops, best of 3: usec per loop $ python2 -mtimeit -s'x,y,z=1,2,3' '[x,y,z]' loops, best of 3: usec per loop $ python2 -mtimeit '[1,2,3]' loops, best of 3: usec per loop $ python2 -mtimeit -s'x,y,z=1,2,3' '(x,y,z)' loops, best of 3: usec per loop $ python2 -mtimeit '(1,2,3)' loops, best of 3: usec per loop
10
Python: Dictionaries 1 2 3 4 5 6 7 8 9 di = {}
di['one'] = "This is one" di[2] = "This is two" tiny_dict = {'name': 'john','code':6734, 'dept': 'sales'} print (di['one']) # Prints value for 'one' key print (di[2]) # Prints value for 2 key print (tiny_dict) # Prints complete dictionary print (tiny_dict.keys()) # Prints all the keys print (tiny_dict.values()) # Prints all the values This is one This is two {'name': 'john', 'dept': 'sales', 'code': 6734} dict_keys(['name', 'dept', 'code']) dict_values(['john', 'sales', 6734]) They are the hash maps – entries of key:value Syntax: 1 2 di = dict() di = {}
11
Python Functions: Arguments
def change(num, i): num = i num = 5 print(num) change(num, 2) Primitives by value: Non-primitives by reference: 1 2 5 def append(l, i): l.append(i) l = [1] print(l) append(l, 2) 1 2 [1] [1, 2]
12
Python: Functions Default-value arguments:
def reset(lis, default_val=None): del lis[:] if default_val is not None: lis.append(default_val) li = [5] print('original list:', li) reset(li, 2) print('reset default 2:', li) reset(li) print('reset no default:', li) original list: [5] reset default 2: [2] reset no default: [] To provide a variable a default value, add its value in the function header
13
Python: Functions Variable-length arguments:
def print_info(first, *rest): print(first, end='') for one in rest: print(' ', one, end='') print('') print_info(1) print_info(1, 2, 3) Adding * converts “rest” to a list of arguments that can be iterated over
14
Python: Iteration (loop) over data
def for_in_iteration(first, *rest): print(first, end='') for one in rest: print(' ', one, end='') print('') def in_range(first, *rest): print(first, end='') for i in range(len(rest)): print(' ', rest[i], end='') print('') def while_iteration(first, *rest): print(first, end='') i = while i < len(rest): print(' ', rest[i], end='') i += print('') for_in_iteration(1, 2, 3, 4, 5) in_range(1, 2, 3, 4, 5) while_iteration(1, 2, 3, 4, 5)
15
Python: List Comprehensions
letters = [] for letter in 'human': letters.append(letter) print(letters) letters = [letter for letter in 'human'] print(letters) nums = [] for x in range(20): if x % 2 == 0: nums.append(x) print(nums) nums = [x for x in range(20) if x % 2 == 0] print(nums) The faster, more compact way for list iteration li = [] for i in range(10): if i % 2 == 0: li.append('even') else: li.append('odd') print(li) li = ["even" if i % 2 == 0 else "odd" for i in range(10)] print(li)
16
Python: Lambda & Functional Operators
Syntax: Example 1: Example 2: Notes: Lambdas are short, and limited to one line! Mostly used in functional operators lambda argument: manipulate(argument) add = lambda x, y: x + y print(add(3, 5)) even_or_odd = lambda x: 'even' if x % 2 == 0 else 'odd' print(even_or_odd(3))
17
Functional Operators: Map, Filter, Reduce
Applies a function to each element in a list Filter: Returns elements that meet some condition from original list Reduce: Applies an aggregation function on a list, returning one value as result Aggregation: 𝑁−>1 [𝑠𝑢𝑚, 𝑎𝑣𝑒𝑟𝑎𝑔𝑒, 𝑚𝑢𝑙𝑡𝑖𝑝𝑙𝑖𝑐𝑎𝑡𝑖𝑜𝑛, 𝑒𝑡𝑐…] Input = [x1, x2, …, xN] Output = [f(x1), f(x2), …, f(xN)] Input = [x1, x2, …, xN] Output = f(f…(f(x1, x2), …), xN)
18
Map, Filter, Reduce: Examples
product = 1 li = [1, 2, 3, 4] for num in li: product = product * num from functools import reduce li = [1, 2, 3, 4] product = reduce(lambda x, y: x * y, li) items = [1, 2, 3, 4, 5] squared = [] for i in items: squared.append(i**2) li = [1, 2, 3, 4, 5] squared = list(map(lambda x: x ** 2, li)) li = [1, 2, 3] odd_values = [] for x in li: if x % 2 != 0: odd_values.append(x) li = [1, 2, 3] odd_values = list(filter(lambda x: x % 2 != 0, li))
19
Python: Class Example class Employee: # defining class emp_count = def __init__(self, name, salary): # declare class 'constructor' self.name = name # access object instance variable self.salary = salary # self acts like 'this' Employee.emp_count += 1 # access static variable @staticmethod # declare display_count as a static function def display_count(): print("total employees %d" % Employee.emp_count) def display_employee(self): # using 'self' is mandatory - unlike 'this' # one cannot access 'salary' without 'self' print("name : ", self.name, ", salary: ", self.salary)
20
Class: Usage Example Employee.display_count() e1 = Employee('mark', 1000) Employee.display_count() e2 = Employee('joe', 2000) Employee.display_count() e1.display_employee() e2.display_employee() total employees 0 total employees 1 total employees 2 name : mark , salary: name : joe , salary: 2000
21
Python: del command class Employee: def __init__(self): class_name = self.__class__.__name__ print(class_name, "created") def __del__(self): class_name = self.__class__.__name__ print(class_name, "destroyed") e = Employee() del e Employee created Employee destroyed Reminder: All python objects are automatically deleted once there are no references to them
22
Python: del command e1 = Employee() e2 = e1 print('e1 id=', id(e1)) print('e2 id=', id(e2)) del e1 print('e2 id=', id(e2)) # what happens here? del e2 Employee created e1 id= e2 id= e2 id= Employee destroyed del removes the reference e1 – reducing the reference count by 1 If the reference count reaches zero, then the garbage collector removes it del does not delete the object instance The garbage collector does that! del deletes the reference itself The garbage collections comes in if the count reached zero due to this deletion
23
Python: Inheritance p = Person("Marge", "Simpson") e = Employee("Homer", "Simpson", "1007") print(p.name()) print(e.get_employee()) class Person: def __init__(self, first, last): self.first_name = first self.last_name = last def name(self): return self.first_name + " " + self.last_name class Employee(Person): # inheritance! def __init__(self, first, last, staff_number): # must execute super explicitly Person.__init__(self, first, last) self.staff_number = staff_number def get_employee(self): return self.name() + ", " + self.staff_number Marge Simpson Homer Simpson, 1007
24
Python: Setting main Function
No formal notion of a main function in Python! By running: python file.py Execution begins at the beginning of the file All statements are executed in order until the end of the file is reached However, a special variable __name__ is set to __main__ Using this, we can implement our ‘main’ function Example: def main(): # this is the 'main' method if __name__ == '__main__': main()
25
Python: Command Line Arguments
To be able to fetch arguments from the command line: Use sys library: python -m file.py arg1 arg2 import sys def main(args): # this is the 'main' method print(args) if __name__ == '__main__': main(sys.argv)
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.