Intro To Python Till Strings

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

Introduction To Python

 Credits: 2
 Internal Marks:20
 Moodle
 Assignment
 Practical Exam
 External Marks:30

1
Course Outline
1. Introduction to Python
Features of Python
Python interpreter - interactive and non-interactive mode
2. Python Scripting
Data types
Operators
Control Structures
3. Functions and modules
Standard modules and library functions
User defined functions
4. Structured Data Types
Sequences
Lists
Dictionary
Books Recommended:
1. Dive into python Mark Pilgrim Apress
2. Introduction to Python Dave Kuhlman
2
Python Overview
 Python is a high-level, interpreted, interactive and object-
oriented scripting language. Python was designed to be highly
readable which uses English keywords frequently where as other
languages use punctuation and it has fewer syntactical
constructions than other languages.
• Python is Interpreted: This means that it is processed at
runtime by the interpreter and you do not need to compile your
program before executing it. This is similar to PERL and PHP.
• Python is Interactive :This means that you can actually sit at a
Python prompt and interact with the interpreter directly to write
your programs.
• Python is Object-Oriented: This means that Python supports
Object-Oriented style or technique of programming that
encapsulates code within objects.
• Python is Beginner's Language: Python is a great language for
the beginner programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers
to games.
3
Python At First Glance
a
import math Import a library module

def showArea(shape): Function definition


print("Area = ", shape.area() )

def widthOfSquare(area):
return math.sqrt(area)

class Rectangle(object):

def __init__(self, width, height):


self.width = width Class definition
self.height = height

def area(self):
return self.width * self.height
Comment
###### Main Program ######Python At First Glance
r = Rectangle(10, 20) Object instantiation
showArea(r) Calling a function
4
What Is Python?
 Created in 1990 by Guido van Rossum
 While at CWI, Amsterdam

 Now hosted by centre for national research

initiatives, Reston, VA, USA


 Free, open source
 And with an amazing community

 Object oriented language


 “Everything is an object”

 Runs on Win, Linux/Unix, Mac, OS/2 etc


 Versions: 2.x and 3.x

5
What can Python do?
 Scripting
 Rapid Prototyping

 Text Processing

 Web applications

 GUI programs

 Game Development

 Database Applications

 System Administrations

 And many more.

6
Who is using it?
 Google (various projects)
 NASA (several projects)

 NYSE (one of only three languages "on the floor")

 Industrial Light & Magic (everything)

 Yahoo! (Yahoo mail & groups)

 RealNetworks (function and load testing)

 RedHat (Linux installation tools)

 LLNL, Fermilab (steering scientific applications)

 Zope Corporation (content management)

 ObjectDomain (embedded Jython in UML tool)

 Alice project at CMU (accessible 3D graphics)

7
Programming basics
 code or source code: The sequence of instructions in a program.

 syntax: The set of legal structures and commands that can be


used in a particular programming language.

 output: The messages printed to the user by a program.

 console: The text box onto which output is printed.


 Some source code editors pop up the console as an external window,
and others contain their own console window.

8
Compiling
 Definition: A compiler is a computer program that transforms
(translates) source code of a programming language (the source
language) into another computer language (the target language).
In most cases compilers are used to transform source code into
executable program, i.e. they translate code from high-level
programming languages into low (or lower) level languages, mostly
assembly ore machine code.
 Many languages require you to compile (translate) your program
into a form that the machine understands.

compile execute
source code byte code output
Hello.java Hello.class

9
Interpreting
 Definition: An interpreter is a computer program that executes
instructions written in a programming language. It can either
 execute the source code directly or

 translates the source code in a first step into a more efficient

representation and executes this code

 Python is instead directly interpreted into machine instructions.

interpret
source code output
Hello.py

10
Python Language properties
 Everything is an object
 Packages, modules, classes, functions

 Exception handling

 Dynamic typing, polymorphism

 Static scoping

 Operator overloading

 Indentation for block structure

 Otherwise conventional syntax

11
Python Features
 Easy-to-learn: Python has relatively few keywords, simple
structure, and a clearly defined syntax. This
allows the student to pick up the language in a relatively
short period of time.
 Easy-to-read: Python code is much more clearly defined
and visible to the eyes.
 Easy-to-maintain: Python's success is that its source code

is fairly easy-to-maintain.
 A broad standard library: One of Python's greatest

strengths is the bulk of the library is very portable and


cross-platform compatible on UNIX, Windows and
Macintosh.
 Interactive Mode: Support for an interactive mode in which
you can enter results from a terminal right to the
language, allowing interactive testing and debugging of
snippets of code. 12
Python Features (continued..)
 Portable: Python can run on a wide variety of hardware
platforms and has the same interface on all platforms.
 Extendable: You can add low-level modules to the

Python interpreter. These modules enable programmers


to add to or customize their tools to be more efficient.
 Databases: Python provides interfaces to all major

commercial databases.
 GUI Programming: Python supports GUI applications

that can be created and ported to many system calls,


libraries and windows systems, such as Windows MFC,
Macintosh and the X Window system of Unix.
 Scalable: Python provides a better structure and

support for large programs than shell scripting.

13
Python Features (continued..)
 Support for functional and structured programming
methods as well as OOP.
 It can be used as a scripting language or can be

compiled to byte-code for building large applications.


 Very high-level dynamic data types and supports

dynamic type checking.


 Supports automatic garbage collection.

 It can be easily integrated with C, C++, COM, ActiveX,


CORBA and Java.

14
Installation
 Installation on Windows
 Visit https://www.python.org/downloads/ and download

the latest version. The installation is just like any other


Windows-based software.
 DOS Prompt

 If you want to be able to use Python from the Windows


command line i.e. the DOS prompt, then you need to set
the PATH variable appropriately.
 For Windows 2000, XP, 2003 , click on Control Panel →

System → Advanced → Environment Variables. Click on


the variable named PATH in the System Variables section,
then select Edit and add ;C:\Python27 (please verify that
this folder exists, it will be different for newer versions of
Python) to the end of what is already there. Of course, use
the appropriate directory name.
15
Installation(continued..)
 For Windows 7 and 8:
 Right click on Computer from desktop and select
Properties or click Start and choose Control Panel →
System and Security → System. Click on Advanced system
settings on the left and then click on the Advanced tab. At
the bottom click on Environment Variables and under
System variables, look for the PATH variable, select and
then press Edit.
 Go to the end of the line under Variable value and append

;C:\Python27 (please verify that this folder exists, it will


be different for newer versions of Python) to the end of
what is already there. Of course, use the appropriate
folder name.
 If the value was %SystemRoot%\system32; It will now

become %SystemRoot%\system32;C:\Python27
 Click OK 16
Installation(continued..)
 Installation on GNU/Linux
 For GNU/Linux users, Python is mostly pre-installed.

17
Running Python
There are three different ways to start Python:
1) Interactive Interpreter:
You can enter python and start coding right away in the
interactive interpreter by starting it from the command
line.

18
Running Python
2) Script from the Command-line:
A Python script can be executed at command line by
invoking the interpreter on your application, as in the
following:

Note: Be sure the file permission mode allows execution.

19
Running Python
3) Integrated Development Environment (IDLE)
You can run Python from a graphical user interface (GUI)
environment as well. All you need is a GUI application
on your system that supports Python.
• Unix: IDLE is the very first Unix IDE for Python.
• Windows: PythonWin is the first Windows interface for
Python and is an IDE with a GUI.
• Macintosh: The Macintosh version of Python along with
the IDLE IDE is available from the main website,
downloadable as either MacBinary or BinHex'd files.

20
INTERACTIVE MODE PROGRAMMING
1) INTERACTIVE MODE PROGRAMMING:
Invoking the interpreter without passing a script file as a parameter
brings up the following prompt:

 Type the text on the Python prompt and press the Enter key:

 This will produce following result:

21
SCRIPT MODE PROGRAMMING
2) SCRIPT MODE PROGRAMMING:
Invoking the interpreter with a script parameter begins execution of
the script and continues until the script is finished. When the script is
finished, the interpreter is no longer active.
All python files will have extension .py. So put the following source
code in a test.py file.

Assuming Python interpreter set in PATH variable. Run the program


as follows:

This will produce the following result:

22
Python Identifiers
 A Python identifier is a name used to identify a variable, function,
class, module or other object. An identifier starts with a letter A to
Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
 Python does not allow punctuation characters such as @, $ and %
within identifiers. Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in
Python.
 Here are following identifier naming convention for Python:

• Class names start with an uppercase letter and all other identifiers
with a lowercase letter.
• Starting an identifier with a single leading underscore indicates by
convention that the identifier is meant to be private.
• Starting an identifier with two leading underscores indicates a
strongly private identifier.
•If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
23
Reserved Words
 The following list shows the reserved words in Python. These
reserved words may not be used as constant or variable or any
other identifier names. All the Python keywords contain lowercase
letters only.

24
Lines and Indentation
 In Python there are no braces to indicate blocks of code for
class and function definitions or flow control. Blocks of code
are denoted by line indentation, which is rigidly enforced.
 The number of spaces in the indentation is variable, but all
statements within the block must be indented the same
amount
 Example:
 Valid Block

 Invalid Block

 In Python all the continuous lines indented with similar number of


spaces would form a block.
25
Multi-Line Statements
 Statements in Python typically end with a new line. Python does,
however, allow the use of the line continuation character (\) to
denote that the line should continue.
 Example:

 Note: Statements contained within the [], {} or () brackets do


not need to use the line continuation character.
 Example:

26
Quotation in Python
 Python accepts single ('), double (") and triple (''' or """') quotes to
denote string literals, as long as the same type of quote starts and
ends the string.
 The triple quotes can be used to span the string across multiple
lines.
 Example:

27
Comments in Python
 A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the physical line end are part of
the comment and the Python interpreter ignores them.
 Example:

 OUTPUT:

 A comment may be on the same line after a statement or


expression.

 You can comment multiple lines as follows

28
Multiple Statements on a Single Line
 The semicolon ( ; ) allows multiple statements on the single line
given that neither statement starts a new code block.
 Example:

 “\n" is being used to create new line.

29
Multiple Statement Groups as Suites
 A group of individual statements, which make a single code
block are called suites in Python. Compound or complex
statements, such as if, while, def, and class, are those which
require a header line and a suite.
 Header lines begin the statement (with the keyword) and terminate
with a colon ( : ) and are followed by one or more lines, which
make up the suite.
 Example:

30
Variables
 Variables are nothing but reserved memory locations to store
values. A variable is a name that refers to a value.
 Based on the data type of a variable, the interpreter allocates
memory and decides what can be stored in the reserved memory.

 Assigning Values to Variables

 Python variables do not have to be explicitly declared to reserve


memory space. The declaration happens automatically when you
assign a value to a variable.
 The equal sign (=) is used to assign values to variables.

31
Variables
Variable is a reference to an object
 not a value
 more than one variable can refer to the same object

Var1

Var1_copy

Var2
Multiple Assignment of Variable
 Python allows you to assign a single value to several variables
simultaneously.
 Example:

Explanation: An integer object is created with the value 1, and all


three variables are assigned to the same memory location.

Assign multiple objects to multiple variables

Explanation: Two integer objects with values 1 and 2 are assigned to


variables a and b, and one string object with the value "john" is
assigned to the variable c.

33
Standard Data Types
 The data stored in memory can be of many types. Python has
various standard types that are used to define the operations
possible on them and the storage method for each of them.

 Python has five standard data types:

• Numbers

• String

• List

• Tuple

• Dictionary

34
Python Numbers
 Number data types store numeric values.
 Number objects are created when you assign a value to them.
Example:

 You can delete a single object or multiple objects by using the del
statement.

Example:

35
Python Numeric Types
Python supports four different numerical types:

Integers
 Generally signed, 32-bit
Long Integers
 Unlimited size
 Format: <number>L
 Example: 4294967296L
Float
 Platform dependent “double” precision
Complex
 Format: <real>+<imag>j
 Example: 6+3j
Python Strings
 Strings in Python are identified as a contiguous set of
characters between quotation marks.
3 ways to quote strings:
1. 'Single Quotes'
2. "Double Quotes"
3. """Triple Quotes""" or '''triple quotes''‘

 Triple quotes can span multiple lines

Examples:
>>> print('This string may contain a "')
This string may contain a "
>>> print("A ' is allowed")
A ' is allowed
>>> print("""Either " or ' are OK""")
Either " or ' are OK

37
Python Strings
 Subsets of strings can be taken using the slice operator
( [ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.
 The plus ( + ) sign is the string concatenation operator and the

asterisk ( * ) is the repetition operator.


Example:

 OUTPUT:

38
Python Lists
 Lists are the Python's compound data types.

 A list contains items separated by commas and enclosed within


square brackets ([]).

 To some extent, lists are similar to arrays in C.

 One difference between them is that all the items belonging to a list
can be of different data type.

 The values stored in a list can be accessed using the slice operator
( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the list
and working their way to end -1.

 The plus ( + ) sign is the list concatenation operator.

 The asterisk ( * ) is the repetition operator.


39
Python Lists
 Example:

 OUTPUT :

40
Python Tuples
 A tuple is another sequence data type that is similar to the list.

 A tuple consists of a number of values separated by commas.

 Unlike lists, however, tuples are enclosed within parentheses.

 The main differences between lists and tuples are

 Lists are enclosed in brackets ( [ ] ) and their elements and


size can be changed,

 Tuples are enclosed in parentheses ( ( ) ) and cannot be


updated.

 Tuples can be thought of as read-only lists.

41
Python Tuples
 Example:

 Output:

42
Python Tuples
 Following is invalid with tuple, because we attempted to update a
tuple, which is not allowed. Similar case is possible with lists.

43
Python Dictionary
 Python's dictionaries are kind of hash table type.

 They work like associative arrays or hashes found in Perl and


consist of key-value pairs.

 A dictionary key can be almost any Python type, but are usually
numbers or strings. Values, on the other hand, can be any arbitrary
Python object.

 Dictionaries are enclosed by curly braces ( { } ) and values can be


assigned and accessed using square braces ( [] ).

 Dictionaries have no concept of order among elements. They are


simply unordered.

44
Python Dictionary
 Example:

 OUTPUT:

45
Data Type Conversion
 To perform conversions between the built-in types use the type
name as a function.
 Several built-in functions to perform conversion from one data type
to another are available.
Function Description

int(x [,base]) Converts x to an integer. base specifies the base if x is a string.

long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.

float(x) Converts x to a floating-point number.

complex(real [,imag]) Creates a complex number.

str(x) Converts object x to a string representation.

repr(x) Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.

tuple(s) Converts s to a tuple.

list(s) Converts s to a list.

set(s) Converts s to a set.

dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.

frozenset(s) Converts s to a frozen set.

chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

ord(x) Converts a single character to its integer value.

hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.


46
Python Operators
 What is an Operator?
Operators are the symbols which tells the Python interpreter to do some
mathematical or logical operation. The values the operator uses are called
operands.
Python language supports the following types of operators.
• Arithmetic Operators
+,-,*,/,%,**,//
• Comparison (i.e., Relational) Operators
==,!== or <>,>,<.>=,<=
• Assignment Operators
=,+=,-=,*=,/=,%=,**=,//=
• Logical Operators
and, or, not
• Bitwise Operators
& , |, ^,~,<<,>>
• Membership Operators
In , not in
• Identity Operators
Is, is not 47
Arithmetic Operators
 Assume variable a holds 10 and variable b holds 20, then
Operators Description Example

+ Addition - Adds values on either side of the a + b will give 30


operator
- Subtraction - Subtracts right hand operand a - b will give -10
from left hand operand
* Multiplication - Multiplies values on either a * b will give 200
side of the operator
/ Division - Divides left hand operand by right b / a will give 2
hand operand
% Modulus - Divides left hand operand by right b % a will give 0
hand operand and returns remainder

** Exponent - Performs exponential (power) a**b will give 10 to the


calculation on operators power 20
// Floor Division - The division of operands 9//2 is equal to 4 and
where the result is the quotient in which the 9.0//2.0 is equal to
digits after the decimal point is removed. 4.0

48
Arithmetic Operators

OUTPUT :

49
Comparison Operators
 Assume variable a holds 10 and variable b holds 20, then

50
Comparison Operators
 Example : OUTPUT :
a = 21
b = 10 Line 1 - a is not equal to b
c=0 Line 2 - a is not equal to b
Line 3 - a is not less than b
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a < b ):
print "Line 3 - a is less than b"
else:
print "Line 3 - a is not less than b"

51
Assignment Operators
 Assume variable a holds 10 and variable b holds 20, then

52
Assignment Operators
 a = 21 OUTPUT :
b = 10
c=0 Line 1 - Value of c is 31
c=a+b Line 2 - Value of c is 52
print "Line 1 - Value of c is ", c Line 3 - Value of c is 1092
c += a Line 4 - Value of c is 52
print "Line 2 - Value of c is ", c Line 5 - Value of c is 2
c *= a Line 6 - Value of c is 2097152
print "Line 3 - Value of c is ", c Line 7 - Value of c is 99864
c /= a
print "Line 4 - Value of c is ", c
c=2
c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
print "Line 7 - Value of c is ", c
53
Logical Operators
 Assume variable a holds 10 and variable b holds 20, then

54
Logical Operators
 Example: OUTPUT :
a = 10 Line 1 - a and b are true
b = 20 Line 2 - Either a is true or b is true or both
are true
c=0 Line 3 - Either a is not true or b is not true
if ( a and b ):
print "Line 1 - a and b are true"
else:
print "Line 1 - Either a is not true or b is not true"
if ( a or b ):
print "Line 2 - Either a is true or b is true or both are true"
else:
print "Line 2 - Neither a is true nor b is true"
a=0
if ( a and b ):
print "Line 3 - a and b are true"
else:
print "Line 3 - Either a is not true or b is not true"
55
Bitwise Operators
 Bitwise operator works on bits and perform bit-by-bit operation.
Assume if a = 60 and b = 13, now in binary format they will be as
follows
a = 00111100 , b = 00001101
Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both (a & b) will give 12 which is 0000 1100
operands.

| Binary OR Operator copies a bit if it exists in either operand. (a | b) will give 61 which is 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not (a ^ b) will give 49 which is 0011 0001
both.

~ Binary Ones Complement Operator is unary and has the effect of (~a ) will give -60 which is 1100 0011
'flipping' bits.

<< Binary Left Shift Operator. The left operands value is moved left by a << 2 will give 240 which is 1111 0000
the number of bits specified by the right operand.

>> Binary Right Shift Operator. The left operands value is moved right by a >> 2 will give 15 which is 0000 1111
the number of bits specified by the right operand.

56
Bitwise Operators
 Example: OUTPUT :
a = 60 # 60 = 00111100
b = 13 # 13 = 00001101 Line 1 - Value of c is 12
c=0 Line 2 - Value of c is 61
Line 3 - Value of c is 49
c = a & b; # 12 = 00001100
Line 4 - Value of c is -61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a | b; # 61 = 00111101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 00110001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 11000011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 11110000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 00001111
print "Line 6 - Value of c is ", c

57
Membership Operators
 Python has membership operators, which test for membership
in a sequence, such as strings, lists or tuples.

58
Membership Operators
 Example: OUTPUT :
a = 10 Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
b = 20 Line 3 - a is available in the given list
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"
if ( b not in list ):
print "Line 2 - b is not available in the given list"
else:
print "Line 2 - b is available in the given list"
a=2
if ( a in list ):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"
59
Identity Operators
 Identity operators compare the memory locations of two objects.

60
Identity Operators
 Example: OUTPUT :
Line 1 - a and b have same identity
a = 20 Line 2 - a and b have same identity
b = 20 Line 3 - a and b do not have same identity
if ( a is b ):
print "Line 1 - a and b have same identity"
else:
print "Line 1 - a and b do not have same identity"
if ( id(a) == id(b) ):
print "Line 2 - a and b have same identity"
else:
print "Line 2 - a and b do not have same identity"
b = 30
if ( a is b ):
print "Line 3 - a and b have same identity"
else:
print "Line 3 - a and b do not have same identity"

61
Operators Precedence
 Operator precedence determines the grouping of terms in an
expression. This affects how an expression is evaluated.
The following table lists all operators from highest precedence to lowest.
Operator Description
Exponentiation (raise to the power)
**
~+- Complement, 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

62
Operators Precedence
 Example: OUTPUT :
a = 20 Value of (a + b) * c / d is 90
b = 10 Value of ((a + b) * c) / d is 90
c = 15 Value of (a + b) * (c / d) is 90
d=5 Value of a + (b * c) / d is 50
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = (a + b) * (c / d); # (30) * (15/5)
print "Value of (a + b) * (c / d) is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e

63
Decision Making
 Decision making structures require that the programmer specify
one or more conditions to be evaluated or tested by the program,
along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements
to be executed if the condition is determined to be false.

 Python programming language assumes any non-zero and non-null


values as true, and if it is either zero or null, then it is assumed as
false value.

64
Decision Making
 The general form of a typical decision making structure found in most of
the programming languages.

 Python programming language assumes any non-zero and non-


null values as true, and if it is either zero or null, then it is
assumed as false value.
65
Decision Making
Python programming language provides following types of decision
making statements.

Statement Description

if statements An if statement consists of a boolean expression followed by one or


more statements.

if...else An if statement can be followed by an optional else statement,


statements which executes when the boolean expression is false.

nested if You can use one if or else if statement inside another if or else if
statements statement(s)

66
If statements
 The if statement contains a logical expression using which data is
compared and a decision is made based on the result of the
comparison.
Example:
 Syntax: a=-5
if(a<0):
if expression: print “negative number”
statement(s) Output:
negative number

 If the boolean expression evaluates to true, then the block of


statement(s) inside the if statement will be executed.
 If boolean expression evaluates to false, then the first set of code
after the end of the if statement(s) will be executed.

67
If statements
 Flow Diagram

68
If statements
 Example:

 Output:

69
if...else statements
 An else statement can be combined with an if statement.
 An else statement contains the block of code that executes if
the conditional expression in the if statement resolves to 0 or a
false value.
 The else statement is an optional statement and there could be at
most only one else statement following if .

 Syntax: Example:
if expression: a=5
If(a<0):
statement(s) print “negative number”
else: else:
statement(s) print “positive number”

Output:
positive number

70
if...else statements
Flow Diagram

71
if...else statements
 Example: OUTPUT :
var1 = 100 1 - Got a true expression value
if var1: 100
print "1 - Got a true expression value" 2 - Got a false expression value
print var1
0
Good bye!
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!"

72
elif Statement
 The elif statement allows you to check multiple expressions for truth
value and execute a block of code as soon as one of the conditions
evaluates to true.
 Like the else, the elif statement is optional.

 However, unlike else, for which there can be at most one statement,

there can be an arbitrary number of elif statements following an if.


Syntax:
Example:
if expression1: a=0
statement(s) if(a<0):
elif expression2: print “negative number”
elif (a>0):
statement(s) print “positive number”
elif expression3: else:
statement(s) print “exact zero”
else: Output:
exact zero
statement(s)
Note: Core Python does not provide switch or case statements as in other
languages.
73
elif Statement
 Example: OUTPUT:
var=100 3 - Got a true expression value
100
if var == 200:
Good bye!
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var2
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var

print "Good bye!"

74
nested if statements
 There may be a situation when you want to check for another condition
after a condition resolves to true. In such a situation, you can use the
nested if construct.
 In a nested if construct, you can have an if...elif...else construct inside
another if...elif...else construct.
 Syntax:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
75
nested if statements
 Example: OUTPUT:
var = 100 Expression value is less than 200
Which is 100
if var < 200: Good bye!
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!"

76
Single Statement Suites
 If the suite of an if clause consists only of a single line, it may go on
the same line as the header statement.
Example of one-line if clause:
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!“

OUTPUT:
Value of expression is 100
Good bye!

77
Exercises on If
1)Write a program that asks the user to enter a length in centimeters. If the user
enters a negative length, the program should tell the user that the entry is
invalid. Otherwise, the program should convert the length to inches and print out
the result. There are 2.54 centimeters in an inch.
2)Ask the user for a temperature. Then ask them what units, Celsius or
Fahrenheit, the temperature is in. Your program should convert the temperature
to the other unit. The conversions are F = 9/5 C + 32 and
C = 5 9(F − 32).
3)Ask the user to enter a temperature in Celsius. The program should print a
message based on the temperature:
• If the temperature is less than -273.15, print that the temperature is invalid
because it is below absolute zero.
• If it is exactly -273.15, print that the temperature is absolute 0.
• If the temperature is between -273.15 and 0, print that the temperature is
below freezing.
• If it is 0, print that the temperature is at the freezing point.
• If it is between 0 and 100, print that the temperature is in the normal range.
• If it is 100, print that the temperature is at the boiling point.
• If it is above 100, print that the temperature is above the boiling point.

 78
Python Loops
 A loop statement allows us to execute a statement or group of
statements multiple times and following is the general form of a
loop statement in most of the programming languages.
 Flow Diagram:

79
Python Loops
 Python programming language provides following types of loops to
handle looping requirements.

Loop Type Description


while loop Repeats a statement or group of statements
while a given condition is true. It tests
the condition before executing the loop body.
for loop Executes a sequence of statements multiple
times and abbreviates the code that
manages the loop variable.
nested loops You can use one or more loop inside any
another while, for loop.

80
while loop
 A while loop statement in Python programming language repeatedly
executes a target statement as long as a given condition is true.

Syntax:
while expression:
statement(s)
statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero
value. The loop iterates while the condition is true.
 When the condition becomes false, program control passes to the
line immediately following the loop.

81
while loop
 Flow Diagram:

82
while loop
 Example: Output:
The count is: 0
count = 0
The count is: 1
while (count < 9):
The count is: 2
print 'The count is:', count
The count is: 3
count = count + 1
The count is: 4
print "Good bye!"
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

83
The Infinite loop
 A loop becomes infinite loop if a condition never becomes false. 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.

 Example:
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
print "Good bye!"

NOTE: Above example will go in an infinite loop and you would


need to use CTRL+C to come out of the program.

84
The else Statement Used with Loops
 Python supports to have an else statement associated with a loop
statement.
• If the else statement is used with a for loop, the else statement is
executed when the loop has exhausted iterating the list.
• If the else statement is used with a while loop, the else statement
is executed when the condition becomes false.

Output:
 Example:
0 is less than 5
count = 0 1 is less than 5
while count < 5: 2 is less than 5
print count, " is less than 5" 3 is less than 5
count = count + 1 4 is less than 5
else: 5 is not less than 5
print count, " is not less than 5"

85
Single Statement Suites
 if while clause consists only of a single statement, it may be placed
on the same line as the while header.

 Example of a one-line while clause:

flag = 3
while (flag==3): print 'Given flag is really true!'
print "Good bye!"

Output:
Given flag is really true!
Good bye!

86
for loop
 The for loop in Python has the ability to iterate over the items of
any sequence, such as a list or a string.

 Syntax: Example:
for iterating_var in sequence: for letter in ‘Hi':
statements(s) print 'Current Letter :', letter
 NOTE:
If a sequence contains an expression list, it is evaluated first. Then,
the first item in the sequence is assigned to the iterating variable
iterating_var. Next, the statements block is executed. Each item in
the list is assigned to iterating_var, and the statement(s) block is
executed until the entire sequence is exhausted.

Output:
Current Letter : H
Current Letter : i
87
for loop
 Flow Diagram:

88
for loop
 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!" Output:
Current Letter : H
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
89
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!“
Note: The len() built-in function,which provides the total number of
elements in the tuple as well as the range() built-in function to give
us the actual sequence to iterate over.

OUTPUT:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
90
The else Statement Used with Loops
 Example:
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number‘
OUTPUT: 10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number
91
nested loops
 Python programming language allows to use one loop inside
another loop.

 Syntax for nested for loop  Syntax for nested while loop
for iterating_var in sequence: while expression:
for iterating_var in while expression:
sequence: statement(s)
statement(s) statement(s)
statement(s)

92
Example of nested for loop
 Example :
for x in range(1,4):
### Inner for loop ###
for y in range(1, 5):
#print '%d * %d = %d' % (x, y, x*y)
print x,”*”,y,”=”, x*y
 OUTPUT: 1*1=1
1*2=2
1*3=3
1*4=4
2*1=2
2*2=4
2*3=6
2*4=8
3*1=3
3*2=6
3*3=9
3*4=12
93
Example of nested while loop
Example: OUTPUT:
i=2 2 is prime
while(i < 25): 3 is prime
j=2 5 is prime
while(j <= (i/j)): 7 is prime
if not(i%j): break 11 is prime
j=j+1 13 is prime
if (j > i/j) : print i, " is prime" 17 is prime
i=i+1 19 is prime
print "Good bye!" 23 is prime

94
Loop Control Statements
 Loop control statements change execution from its normal
sequence. When execution leaves a scope, all automatic objects
that were created in that scope are destroyed.
 Python supports the following control statements

Control statement Description


break statement Terminates the loop statement and transfers
execution to the statement immediately
following the loop.
continue statement Causes the loop to skip the remainder of its
body and immediately retest its condition prior
to reiterating.
pass statement The pass statement in Python is used when a
statement is required syntactically but you do
not want any command or code to execute.

95
break statement
 The break statement in Python terminates the current loop and
resumes execution at the next statement.

Example: Output:
for letter in 'Python': Current Letter : P
if letter == 'h': Current Letter : y
break Current Letter : t
print 'Current Letter :', letter Good bye!

print "Good bye!"

96
break statement
 Flow diagram:

97
continue statement
 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: Output:
var = 10 # Second Example Current variable value : 9
while var > 0: Current variable value : 8
var = var -1 Current variable value : 7
if var == 5: Current variable value : 6
continue Current variable value : 4
print 'Current variable Current variable value : 3
value :', var Current variable value : 2
print “Good bye!” Current variable value : 1
Current variable value : 0
Good bye!

98
continue statement
 Flow diagram:

99
pass statement
 The pass statement is a null operation; nothing happens when it
executes.

Example: Output:
for letter in 'Python': Current Letter : P
if letter == 'h': Current Letter : y
pass Current Letter : t
print 'This is pass block' This is pass block
print 'Current Letter :', letter Current Letter : h
print "Good bye! Current Letter : o
Current Letter : n
Good bye!

100
Mathematical functions
 Python includes following functions that perform mathematical
calculations.
Function Returns ( description )

abs(x) The absolute value of x: the (positive) distance between x and


zero.
ceil(x) The ceiling of x: the smallest integer not less than x

cmp(x, -1 if x < y, 0 if x == y, or 1 if x > y


y)
exp(x) The exponential of x: ex

fabs(x) The absolute value of x.

floor(x) The floor of x: the largest integer not greater than x

log(x) The natural logarithm of x, for x> 0

log10(x) The base-10 logarithm of x for x> 0 .


101
Mathematical functions
 Python includes following functions that perform mathematical
calculations.

Function Returns ( description )

max(x1, The largest of its arguments: the value closest to positive infinity
x2,...)
min(x1, The smallest of its arguments: the value closest to negative infinity
x2,...)
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts
have the same sign as x. The integer part is returned as a float.
pow(x, y) The value of x**y.

round(x x rounded to n digits from the decimal point. Python rounds away
[,n]) from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
sqrt(x) The square root of x for x > 0

102
Random Number Functions
 Random numbers are used for games, simulations, testing, security
and privacy applications. Python includes the following functions
that are commonly used.

103
Trigonometric Functions
 Python includes the following functions that perform trigonometric
calculations.

104
Python Strings
 Strings are amongst the most popular types in Python.
 Creating strings is as simple as assigning a value to a variable.

 Example :

var1 = 'Hello World!'


var2 = "Python Programming“
Accessing Values in Strings
var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0] OUTPUT:
var1[0]: H
print "var2[1:5]: ", var2[1:5] var2[1:5]: ytho
Updating Strings
var1 = 'Hello World!‘
print "Updated String :- ",var1[:6] + 'Python'
OUTPUT:
Updated String :- Hello Python
105
String Special Operators
 Assume string variable a holds 'Hello' and variable b holds 'Python',
then:

106
String Formatting Operator
 The string format operator %.This operator is unique to strings and
makes up for the pack of having functions from C's printf() family.
 Here is the list of complete set of symbols, which can be used along with %:

107
String Formatting Operator

 Example
 print "My name is %s and age is %d Years!" % (‘Sachin', 41)

OUTPUT:
My name is Sachin and age is 41 Years!

108
Built-in String Methods
 Python includes the following built-in methods to manipulate strings.
 Example : List of some Built-in string methods.

Method Description

lower() returns a string with every letter of the original in lowercase

upper() returns a string with every letter of the original in uppercase

replace(x,y) returns a string with every occurrence of x replaced by y

count(x) counts the number of occurrences of x in the string

index(x) returns the location of the first occurrence of x

isalpha() returns True if every character of the string is a letter

109
Formatting Options
 The general syntax for a format placeholder is

%[flags][width][.precision]type

Example :
print "the price is %6.2f" %453.2134567
Output:
the price is 453.21

110
Formatting Options
 Type Conversions Options
Conversion Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Unsigned decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a "%" character in the result. 111
Formatting Options
 Flag Options

Flag Meaning
# Used with o, x or X specifiers the value is preceded with 0, 0o, 0O, 0x or 0X
respectively.
0 The conversion result will be zero padded for numeric values.
- The converted value is left adjusted

If no sign (minus sign e.g.) is going to be written, a blank space is inserted


before the value.
+ A sign character ("+" or "-") will precede the conversion (overrides a "space"
flag).

112
Formatting Options
 Example
uid = "sa"
pwd = "secret"
print pwd + " is not a good password for " + uid
print "%s is not a good password for %s" % (pwd, uid)
userCount=6
print "Users connected: %d" % (userCount)
#print "Users connected: " + userCount
print "Today's stock price: %f" % 50.4625
print "Today's stock price: %.2f" % 50.4625
print "Change since yesterday: %+.2f" % 1.5
print "the price is %6.2f" %453.2134567
print "the price is %6.2F" %453.2134567
print "the price is %4d" %453.2134567
print "the price is %6d" %453.2134567

113
Formatting Options
s1 = "cats"
s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)
print s3
s1 = "so much depends upon %s" %("a red wheel barrow")
s2 = "glazed with %s water beside the %s chickens" %("rain", "white")
print s1,s2
a="B"
b="B"
c="Roy"
d="of"
e="Great Britain"
f="had"
g="very"
h="good"
i="wife"
set = " (%s, %s, %s, %s, %s, %s, %s, %s) " % (a,b,c,d,e,f,g,h,i)
print set
114

You might also like