Introduction to Python For Diploma Students

SanjaySampat1 33 views 49 slides Sep 28, 2024
Slide 1
Slide 1 of 49
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49

About This Presentation

Python introduction for the Diploma level students


Slide Content

Introduction to PythonIntroduction to Python
ByBy
Dr. S N SampatDr. S N Sampat
Venue: Government Polytechnic For Girls, SuratVenue: Government Polytechnic For Girls, Surat
Sep 28, 2024 1

What is Python?
A Open source programming language with powerful
typing and object oriented features.
•Commonly used for producing HTML content on websites. Great for
text files.
•Useful for Data Science, AI, NLP, Embedded Hardware development
•Very Good Library Support
•Useful built-in types (lists, dictionaries).
•Clean syntax, dynamic interpreter, powerful extensions,
•Efficient high-level data structures and a simple but effective
approach to object-oriented programming
Sep 28, 2024 2

Why Python?
•Natural Language ToolKit
•Ease of use; interpreter
•AI Processing: Symbolic
•Python’s built-in datatypes for strings, lists, and more.
•Java or C++ require the use of special classes for this.
•AI Processing: Statistical
•Python has strong numeric processing capabilities: matrix
operations, etc.
•Suitable for probability and machine learning code.
Sep 28, 2024 3

Great Applications based on Python by Big Companies
1.Dropbox: client side programs are coded in Python
2.Instagram: high-level Python web framework
3.IBM: Deployment of Web Server- IBM Bluemix, Python SDK
for Watson (Big data and AI)
4.Netflix: Audio and video streaming
 recommendation and
analytics engine based on Python
5.Spotify: For music, Back end analysis based on Python
6.Facebook : 21 % code based on Python
7.Google: Most of Youtube code in Python
Sep 28, 2024 4

Python On line Resources
•https://python.org
•Things to read through
•“Dive into Python” (Chapters 2 to 4)
http://diveintopython.org/
•Things to refer to
•The Official Python Tutorial
https://docs.python.org/3/tutorial/
•The Python Quick Reference
http://rgruet.free.fr/PQR27/PQR2.7.html
•Python Books
https://pythonbooks.org/
Sep 28, 2024 5

Installing Python
•Python for Win/Mac/Unix/Linux is available from
www.python.org.
•Generally an easy install.
•On macs, already part of OS X.
•For NLTK you need Python 2.3 or higher.
•GUI development environment: IDLE.
•Anaconda – an integrated package of Python
•Spyder ( Scientific GUI development environment)
•jupyter lab and notebook (Web based interactive dev. Environment)
• PyQt GUI console (inline figures, multiline input, Graphical calltips)
•,Glueviz ( multidimensional data visualization across files )
•Orange3 ( component based data mining framework)
•R Studio ( For open source R language )
•VS Code (editor for debugging, version control, task management)
Sep 28, 2024 6

IDLE Development Environment
•Shell for interactive evaluation.
•Text editor with color-coding and smart indenting for creating
python files.
•Menu commands for changing system settings and running
files.
•We will use IDLE
Sep 28, 2024 7

Overview
•Names & Assignment
•Data types
•Sequences types: Lists, Tuples, and Strings
•Mutability
•Understanding Reference Semantics in Python
Sep 28, 2024 8

A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
Sep 28, 2024 9

Enough to Understand the Code
Indentation matters to meaning the code
Block structure indicated by indentation
The first assignment to a variable creates it
Dynamic typing: no declarations, names don’t have types,
objects do
Assignment uses = and comparison uses ==
For numbers + - * / % are as expected.
Use of + for string concatenation.
Use of % for string formatting (like printf in C)
Logical operators are words (and,or,not)
not symbols
The basic printing command is print
Sep 28, 2024 10

Basic Datatypes
Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
Floats
x = 3.456
Strings
Can use ”…" or ’…’ to specify, "foo" == 'foo’
Unmatched can occur within the string
“John’s” or ‘John said “foo!”.’
Use triple double-quotes for multi-line strings or strings than
contain both ‘ and “ inside of them:
“““a‘b“c”””
Sep 28, 2024 11

Whitespace
Whitespace is meaningful in Python, especially
indentation and placement of newlines
Use a newline to end a line of code
Use \ when must go to next line prematurely
No braces {} to mark blocks of code, use consistent
indentation instead
•First line with less indentation is outside of the block
•First line with more indentation starts a nested block
Colons start of a new block in many constructs, e.g.
function definitions, then clauses
Sep 28, 2024 12

Comments
Start comments with #, rest of line is ignored
Can include a “documentation string” as the first line of
a new function or class you define
Development environments, debugger, and other tools
use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive integer
and returns facorial of n. ”””
assert(n>0)
return 1 if n==1 else n*fact(n-1)
Sep 28, 2024 13

Assignment
Binding a variable in Python means setting a name to hold
a reference to some object
Assignment creates references, not copies
Names in Python don’t have an intrinsic type, objects have
types
Python determines type of the reference auto-matically
based on what data is assigned to it
You create a name the first time it appears on the left side
of an assignment expression:
x = 3
A reference is deleted via garbage collection after any
names bound to it have passed out of scope
Sep 28, 2024 14

Naming Rules
Names are case sensitive and cannot start with a
number. They can contain letters, numbers, and
underscores.
bob Bob _bob _2_bob_ bob_2 BoB
There are some reserved words:
and, assert, break, class, continue, def,
del, elif, else, except, exec, finally, for,
from, global, if, import, in, is, lambda,
not, or, pass, print, raise, return, try,
while
Sep 28, 2024 15

Variables
Sep 28, 2024 16
No need to declare
Need to assign (initialize)
use of uninitialized variable raises exception
Dynamically typed
if friendly:
greeting = "hello world"
else:
greeting = 12**2
print greeting
Everything is a "variable":
Even functions, classes, modules

Reference Semantics
Sep 28, 2024 17
Assignment manipulates references
x = y does not make a copy of y
x = y makes x reference the object y references
Very useful; but beware!
Example:
>>> a = [1, 2, 3]
>>> b = a
>>> a.append(4)
>>> print b
[1, 2, 3, 4]

Control Structures
Sep 28, 2024 18
if condition:
statements
[elif condition:
statements] ...
[else:
statements]
while condition:
statements
for var in sequence:
statements
break
continue

Grouping Indentation
Sep 28, 2024 19
In Python:
for i in range(20):
if i%3 == 0:
print i
if i%5 == 0:
print "Bingo!"
print "---"
In C:
for (i = 0; i < 20; i++)
{
if (i%3 == 0) {
printf("%d\n", i);
if (i%5 == 0) {
printf("Bingo!\n"); }
}
printf("---\n");
}
0
Bingo!
---
---
---
3
---
---
---
6
---
---
---
9
---
---
---
12
---
---
---
15
Bingo!
---
---
---
18
---
---

Naming conventions
The Python community has these recommended
naming conventions
joined_lower for functions, methods and, attributes
joined_lower or ALL_CAPS for constants
StudlyCaps for classes
camelCase only to conform to pre-existing
conventions
Attributes: interface, _internal, __private
Sep 28, 2024 20

Python PEPs
Where do such conventions come from?
The community of users
Codified in PEPs
Python's development is done via the Python
Enhancement Proposal (PEP) process
PEP: a standardized design document, e.g. proposals,
descriptions, design rationales, and explanations for
language features
Similar to IETF RFCs
See the PEP index
PEP 8: Style Guide for Python Code
Sep 28, 2024 21

Accessing Non-Existent Name
Accessing a name before it’s been properly created
(by placing it on the left side of an assignment), raises
an error
>>> y
Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevel-
y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3
Sep 28, 2024 22

Numbers
Sep 28, 2024 23
C-style shifting & masking
1 << 16, x & 0xff, x | 1, ~x, x^y
Integer division truncates
1/2 -> 0# 1./2 -> 0.5, float(1)/2 -> 0.5
Long (arbitrary precision), complex
2**100 -> 1267650600228229401496703205376L
1j**2 -> (-1+0j)

String
Sep 28, 2024 24
"hello"+"world""helloworld"# concatenation
"hello"*3 "hellohellohello" # repetition
"hello"[0] "h" # indexing
"hello"[-1] "o" # (from end)
"hello"[1:4] "ell" # slicing
"hello"[::2] "hlo" # more slicing
len("hello") 5 # size
"hello" < "jello”True # comparison
"e" in "hello"True # search
'single quotes' """triple quotes""" r"raw strings"

String continued
Sep 28, 2024 25
Formatted Strings
>>> "Pi: %.5f - Pi/2: %.5f" % (math.pi, math.pi/2)
'Pi: 3.14159 - Pi/2: 1.57080'
Splitting
>>> "The quick brown fox jumps".split()
['The', 'quick', 'brown', 'fox', 'jumps']
Joining
>>> '?'.join(['The', 'quick', 'brown', 'fox', 'jumps'])
'The?quick?brown?fox?jumps'

Everything is an object
Python data is represented by objects or by relations
between objects
Every object has an identity, a type and a value
Identity never changes once created Location or
address in memory
Type (e.g., integer, list) is unchangeable and
determines the possible values it could have and
operations that can be applied
Value of some objects is fixed (e.g., an integer) and
can change for others (e.g., list)
Sep 28, 2024 26

Python’s built-in type hierarchy
Sep 28, 2024 27

Sequence Types
Sequences are containers that hold objects
Finite, ordered, indexed by integers
Tuple: (1, “a”, [100], “foo”)
Tuple is An immutable ordered sequence of items
Strings: “foo bar”
Strings can be of mixed types, including collection types
An immutable ordered sequence of chars
Conceptually very much like a tuple
List: [“one”, “two”, 3]
A Mutable ordered sequence of items of mixed types
Sep 28, 2024 28

Similar SyntaxSimilar Syntax
All three sequence types (tuples, strings, and
lists) share much of the same syntax and
functionality.
Key difference:
Tuples and strings are immutable
Lists are mutable
The operations shown in this section can be
applied to all sequence types
most examples will just show the operation
performed on one
Sep 28, 2024 29

Sequence Types 1
Define tuples using parentheses and commas
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
Define lists are using square brackets and commas
>>> li = [“abc”, 34, 4.34, 23]
Define strings using quotes (“, ‘, or “””).
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “””This is a multi-line
string that uses triple quotes.”””
Sep 28, 2024 30

Sequence Types 2Sequence Types 2
Access individual members of a tuple, list, or string
using square bracket “array” notation
Note that all are 0 based…
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> tu[1] # Second item in the tuple.
‘abc’
>>> li = [“abc”, 34, 4.34, 23]
>>> li[1] # Second item in the list.
34
>>> st = “Hello World”
>>> st[1] # Second character in string.
‘e’
Sep 28, 2024 31

Positive and negative indices
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Positive index: count from the left, starting with 0
>>> t[1]
‘abc’
Negative index: count from right, starting with –1
>>> t[-3]
4.56
Sep 28, 2024 32

Slicing: Return Copy of a Subset
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Returns copy of container with subset of original
members. Start copying at first index, and stop
copying before the second index
>>> t[1:4]
(‘abc’, 4.56, (2,3))
You can also use negative indices
>>> t[1:-1]
(‘abc’, 4.56, (2,3))
Sep 28, 2024 33

Slicing: Return Copy of a Subset
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Omit first index to make a copy starting from the
beginning of container
>>> t[:2]
(23, ‘abc’)
Omit second index to make a copy starting at 1st index
and going to end of the container
>>> t[2:]
(4.56, (2,3), ‘def’)
Sep 28, 2024 34

Copying the Whole Sequence
[ : ] makes a copy of an entire sequence
>>> t[:]
(23, ‘abc’, 4.56, (2,3), ‘def’)
Note the difference between these two lines for
mutable sequences
>>> l2 = l1 # Both refer to same ref,
# changing one affects both
>>> l2 = l1[:] # Independent copies, two refs

Sep 28, 2024 35

The ‘in’ Operator
Boolean test whether a value is inside a container:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
For strings, tests for substrings
>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False
Careful: the in keyword is also used in the syntax of for loops
and list comprehensionsSep 28, 2024 36

+ Operator is Concatenation
The + operator produces a new tuple, list, or string
whose value is the concatenation of its arguments.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> “Hello” + “ “ + “World”
‘Hello World’
Sep 28, 2024 37

Lists are mutable
>>> li = [‘abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]
We can change lists in place.
Name li still points to the same memory
reference when we’re done.
Sep 28, 2024 38

Tuples are immutable
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14
Traceback (most recent call last):
File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment
You can’t change a tuple.
You can make a fresh tuple and assign its reference to
a previously used name.
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
The immutability of tuples means they are faster than
lists
Sep 28, 2024 39

Functions vs. methods
Some operations are functions and others methods
Remember that (almost) everything is an object
You just have to learn (and remember or lookup) which operations are
functions and which are methods
len() is a function on collec-
tions that returns the num-
ber of things they contain
>>> len(['a', 'b', 'c'])
3
>>> len(('a','b','c'))
3
>>> len("abc")
3
index() is a method on col-
lections that returns the
index of the 1st occurrence
of its arg
>>> ['a’,'b’,'c'].index('a')
0
>>> ('a','b','c').index('b')
1
>>> "abc".index('c')
2
Sep 28, 2024 40

Lists methods
Lists have many methods, including index, count,
append, remove, reverse, sort, etc.
Many of these modify the list
>>> l = [1,3,4]
>>> l.append(0) # adds a new element to the end of the list
>>> l
[1, 3, 4, 0]
>>> l.insert(1,200) # insert 200 just before index position 1
>>> l
[1, 200, 3, 4, 0]
>>> l.reverse() # reverse the list in place
>>> l
[0, 4, 3, 200, 1]
>>> l.sort() # sort the elements. Optional arguments can
give
>>> l # the sorting function and direction
[0, 1, 3, 4, 200]
>>> l.remove(3) # remove first occurence of element from
list
>>> l
[0, 1, 4, 200]
Sep 28, 2024 41

Tuple details
The comma is the tuple creation operator, not parens
>>> 1,
(1,)
Python shows parens for clarity (best practice)
>>> (1,)
(1,)
Don't forget the comma!
>>> (1)
1
Trailing comma only required for singletons others
Empty tuples have a special syntactic form
>>> ()
()
>>> tuple()
()
Sep 28, 2024 42

Tuples vs. Lists
Lists slower but more powerful than tuples
Lists can be modified and they have many handy operations
and methods
Tuples are immutable & have fewer features
Sometimes an immutable collection is required (e.g., as a
hash key)
Tuples used for multiple return values and parallel
assignments
x,y,z = 100,200,300
old,new = new,old
Convert tuples and lists using list() and tuple():
mylst = list(mytup); mytup = tuple(mylst)
Sep 28, 2024 43

List discussionList discussion
Sep 28, 2024 44
Flexible arrays, not linked lists
a = [99, "bottles of beer", ["on", "the", "wall"]]
Same operators as for strings
a+b, a*3, a[0], a[-1], a[1:], len(a)
Item and slice assignment
a[0] = 98
a[1:2] = ["bottles", "of", "beer"]
-> [98, "bottles", "of", "beer", ["on", "the", "wall"]]
del a[-1]# -> [98, "bottles", "of", "beer"]

List Discussion continue
Sep 28, 2024 45
>>> a = range(5) # [0,1,2,3,4]
>>> a.append(5) # [0,1,2,3,4,5]
>>> a.pop() # [0,1,2,3,4]
5
>>> a.insert(0, 42)# [42,0,1,2,3,4]
>>> a.pop(0) # [0,1,2,3,4]
42
>>> a.reverse() # [4,3,2,1,0]
>>> a.sort() # [0,1,2,3,4]

Dictionaries
Sep 28, 2024 46
Hash tables, "associative arrays"
d = {"duck": "eend", "water": "water"}
Lookup:
d["duck"] -> "eend"
d["back"] # raises KeyError exception
Insert, delete, overwrite:
d["back"] = "rug" # {"duck": "eend", "water": "water",
"back": "rug"}
del d["water"] # {"duck": "eend", "back": "rug"}
d["duck"] = "duik" # {"duck": "duik", "back": "rug"}

More Dictionary Operations
Sep 28, 2024 47
Keys, values, items:
d.keys() -> ["duck", "back"]
d.values() -> ["duik", "rug"]
d.items() -> [("duck","duik"), ("back","rug")]
Presence check:
d.has_key("duck") -> True
d.has_key("spam") -> False
"duck" in d -> True; "spam" in d -> False
Values of any type; keys almost any
{"name":"Bryce", "age":22, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}

Dictionary Detail
Sep 28, 2024 48
Keys must be immutable:
numbers, strings, tuples of immutables
these cannot be changed after creation
reason is hashing (fast lookup technique)
not lists or other dictionaries
these types of objects can be changed "in
place"
no restrictions on values
Keys will be listed in arbitrary order
again, because of hashing

Thank You All
Questions Please
Sep 28, 2024 49
Tags