You are on page 1of 14

PYTHON

Python Overview
 Python is a great and friendly language to use & learn, can be adapted to
small & big projects.
 Open source.
 Can use both procedure oriented and OOPS concepts
 Dynamic typed language- don’t have to explicitly declare variable
 Python is formally an Interpreted language.
 Easy to interface with Java / C / ObjC
 Built-in-data structures – Lists, tuples, dicts
Python Installation
 Windows
 Visit https://www.python.org/downloads/ and download
the latest version.
 Set path
 Python interpreter or idle
 Linux
 Already installed
 Python (alt+f2)
Python Interactive Shell

% python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

You can type things directly into a running Python session


>>> 2+3*4
14
>>> name = "Andrew"
>>> name
'Andrew'
>>> print "Hello", name
Hello Andrew
>>>
Syntax
 Whitespace is used to denote blocks. In other languages
curly brackets { … } are common.
 When you indent, it becomes a child of the previous
line.
 The parent can also has a colon(:) following it.
>>> Parent:
child_1:
grand_child_1
child_2:
grand_child_2

Comments
 Starts with #
Variables
 Binding between a name and an object
 Single variable assignment: x = 1
 Multi variable assignment: x, y = 1, 2
 Swap values: x, y = y, x
 Variables are examples of identifiers
 First char must be alphabet or _, followed by
digit/alphabet/_
Input & Output
 Input(“enter a number “)
 raw_input – takes input in string form
Output:
Print(“name”)
Print ‘{0} age is {1}’,format(name,age)
Print “name”
print "Name:", name, "\nAge:", age

Escape Sequences
 \\ - backslash- print ‘\\’ -- \
 \’ - prints single quote –
 \’’ – double quote
 \n – new lone
Data Types

 Numbers: int (Integers), float (Real Numbers), bool


(Boolean, a subset of int)
 Immutable Types: str (string), tuples
 Mutable Types: list, set, dict (dictionary)
 Sequence Types: str, tuple, list
 Determining the type of an object: type()
Types and Operators: Operations on Numbers

 Basic algebraic operations


 Four arithmetic operations: a+b, a-b, a*b, a/b
 Exponentiation: a**b
 Other elementary functions are not part of standard Python, but included in packages
like NumPy and SciPy
 Comparison operators
 Greater than, less than, etc.: a < b, a > b, a <= b, a >= b
 Identity tests: a == b, a != b
 Bitwise operators
 Bitwise or: a | b
 Bitwise exclusive or: a ^ b # Don't confuse this with exponentiation
 Bitwise and: a & b
 Shift a left or right by b bits: a << b, a >> b
Types and Operators: Strings and Operations

 Strings are ordered blocks of text


 Strings are enclosed in single or double quotation marks
 Triple quotes is used for multiple lines
 Immutable – once created can’t be changed
 Examples: 'abc', “ABC”
 Concatenation and repetition
 Strings are concatenated with the + sign:
>>> 'abc'+'def'
'abcdef'
 Strings are repeated with the * sign:
>>> 'abc'*3
'abcabcabc'
Types and Operators: Indexing and Slicing
 Indexing and slicing
 Python starts indexing at 0. A string s will have indexes running from 0 to len(s)-1
(where len(s) is the length of s) in integer quantities.
 s[i] fetches the ith element in s
>>> s = 'string'
>>> s[1]
't'
 >>>s[i:j] fetches elements i (inclusive) through j (not inclusive)
>>> s[1:4]
'tri'
 s[:j] fetches all elements up to, but not including j
>>> s[:3]
'str'
 s[i:] fetches all elements from i onward (inclusive)
>>> s[2:]
'ring'
 Indexing and slicing, contd.
 s[i:j:k] extracts every kth element starting with index i (inlcusive) and ending with
index j (not inclusive)
>>> s[0:5:2]
'srn'
 Python also supports negative indexes. For example, s[-1] means extract the first
element of s from the end (same as s[len(s)-1])
>>> s[-1]
'g'
>>> s[-2]
'n'
String Methods

 >>> line = " # This is a comment line \n"


>>> line.strip()
'# This is a comment line'
 email.startswith(“c") endswith(“u”)
True/False
 >>> names = [“Ben", “Chen", “Yaqin"]

>>> ", ".join(names)


‘Ben, Chen, Yaqin‘

 >>> “chen".upper()
‘CHEN'
Operators And Expressions
 Logical Operator  Bitwise Operator
not unary negation ∼ bitwise complement (prefix unary operator)
and conditional_and & bitwise and
or conditional_or | bitwise or
ˆ bitwise exclusive-or
<< shift bits left, filling in with zeros
 Equality Operator >> shift bits right, filling in with sign bit
is same identity
is not different identity
== equivalent  Sequence Operator
!= not equivalent s[j] element at index j
s[start:stop] slice including indices
[start,stop)
 Comparison Operator s + t concatenation of sequences
< less than k * s shorthand for s + s +... (k
< = less than or equal to times)
> greater than val in s containment check
> = greater than or equal to val not in s non-containment check

 Arithmetic Operator
+ addition
− subtraction
* multiplication
/ true division
// integer division
% modulo operator

You might also like