Python Unit 1
Python Unit 1
Dr. Anand M
Assistant Professor
Introduction to Python Programming
• Python is a very simple programming language so even if you are new
to programming, you can learn python without facing any issues.
• Python is a high-level, interpreted, interactive and object-oriented
scripting language. Python is designed to be highly readable. It uses
English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other
languages.
• Python is a MUST for students and working professionals to become a
great Software Engineer specially when they are working in Web
Development Domain.
Brief History of Python
• Invented in the Netherlands, early 90s by Guido van Rossum
• Named after Monty Python
• Open sourced from the beginning
• Considered a scripting language, but is much more
• Scalable, object oriented and functional from the beginning
• Used by Google from the beginning
• Increasingly popular
Python’s Benevolent Dictator For Life
*= Multiply AND assignment operator, It multiplies right operand with the left c *= a is equivalent to c =
operand and assign the result to left operand c*a
/= Divide AND assignment operator, It divides left operand with the right c /= a is equivalent to c = c
operand and assign the result to left operand /a
%= Modulus AND assignment operator, It takes modulus using two operands and c %= a is equivalent to c =
assign the result to left operand c %a
**= Exponent AND assignment operator, Performs exponential (power) calculation c **= a is equivalent to c =
on operators and assign value to the left operand c ** a
//= Floor Division and assigns a value, Performs floor division on operators and c //= a is equivalent to c =
assign value to the left operand c // a
Python Bitwise Operators:
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists (a & b) will give 12 which is
in both operands. 0000 1100
| Binary OR Operator copies a bit if it exists in either (a | b) will give 61 which is 0011
operand. 1101
^ Binary XOR Operator copies the bit if it is set in one (a ^ b) will give 49 which is
operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary and has the (~a ) will give -60 which is 1100
effect of 'flipping' bits. 0011
<< Binary Left Shift Operator. The left operands value is a << 2 will give 240 which is
moved left by the number of bits specified by the right 1111 0000
operand.
>> Binary Right Shift Operator. The left operands value is a >> 2 will give 15 which is
moved right by the number of bits specified by the right 0000 1111
operand.
Python Logical Operators:
Operator Description Example
and Called Logical AND operator. If both the operands are true (a and b) is true.
then then condition becomes true.
or Called Logical OR Operator. If any of the two operands are (a or b) is true.
non zero then then condition becomes true.
not Called Logical NOT Operator. Use to reverses the logical not(a and b) is false.
state of its operand. If a condition is true then Logical NOT
operator will make false.
Python Membership Operators:
In addition to the operators discussed previously, Python has membership operators, which test for
membership in a sequence, such as strings, lists, or tuples.
not in Evaluates to true if it does not finds a variable in the x not in y, here not in results in a 1
specified sequence and false otherwise. if x is a member of sequence y.
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~+- Ccomplement, unary plus and minus (method names for the last two are
+@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
The if Statement
• Control structure: logical design that controls order in which set of
statements execute
• Sequence structure: set of statements that execute in the order they
appear
• Decision structure: specific action(s) performed only if a condition
exists
• Also known as selection structure
The if Statement (cont’d.)
• In flowchart, diamond represents true/false condition that must be
tested
• Actions can be conditionally executed
• Performed only when a condition is true
• Single alternative decision structure: provides only one alternative
path of execution
• If condition is not true, exit the structure
The if Statement (cont’d.)
The if Statement (cont’d.)
• Python syntax:
if condition:
Statement
Statement
• First line known as the if clause
• Includes the keyword if followed by condition
• The condition can be true or false
• When the if statement executes, the condition is tested, and if it is true the block
statements are executed. otherwise, block statements are skipped
Python - IF... Statement
• The syntax of the if statement is:
if expression:
statement(s)
Example:
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
The if-else Statement
• Dual alternative decision structure: two possible paths of execution
– One is taken if the condition is true, and the other if the condition is false
• Syntax: if condition:
statements
else:
other statements
• if clause and else clause must be aligned
• Statements must be consistently indented
The if-else Statement (cont’d.)
The if-else Statement (cont’d.)
Python - IF...ELIF...ELSE Statement
if expression:
var1 = 100
statement(s)
if var1:
else:
print "1 - Got a true expression value"
statement(s)
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
Nested Decision Structures and the if-elif-
else Statement
• A decision structure can be nested inside another decision structure
• Commonly needed in programs
• Example:
• Determine if someone qualifies for a loan, they must meet two conditions:
• Must earn at least $30,000/year
• Must have been employed for at least two years
• Check first condition, and if it is true, check second condition
Nested Decision Structures and the if-elif-else
Statement (cont’d.)
• Important to use proper indentation in a nested decision structure
• Important for Python interpreter
• Makes code more readable for programmer
• Rules for writing nested if statements:
• else clause should align with matching if clause
• Statements in each block must be consistently indented
The if-elif-else Statement
• if-elif-else statement: special version of a decision structure
– Makes logic of nested decision structures simpler to write
• Can include multiple elif statements
Syntax: if condition1
statements
elif condition2
statements
else
statements
The if-elif-else Statement (cont’d.)
• Alignment used with if-elif-else statement:
if, elif, and else clauses are all aligned
Conditionally executed blocks are consistently indented
• if-elif-else statement is never required, but logic easier to follow
Can be accomplished by nested if-else
• Code can become complex, and indentation can cause problematic long lines
The Nested if...elif...else Construct
Example:
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression“
print "Good bye!"
Python - while Loop Statements
• The while loop is one of the looping constructs available in Python. The while loop continues until
the expression becomes false. The expression has to be a logical expression and must return
either a true or a false value
The syntax of the while loop is:
while expression:
statement(s)
Example:
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
The Infinite Loops:
• You must use caution when using while loops because of the possibility that this condition never
resolves to a false value. This results in a loop that never ends. Such a loop is called an infinite loop.
• An infinite loop might be useful in client/server programming where the server needs to run
continuously so that client programs can communicate with it as and when required.
• Example:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
OUT PUT
The continue Statement:
• The continue statement in Python returns the control to the beginning of the while loop. The
continue statement rejects all the remaining statements in the current iteration of the loop and
moves the control back to the top of the loop.
Example:
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"
continue STATEMENT
• The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The
function accomplishes nothing and finally this would produce following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments:
A function by using the following types of formal arguments::
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments:
• Required arguments are the arguments passed to a function in correct positional order.
def printme( str ): "This prints a passed string"
print str;
return;
printme();
• This would produce following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments:
• Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
• This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with
parameters.
def printme( str ): "This prints a passed string"
print str;
return;
printme( str = "My string");
• This would produce following result:
My string
Following example gives more clear picture. Note, here order of the parameter does
not matter:
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
• This would produce following result:
Name: miki Age 50
Default arguments:
• A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.
• Following example gives idea on default arguments, it would print default age if it is
not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
• This would produce following result:
Name: miki Age 50 Name: miki Age 35
Variable-length arguments:
• You may need to process a function for more arguments than you specified while defining the
function. These arguments are called variable-length arguments and are not named in the function
definition, unlike required and default arguments.
• The general syntax for a function with non-keyword variable arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
• An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function
call. For example:
def printinfo( arg1, *vartuple ):
"This is test"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 );
printinfo( 70, 60, 50 );
• This would produce following result:
Output is:
10
Output is:
70
60
50
The Anonymous Functions:
You can use the lambda keyword to create small anonymous functions. These functions are called anonymous
because they are not declared in the standard manner by using the def keyword.
• Lambda forms can take any number of arguments but return just one value in the form of an expression. They
cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an expression.
• Lambda functions have their own local namespace and cannot access variables other than those in their
parameter list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline
statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance
reasons.
• Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example:
• Following is the example to show how lembda form of function works:
sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
• This would produce following result:
Value of total : 30
Value of total : 40
Scope of Variables:
• All variables in a program may not be accessible at all locations in that program. This depends on where you
have declared a variable.
• The scope of a variable determines the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python:
Global variables
Local variables
• Global vs. Local variables:
• Variables that are defined inside a function body have a local scope, and those defined outside have a global
scope.
• This means that local variables can be accessed only inside the function in which they are declared whereas
global variables can be accessed throughout the program body by all functions. When you call a function, the
variables declared inside it are brought into scope.
• Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
• This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
Recursive Definitions
• A description of something that refers to itself is called a recursive
definition.
• In mathematics, recursion is frequently used. The most common
example is the factorial:
• For example, 5! = 5(4)(3)(2)(1), or
5! = 5(4!)
n ! n ( n 1) ( n 2 ) ...(1)
66
Recursive Definitions
• In other words, n ! n ( n 1) !
• Or 1 if n 0
n!
n ( n 1) ! o t h e r w is e
• This definition says that 0! is 1, while the factorial of any other
number is that number times the factorial of one less than that
number.
68
Recursive Definitions
• Factorial is not circular because we eventually get to 0!, whose
definition does not rely on the definition of factorial and is just 1. This
is called a base case for the recursion.
• When the base case is encountered, we get a closed expression that
can be directly computed.
69
Recursive Definitions
70
Recursive Functions
• We’ve seen previously that factorial can be calculated using a loop
accumulator.
• If factorial is written as a separate function:
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
71
Recursive Functions
• We’ve written a function that calls itself, a recursive function.
• The function first checks to see if we’re at the base case (n==0). If so,
return 1. Otherwise, return the result of multiplying n by the factorial
of n-1, fact(n-1).
72
Recursive Functions
>>> fact(4)
24
>>> fact(10)
3628800
>>> fact(100)
933262154439441526816992388562667004907159682643816214685929638952175999932299156089
41463976156518286253697920827223758251185210916864000000000000000000000000L
>>>
• Remember that each call to a function starts that function a new, with
its own copies of local variables and parameters.
73
Recursive Functions
74