KEMBAR78
Introduction to Python Basics | PPTX
Python – Basics
by Raghunath Akula
Python Overview
 Python is a great and friendly language to use & learn, can be
adapted to small & big projects.
 Open source general-purpose language and with great supports for
Oops.
 Python is formally an Interpreted language.
 Fast array operations – 2D / multi-D arrays, linear algebra etc.
 Easy to interface with Java / C / ObjC
 Offers Matlab-ish capabilities within Python.
Integer  num = 8
Float  num = 3.456
String  “abc” or ‘abc’
Triple double-quotes for multi-line strings
””” this is veryyy
long string…”””
Basic Datatypes
Whitespace
 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
 Start comments with # – the rest of line is ignored.
 Can include a “documentation string” as the first line of any
new function or class that you define.
 Multiline comments – ”””… ”””. Similar to /* */ in java.
Naming Rules
 Names are case sensitive and cannot start with a number. They can
contain letters, numbers, and underscores.
rax Rax _rax _2_rax_ rax_2 RaX
 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
 Binding a variable in Python means setting a name to hold a reference
to some object.
 Python determines the type of the reference automatically based on the
data object assigned to it.
 Name is created for 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.
>>> fname, lname = ‘Raghu’, ‘Akula’
>>> fname
‘Raghu’
>>> lname
‘Akula’
Identifiers
 Logical Operator
not unary negation
and conditional_and
or conditional_or
 Equality Operator
is same identity
is not different identity
== equivalent
!= not equivalent
 Comparison Operator
< less than
< = less than or equal to
> greater than
> = greater than or equal to
 Arithmetic Operator
+ addition
− subtraction
* multiplication
/ true division
// integer division
% modulo operator
Operators And Expressions
 Bitwise Operator
∼ bitwise complement (prefix unary operator)
& bitwise and
| bitwise or
ˆ bitwise exclusive-or
<< shift bits left, filling in with zeros
>> shift bits right, filling in with sign bit
 Sequence Operator
s[j] element at index j
s[start:stop] slice including indices [start,stop)
s + t concatenation of sequences
k * s shorthand for s + s +... (k times)
val in s containment check
val not in s non-containment check
Control Flow
 Conditional
if a > 10:
print (“a is greater than 10.”)
eif a < 10:
print (“a is lesser than 10.”)
else
print (“a is equals to 10.”)
 While Loop
n = 20
s = 0
count = 1
while counter <= n:
s = s + count
count += 1
print (“Sum = ”, count)
 For Loop
# Squares of numbers [1,4,9,16,…]
squares = []
for k in range(1, n+1):
squares.append(k*k)
# with List comprehension
squares = [k*k for k in range(1, n+1)]
 Break & Continue
x = 3
While x < 10 :
if x > 7 :
x = x + 2
continue
x = x + 1
print “Inside loop.”
if x == 8:
break
 Python is a dynamically typed language, types are dynamically designated to
parameter(s).
 Each time a function is called, Python creates a dedicated activation
record that stores information relevant to the current call.
 “def” creates a function and assigns it a name
>>> def function_name(arg1, arg2, ..., argN):
<statements>
return
>>> def compute_gradeAverage(grades):
points{‘A’:5, ‘B’:4, ‘C’:3, ‘D’:2, ‘E’:1}
num_courses = 0
total_points = 0
for g in grades:
num_courses += 1
total_points += points[g]
return total_points / num_courses
Functions
 Identifiers used to describe the expected parameters are known as formal
parameters, and the objects sent by the caller when invoking the function
are the actual parameters.
 A caller can invoke a function with varying number of actual parameters
 Changing a mutable argument may affect the caller
>>> def sum(arg_1,arg_2):
total = arg_1 + arg_2
return total
 Can define defaults for arguments that need not be passed
>>> def func(a, b, c=10, d=100):
print a, b, c, d
>>> func(1,2)
1 2 10 100
>>> func(1,2,3,4)
1,2,3,4
Functions – Passing Arguments
Exception Handling
 Exceptions are unexpected events that occur during the execution of a
program.
 An exception might result from a logical error or an unanticipated
situation.
 A raised error may be caught by a surrounding context that handles the
exception in an appropriate fashion.
 If uncaught, an exception causes the interpreter to stop executing
 The try-except clause is best used when there is reason to believe that
the exceptional case is relatively unlikely
 Particularly useful when working with user input or when reading /
writing to files
>>> try:
<statements>
except:
print(“error statement”)
finally:
print(“gets executed no matter what”)
Thank you!!

Introduction to Python Basics

  • 1.
    Python – Basics byRaghunath Akula
  • 2.
    Python Overview  Pythonis a great and friendly language to use & learn, can be adapted to small & big projects.  Open source general-purpose language and with great supports for Oops.  Python is formally an Interpreted language.  Fast array operations – 2D / multi-D arrays, linear algebra etc.  Easy to interface with Java / C / ObjC  Offers Matlab-ish capabilities within Python.
  • 3.
    Integer  num= 8 Float  num = 3.456 String  “abc” or ‘abc’ Triple double-quotes for multi-line strings ””” this is veryyy long string…””” Basic Datatypes Whitespace  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
  • 4.
    Comments  Start commentswith # – the rest of line is ignored.  Can include a “documentation string” as the first line of any new function or class that you define.  Multiline comments – ”””… ”””. Similar to /* */ in java. Naming Rules  Names are case sensitive and cannot start with a number. They can contain letters, numbers, and underscores. rax Rax _rax _2_rax_ rax_2 RaX  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
  • 5.
     Binding avariable in Python means setting a name to hold a reference to some object.  Python determines the type of the reference automatically based on the data object assigned to it.  Name is created for 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. >>> fname, lname = ‘Raghu’, ‘Akula’ >>> fname ‘Raghu’ >>> lname ‘Akula’ Identifiers
  • 6.
     Logical Operator notunary negation and conditional_and or conditional_or  Equality Operator is same identity is not different identity == equivalent != not equivalent  Comparison Operator < less than < = less than or equal to > greater than > = greater than or equal to  Arithmetic Operator + addition − subtraction * multiplication / true division // integer division % modulo operator Operators And Expressions  Bitwise Operator ∼ bitwise complement (prefix unary operator) & bitwise and | bitwise or ˆ bitwise exclusive-or << shift bits left, filling in with zeros >> shift bits right, filling in with sign bit  Sequence Operator s[j] element at index j s[start:stop] slice including indices [start,stop) s + t concatenation of sequences k * s shorthand for s + s +... (k times) val in s containment check val not in s non-containment check
  • 7.
    Control Flow  Conditional ifa > 10: print (“a is greater than 10.”) eif a < 10: print (“a is lesser than 10.”) else print (“a is equals to 10.”)  While Loop n = 20 s = 0 count = 1 while counter <= n: s = s + count count += 1 print (“Sum = ”, count)  For Loop # Squares of numbers [1,4,9,16,…] squares = [] for k in range(1, n+1): squares.append(k*k) # with List comprehension squares = [k*k for k in range(1, n+1)]  Break & Continue x = 3 While x < 10 : if x > 7 : x = x + 2 continue x = x + 1 print “Inside loop.” if x == 8: break
  • 8.
     Python isa dynamically typed language, types are dynamically designated to parameter(s).  Each time a function is called, Python creates a dedicated activation record that stores information relevant to the current call.  “def” creates a function and assigns it a name >>> def function_name(arg1, arg2, ..., argN): <statements> return >>> def compute_gradeAverage(grades): points{‘A’:5, ‘B’:4, ‘C’:3, ‘D’:2, ‘E’:1} num_courses = 0 total_points = 0 for g in grades: num_courses += 1 total_points += points[g] return total_points / num_courses Functions
  • 9.
     Identifiers usedto describe the expected parameters are known as formal parameters, and the objects sent by the caller when invoking the function are the actual parameters.  A caller can invoke a function with varying number of actual parameters  Changing a mutable argument may affect the caller >>> def sum(arg_1,arg_2): total = arg_1 + arg_2 return total  Can define defaults for arguments that need not be passed >>> def func(a, b, c=10, d=100): print a, b, c, d >>> func(1,2) 1 2 10 100 >>> func(1,2,3,4) 1,2,3,4 Functions – Passing Arguments
  • 10.
    Exception Handling  Exceptionsare unexpected events that occur during the execution of a program.  An exception might result from a logical error or an unanticipated situation.  A raised error may be caught by a surrounding context that handles the exception in an appropriate fashion.  If uncaught, an exception causes the interpreter to stop executing  The try-except clause is best used when there is reason to believe that the exceptional case is relatively unlikely  Particularly useful when working with user input or when reading / writing to files >>> try: <statements> except: print(“error statement”) finally: print(“gets executed no matter what”)
  • 11.