Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

PYTHON BASICS

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

“Python is an experiment in how much


freedom program-mers need. Too much
freedom and nobody can read another's
code; too little and expressive-ness is
endangered.”
- Guido van Rossum
http://docs.python.org/
The Python tutorial is good!
Advantages of Python
• Python is Interpreted − Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it. This is
similar to PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers to
games.
Features of Python programming
Installing
• Python is pre-installed on most Unix systems, including Linux and MAC
OS X
• The pre-installed version may not be the most recent one
• Download from http://python.org/download/
• Python comes with a large library of standard modules
• There are several options for an IDE
• IDLE – works well with Windows
• Emacs with python-mode or your favorite text editor
• Eclipse with Pydev (http://pydev.sourceforge.net/)
Python Interpreter and Interactive Mode
• Python is an interpreted object-oriented programming language. By
interpreted it is meant that each time a program is run the interpreter
checks through the code for errors and then interprets the
instructions into machine-readable byte code.
• An interpreter is a translator in computer's language which translates
the given code line-by-line in machine readable byte codes. And if any
error is encountered it stops the translation until the error is fixed.
Unlike C language, which is a compiled programming language. The
compiler translates the whole code in one-go rather than line-by-line.
This is the reason why in C language, all the errors are listed during
compilation only.
Python Interpreter and Interactive Mode
• Python is interactive. When a Python statement is entered, and is
followed by the Return key, if appropriate, the result will be printed
on the screen, immediately, in the next line. This is particularly
advantageous in the debugging process. In interactive mode of
operation, Python is used in a similar way as the Unix command line
or the terminal.
• Interactive Python is very much helpful for the debugging purpose. It
simply returns the >>> prompt or the corresponding output of the
statement if appropriate and returns error for incorrect statements. In
this way if you have any doubts like: whether a syntax is correct,
whether the module you are importing exists or anything like that,
you can be sure within seconds using Python interactive mode.
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
Variables and Identifiers
• Variables: Variables are a very important role in Programming
Language, you can store any piece of information in a variable.
Variables are nothing but it’s just parts of your computer’s memory
where information is stored. Variables are reserved memory locations
that store the values. So, each variable is given an appropriate name,
every variable is assigned a name that can be used to refer to the
value in the program.
• Identifiers: Identifiers are as the name suggests and the names given
to identify something. This something can be a variable, function,
class, module or object.
Basic Rules for Python Variables or identifiers
1. The first character of an identifier may be an underscore (‘_’) or the
first character of an identifier starting with a letter must be
lowercase or upper case.
2. The rest of the identifier name can be underscored (‘_’)
3. Identifier names are case sensitive, Example: Python
4. Punctuation characters such as @, $, %, the characters of This type
are not allowed.
Operators
Python has many operators. Some examples are:
+, -, *, /, %, >, <, ==
print
Operators perform an action on one or more operands. Some
operators accept operands before and after themselves:
operand1 + operand2, or 3 + 5
Others are followed by one or more operands until the end of the line,
such as: print “Hi!”, 32, 48
When operators are evaluated, they perform action on their operands,
and produce a new value.
15
Example Expression Evaluations
An expression is any set of values and operators that will produce a
new value when evaluated. Here are some examples, along with the
new value they produce when evaluated:
5 + 10 produces 15
“Hi” + “ “ + “Jay!” produces “Hi Jay!”
10 / (2+3) produces 2
10 > 5 producesTrue
10 < 5 producesFalse
10 / 3.5 produces2.8571428571
10 / 3 produces3
10 % 3 produces1
16
Python - Basic Operators
Python language supports following type of operators.
• Arithmetic Operators
• Comparision Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Python Arithmetic Operators:
Operator Description Example
+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left hand a - b will give -10
operand
* Multiplication - Multiplies values on either side of the a * b will give 200
operator
/ Division - Divides left hand operand by right hand b / a will give 2
operand
% Modulus - Divides left hand operand by right hand b % a will give 0
operand and returns remainder
** Exponent - Performs exponential (power) calculation on a**b will give 10 to the power
operators 20
// Floor Division - The division of operands where the result 9//2 is equal to 4 and 9.0//2.0
is the quotient in which the digits after the decimal point is equal to 4.0
are removed.
Python Comparison Operators:
Operator Description Example
== Checks if the value of two operands are equal or not, if yes then (a == b) is not true.
condition becomes true.
!= Checks if the value of two operands are equal or not, if values are not (a != b) is true.
equal then condition becomes true.
<> Checks if the value of two operands are equal or not, if values are not (a <> b) is true. This is similar
equal then condition becomes true. to != operator.
> Checks if the value of left operand is greater than the value of right (a > b) is not true.
operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right (a < b) is true.
operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value (a >= b) is not true.
of right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of (a <= b) is true.
right operand, if yes then condition becomes true.
Python Assignment Operators:
Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left c = a + b will assigne value
side operand of a + b into c
+= Add AND assignment operator, It adds right operand to the left operand and c += a is equivalent to c =
assign the result to left operand c+a
-= Subtract AND assignment operator, It subtracts right operand from the left c -= a is equivalent to c = c
operand and assign the result to left operand -a

*= 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.

Operator Description Example

in Evaluates to true if it finds a variable in the specified x in y, here in results in a 1 if x is a


sequence and false otherwise. member of sequence y.

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.

Following loop will continue till you enter CTRL+C :


while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
print "Good bye!"
Single Statement Suites:
• Similar to the if statement syntax, if your while clause consists only of a single statement, it may be
placed on the same line as the while header.

• Here is the syntax of a one-line while clause:

while expression : statement


Python - for Loop Statements
• The for loop in Python has the ability to iterate over the items of any sequence, such as a list or a
string.
• The syntax of the loop look is:
for iterating_var in sequence:
statements(s)
Example:
for letter in 'Python': # First Example
print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
for Loop Statements - Example
Iterating by Sequence Index:
• An alternative way of iterating through each item is by index offset into the sequence itself:

• Example:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "Good bye!"


Python break, continue and pass Statements
The break Statement:
• The break statement in Python terminates the current loop and resumes execution at the next statement,
just like the traditional break found in C.
Example:
for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
print "Good bye!"
break STATEMENT

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

when i value becomes 2 the print statement gets skipped, continue


statement goes for next iteration, hence in the out put 2 is not printed
Python - Functions
• A function is a block of organized, reusable code that is used to perform
a single, related action. Functions provides better modularity for your
application and a high degree of code reusing.
• As you already know, Python gives you many built-in functions like
print() etc. but you can also create your own functions. These functions
are called user-defined functions.
Defining a Function
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also define parameters
inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string of the function or
docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None.
• Syntax:
• def functionname( parameters ):
• "function_docstring" function_suite return [expression]
Functions : Example
• Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior, and you need to inform them in the same order that
they were defined.
• Example:
def printme( str ):
"This prints a passed string function"
print str
return
Calling a Function
• Following is the example to call printme() function:
def printme( str ): "This is a print function“
print str;
return;

printme("I'm first call to user defined function!");


printme("Again second call to the same function");

• This would produce following result:


I'm first call to user defined function!
Again second call to the same function
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you change what a
parameter refers to within a function, the change also reflects back in the calling function. For example:
def changeme( mylist ): "This changes a passed list“
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

• So this would produce following result:


Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference but inside the function, but the reference is
being over-written.
def changeme( mylist ): "This changes a passed list"
mylist = [1,2,3,4];
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

• 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.

Python Programming, 1/e 67


Recursive Definitions
• Our definition is recursive, but definitely not circular. Consider 4!
• 4! = 4(4-1)! = 4(3!)
• What is 3!? We apply the definition again
4! = 4(3!) = 4[3(3-1)!] = 4(3)(2!)
• And so on…
4! = 4(3!) = 4(3)(2!) = 4(3)(2)(1!) = 4(3)(2)(1)(0!) = 4(3)(2)(1)(1) = 24

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

• All good recursive definitions have these two key characteristics:


• There are one or more base cases for which no recursion is applied.
• All chains of recursion eventually end up at one of the base cases.
• The simplest way for these two conditions to occur is for each
recursion to act on a smaller version of the original problem. A very
small version of the original problem that can be solved without
recursion becomes the base case.

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

You might also like