Python Rediscovered
-
Upload
mayank-singh -
Category
Documents
-
view
231 -
download
0
Transcript of Python Rediscovered
-
7/31/2019 Python Rediscovered
1/23
Python Rediscovered
Lecture 1
-
7/31/2019 Python Rediscovered
2/23
Introduction ?
Why Python ?What can you as a user do with pythonWhat I love so much . Why I chose it .
The Calculator we all strive for ;)
The Debate of the Language style ! < DO NOT CARE > Not Compiled / Interpreted- Its a implementation
detail.
Free loosely typed scripting beauty !Open Source ! The Speed Debate ! Its every where , all platform , including Droids !Guido Van Rossum and the PEP
-
7/31/2019 Python Rediscovered
3/23
Hello World and the InterpreterConsole!
print "hello world "or
print ("Hello World")
Playing with code , the beauty of an interpreter : help docs teach yourself , fool around !
Running the code the python file , and compilation USE AN IDE ! Indentation !
-
7/31/2019 Python Rediscovered
4/23
The Teachers Calculator Challenge !
print(eval(input("Enter a valid expression : ")))
# exits on Ctr+C# Such lines are comments ! (''' for multiline)while True :
try :print(eval(input("Enter a valid expression : ")))except NameError :print("Enter a valid expression you twit ! ")
except KeyboardInterrupt :
exit()
-
7/31/2019 Python Rediscovered
5/23
Variables and Expressions
Data Types - The New paradigm , its not an abstract world
Think of it logically, say a trip to the market !What possible things do you encounter ?
Currency -> Numbers -> Math -> Operations -> We need atype .
(note to 2.x devs : long is depreciated ) 23456789 ** 4567 is valid !
Names of things -> characters -> One More Decisions, To Do Or Not To Do THAT Is The Question
? BooleanQuantities and the List, your phonebook when you forget
what mama told you !
-
7/31/2019 Python Rediscovered
6/23
Expression !Golden Rule for a Programmer #iForgot
Yes the computer is one dumb piece of shit ! BE EXPLICIT or ISTHAT SO ?
Each one of these morph depending on type ! + , -,*
/ and // ** != , ! , ^ , & , and or
Beauty of assignments in python ! a,b = b,a is VALID so is a,b,c= (110,220,130) a,b = b, a+b
type() function ! Libraries
math , cmath , numpy ..
-
7/31/2019 Python Rediscovered
7/23
Interaction
Input : input () readlines() raw_input () # DEPRECATED !
Output : print ()
the formatting : Classic Style %d %s using format() format "%[padding_type][width][.[precession]]%[type]write ()
-
7/31/2019 Python Rediscovered
8/23
Functions
Type()
Typecasters: int(), float(), etc. len(), sort(), sorted()Other ways of typecasting: minute/60.0Math funcs: sqrt, log, exp, etc. Composition of functions Function defintion Fruitful functions to practise:
Area of all stuff Euclidean distance
Isdivisible counting elements gcd
Recursion (Programming inception): Factorial Fibonacci
-
7/31/2019 Python Rediscovered
9/23
Iteration and conditional flow
for loop range and xrange loop over lists, strings, all iterable objects nested fors
while loop nested whiles if else nested ifs break and continue and pass
-
7/31/2019 Python Rediscovered
10/23
Strings - The Fortress of Python'sInvincibility
Never ever has it been easier to deal with strings - reason whyits the language of the future , AI, machine learning , NLP.String "Methods" :
ctype.h -> s.digits, .letters,.[]case , .lower(), startswith() s.find (sub) s.join # do not use '+' a list method ! s.split () s.replace() s.strip(), lstrip, rstrip
The Unicode debate ! #extars
-
7/31/2019 Python Rediscovered
11/23
Lists a = [1,2,3]
b = [1,2,"asdsad"] c = [1,2,[1,2],[3,4],"sadas",(8,9)] iterating over lists appending to list - a.append("asda") list slicing indices negative index list cloning vs aliasingmatrices
Handling two dimensional lists common funcs - insert(i,x),index(x),remove(x),sort(),
reverse(), del a[0] string.split() and string.join()
-
7/31/2019 Python Rediscovered
12/23
Tuples
a = (1,2,3) or just a=1,2,3 the idea behind a,b = b,a or x,y = int(x),int(y) similar to lists immutable
('a') vs ('a',) similar slicing as lists return tuples in functions
-
7/31/2019 Python Rediscovered
13/23
Sets
a = [1,1,2,1,3,3] b = set(a) c = [1,1,3,4,5] d = set(c)
e = a& b (intersection) f = a|b (union) g = a-b (difference) h = a^b (symmetric difference)membership testing - "book" in ["house","book","dog"] 'z' in 'abracadabra'
-
7/31/2019 Python Rediscovered
14/23
Iterators and list comprehensions
try combinations and permutations - don't return list butiterator
need to iterate over iterator to get all values the yield keyword - the intermediary return
list comprehensions - shortcut to generate lists of varioustypes of sequences
[x**2 for x in xrange(10) [(x,y) for x in [1,2] for y in [3,4] if x!= y]
-
7/31/2019 Python Rediscovered
15/23
Dictionaries - We the People !
Kill the abstraction, lets name it !
Think Phonebook !
a = [xxxx,sathe,marcus]b =[123,1345,2225]what if i want a no ? b[a.index("marcus")] !!!
numbers ['marcus'] - Cool right !book = { 'marcus': 1123 , 'sathe' : { 'room' : 105, 'hometown';"bombay "}}
Sudden relavance !
-
7/31/2019 Python Rediscovered
16/23
Dictionary Methods
.clear() .copy() .fromkeys(list) Using them
.get() .has_key() like the in() items() and values()
Note : iteritems/values is depreciated items is nowa iterator
.pop() .setdefault()
defaultdict(type) #example
-
7/31/2019 Python Rediscovered
17/23
Looping techniques and variable args
dictionary - iteritems - for i,k in dictname.iteritems(): enumerate - lists - for k,v in enumerate(list): zip and izip - for q,a in zip(list1,list2): *args and **kwargs
def test_var_args(farg,*args):print "fomral arg",fargfor arg in args:
print "another arg:",argtest_var_args(1,"two",3,[1,2,3,4])
def test_var_kwargs(farg, **kwargs):print "formal arg:", fargfor key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])test_var_kwargs(farg=1, myarg2="two", myarg3=3)
sys
-
7/31/2019 Python Rediscovered
18/23
Stacks and Queues via lists
Stacks functions - append and pop
Queues need deque
from collections import deque deque list and use append and popleft queue = deque([1,2,3,4])
-
7/31/2019 Python Rediscovered
19/23
Classes and Objects
Damn I Hate these slides !
Lets go a bit hands on !
-
7/31/2019 Python Rediscovered
20/23
Classes and Methods
__init__(), __str__(), __repr__()others
-
7/31/2019 Python Rediscovered
21/23
__str__ vs __rep__
repr - debugging representation
str - string representation and printableclass Foo:... def __str__(self):... return '__str__'... def __repr__(self):... return '__repr__'
__str__ falls back on __rep__>>> class Foo:... def __repr__(self):... return '__repr__'
>>> class Point:... def __init__(self, x, y):... self.x, self.y = x, y... def __repr__(self):... return 'Point(x=%s, y=%s)' % (self.x, self.y)
-
7/31/2019 Python Rediscovered
22/23
Inheritance
class animal, dog, cat, and some other animalmethod overriding super(subclass, self).func() Base.func(self) class animal(object):
def __init__(self,name):self.name = name
def shout(self):print "I shout\n"+"I am called "+self.name
class bird(object):def __init__(self,name):
self.name = namedef chirp(self):
print "I chirp"class cat(animal):
def shout(self):animal.shout(self)print "I meow\n"+"I am called "+self.name
-
7/31/2019 Python Rediscovered
23/23
Inheritance continued
class bat(animal,bird):def shout(self):
super(bat,self).shout()print "I bark\n"+"I am called "+self.name
a = animal("asd")b = bat("saddd")c = cat("sdsadad")a.shout()b.shout()c.shout()b.chirp()