100% found this document useful (1 vote)
289 views

Ansh Bhawnani: Python Beginner's Course Bitten Tech

This document provides an overview of the Python programming language. Some key points: - Python is a simple, easy to learn, open source, high-level, interpreted, and portable language. - It has a wide range of standard libraries and can be used for web development, scientific computing, desktop applications, and more. - Python's creator Guido van Rossum started developing it in the late 1980s and it has grown significantly in popularity since its initial 1.0 release in 1994.

Uploaded by

Dalllas reviews
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
289 views

Ansh Bhawnani: Python Beginner's Course Bitten Tech

This document provides an overview of the Python programming language. Some key points: - Python is a simple, easy to learn, open source, high-level, interpreted, and portable language. - It has a wide range of standard libraries and can be used for web development, scientific computing, desktop applications, and more. - Python's creator Guido van Rossum started developing it in the late 1980s and it has grown significantly in popularity since its initial 1.0 release in 1994.

Uploaded by

Dalllas reviews
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Ansh Bhawnani

Python Beginner’s Course


Bitten Tech

1
Python
 Simple
 Python is a simple and minimalistic language in
nature
 Reading a good python program should be like
reading English
 Its Pseudo-code nature allows one to concentrate
on the problem rather than the language
 Easy to Learn
 Free & Open source
 Freely distributed and Open source
 Maintained by the Python community
 High Level Language – memory management
 Portable – *runs on anything c code will
2
Python
 Interpreted
 You run the program straight from the source code.
 Python program Bytecode a platforms native language
 You can just copy over your code to another system and it
will auto-magically work! *with python platform
 Object-Oriented
 Simple and additionally supports procedural programming
 Extensible – easily import other code
 Embeddable –easily place your code in non-python programs
 Extensive libraries
 (i.e. reg. expressions, doc generation, CGI, ftp, web
browsers, ZIP, WAV, cryptography, etc...) (wxPython,
Twisted, Python Imaging library) 3
Timeline
 Python was conceived in the late 1980s.
 Guido van Rossum, Benevolent Dictator For Life
 Rossum is Dutch, born in Netherlands, Christmas break
bored, big fan of Monty python’s Flying Circus
 Descendant of ABC, he wrote glob() func in UNIX
 M.D. @ U of Amsterdam, worked for CWI, NIST, CNRI,
Google
 Also, helped develop the ABC programming language
 In 1991 python 0.9.0 was published and reached the
masses through alt.sources
 In January of 1994 python 1.0 was released
 Functional programming tools like lambda, map, filter, and
reduce
 comp.lang.python formed, greatly increasing python’s
userbase
4
Timeline
 In 2000, Python 2.0 was released.
 Introduced list comprehensions similar to Haskells
 Introduced garbage collection
 In 2001, Python 2.2 was released.
 Included unification of types and classes into one
hierarchy, making pythons object model purely Object-
oriented
 Generators were added(function-like iterator behavior)
 In 2008, Python 3.0 was released.
 Broke Backward compatibility
 Latest version is 3.7
 Course will be based on Python3
5
Python types
 Str, unicode – ‘MyString’, u‘MyString’
 List – [ 69, 6.9, ‘mystring’, True]
 Tuple – (69, 6.9, ‘mystring’, True) immutable
 Set/frozenset – set([69, 6.9, ‘str’, True])
frozenset([69, 6.9, ‘str’, True]) –no duplicates &
unordered
 Dictionary or hash – {‘key 1’: 6.9, ‘key2’: False} -
group of key and value pairs

6
Python types
 Int – 42- may be transparently expanded
to long through 438324932L
 Float – 2.171892
 Complex – 4 + 3j
 Bool – True of False

7
Python semantics
 Each statement has its own semantics, the def
statement doesn’t get executed immediately like
other statements
 Python uses duck typing, or latent typing
 Allows for polymorphism without inheritance
 This means you can just declare
“somevariable = 69” don’t actually have to declare a
type
 print “somevariable = “ + tostring(somevariable)”
strong typing , can’t do operations on objects not
defined without explicitly asking the operation to be
done

8
Python Syntax
• Python uses indentation and/or whitespace to
delimit statement blocks rather than keywords or
braces
• if __name__ == "__main__":
print “Salve Mundo"
# if no comma (,) at end ‘\n’ is auto-included

• CONDITIONALS
• if (i == 1): do_something1()
elif (i == 2): do_something2()
elif (i == 3): do_something3()
else: do_something4()

9
Conditionals Cont.
• if (value is not None) and (value == 1):
print "value equals 1”,
print “ more can come in this block”
• if (list1 <= list2) and (not age < 80):
print “1 = 1, 2 = 2, but 3 <= 7 so its True”
• if (job == "millionaire") or (state != "dead"):
print "a suitable husband found"
else:
print "not suitable“
• if ok: print "ok"

10
Loops/Iterations
• sentence = ['Marry','had','a','little','lamb']
for word in sentence:
print word, len(word)
• for i in range(10):
print I
for i in xrange(1000):# does not allocate all initially
print I

• while True:
pass
• for i in xrange(10):
if i == 3: continue
if i == 5: break
11
print i,
Functions
 def. print_hello():# returns nothing
print “hello”
 def has_args(arg1,arg2=['e', 0]):
num = arg1 + 4
mylist = arg2 + ['a',7]
return [num, mylist]
has_args(5.16,[1,'b'])# returns [9.16,[[1, ‘b’],[ ‘a’,7]]

 def duplicate_n_maker(n): #lambda on the fly func.


return lambda arg1:arg1*n
dup3 = duplicate_n_maker(3)
dup_str = dup3('go') # dup_str == 'gogogo'

12
Exception handling
 try:
f = open("file.txt") print "Unexpected:"
except IOError: print sys.exc_info()[0]
print "Could not open“
else: raise # re-throw caught
f.close() exception
 a = [1,2,3] try:
try: a[7] = 0
a[7] = 0 finally:
except (IndexError,TypeError):
print "IndexError caught” print "Will run regardless"
except Exception, e: • Easily make your own
print "Exception: ", e exceptions:
except: # catch everything

13
Classes
class MyVector: """A simple vector
class."""
num_created = 0 #USAGE OF CLASS MyVector
def __init__(self,x=0,y=0): print MyVector.num_created
self.__x = x v = MyVector()
w = MyVector(0.23,0.98)
self.__y = y
print w.get_size()
MyVector.num_created += 1
bool = isinstance(v,
def get_size(self):
MyVector)
return self.__x+self.__y
@staticmethod Output:
def get_num_created 0
return MyVector.num_created 1.21 14
I/O
# read binary records from a file import os

from struct import * print os.getcwd() #get “.”

fin = None os.chdir('..')

try: import glob # file globbing


fin = open("input.bin","rb") lst = glob.glob('*.txt') # get list of files
s = f.read(8) #easy to read in import shutil # mngmt tasks
while (len(s) == 8): shutil.copyfile('a.py','a.bak')
x,y,z = unpack(">HH<L", s)
print "Read record: " \
"%04x %04x %08x"%(x,y,z)
s = f.read(8)
except IOError:
pass
CS 331
if fin: fin.close() 15
Threading in Python
import threading
theVar = 1
class MyThread ( threading.Thread ):
def run ( self ):
global theVar
print 'This is thread ' + \
str ( theVar ) + ' speaking.‘
print 'Hello and good bye.’
theVar = theVar + 1
for x in xrange ( 10 ):
MyThread().start()

16
So what does Python have to do with
Internet and web programming?
 Jython & IronPython(.NET ,written in C#)
 Libraries – ftplib, snmplib, uuidlib, smtpd,
urlparse, SimpleHTTPServer, cgi, telnetlib,
cookielib, xmlrpclib, SimpleXMLRPCServer,
DocXMLRPCServer
 Zope(application server), PyBloxsom(blogger),
MoinMoin(wiki), Trac(enhanced wiki and
tracking system), and Bittorrent (6 no, but prior
versions yes)
17
Applications of Python
 Web Development: Django, Flask, Bottle, Pyramid
 Scientific and Numeric: SciPy, Pandas, numpy
 Desktop applications: pyqt, kivy, PyGUI, PyGTK, WxPython
 Databases: ODBC, MSSQL, PostgreSQL, Oracle
 Business: Odoo, Tryton
 Machine Learning and AI: Tensorflow, scikit-learn, theano,
caffe, keras
 Data Science: matplotlib, bokeh, seaborn, scrapy
 PenTesting: socket, scapy, libnmap, requests, mitmproxy,
spidey, urllib2 18
Python Interpreters
 http://www.python.org/download/
 http://pyaiml.sourceforge.net/
 http://www.py2exe.org/
 http://www.activestate.com/Products/ac
tivepython/
 http://www.wingware.com/
 http://pythonide.blogspot.com/
 Many more…

19
Python on your systems
 Its easy! Go to http://www.python.org/download/
 Download your architecture binary, or source
 Install, make, build whatever you need to do… plenty of info on
installation in readmes
 Make your first program! (a simple on like the hello world one
will do just fine)
 Two ways of running python code. Either in an interpreter or in a
file ran as an executable

20
Running Python
 Windows XP – double click the icon or call it from
the command line as such:

21
Python Interpreter
Python for the future
 Python 3
 Will not be Backwards compatible, they are
attempting to fix “perceived” security flaws.
 Print statement will become a print function.
 All text strings will be unicode.
 Support of optional function annotation, that can be
used for informal type declarations and other
purposes.

23
Python: Data Types
Python: String Indexing
Python: String Slicing
 Sometimes you may find it necessary to extract a portion of a
string from another string.
 You can use “slicing” notation in Python to extract a span of
characters from a string into a new string. We call this new
String a "substring"

26

You might also like