Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Python Module1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python Module1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

PROGRAMMING IN PYTHON

Text books
1. Paul Gries , Jennifer Campbell, Jason Montojo, Practical
Programming: An Introduction to Computer Science Using Python 3,
Pragmatic Bookshelf, 2/E 2014
2. James Payne, Beginning Python: Using Python 2.6 and Python 3,
Wiley India, 2010
MODULE 1
 INTRODUCTION: Python Overview- History of python,
Features, basic syntax, Writing and executing simple
program, Basic Data Types such as numbers, etc Declaring
variables, Performing assignments, arithmetic operations,
Simple input-output, Precedence of operators, Type
conversion, Control statements: Terminating loops,
skipping specific conditions.
INTRODUCTION
 Python Overview- History of python
• Python is a general-purpose interpreted, interactive, object-
oriented and high-level programming language.
• It was created by Guido van Rossum in (1985- 1990) the late
eighties and early nineties at the National Research Institute for
Mathematics and Computer Science in the Netherlands. Python
was named after Monty Python.
• Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and
other scripting languages.
• Python is copyrighted. Like Perl, Python source code is now
available under the GNU General Public License (GPL).
 Getting Python
 The most up-to-date and current source code, binaries,
documentation, news, etc., is available on the official website of
Python https://www.python.org/
 You can download Python documentation
from https://www.python.org/doc/. The documentation is
available in HTML, PDF, and PostScript formats.
 Python Releases for Windows
 Latest Python 3 Release - Python 3.6.4
 Latest Python 2 Release - Python 2.7.14
PYTHON'S FEATURES INCLUDE :

• Easy-to-learn − Python has few keywords, simple structure, and a


clearly defined syntax. This allows us to pick up the language
quickly.
• Easy-to-read − Python code is more clearly defined and visible to
the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-
maintain.
• A broad standard library − Python's bulk of the library is very
portable and cross-platform compatible on UNIX, Windows, and
Macintosh.
• Interactive Mode − Python has support for an interactive mode
which allows interactive testing and debugging of snippets of code.
FEATURES CONTINUED..
• Portable − Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
• Extendable − we 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.
FEATURES CONTINUED..
 It supports 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.
 It provides very high-level dynamic data types and supports
dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA,
and Java.
PYTHON - BASIC SYNTAX
1. Interactive Mode Programming
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC
v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print('Hello Python')

OUTPUT
Hello Python

Note: If you are running old version of Python, then you need not
use print statement with parenthesis as in print "Hello, Python!“
would work
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.

Python files have extension .py.

Type the following source code in a test.py file −


print "Hello, Python!”

To run this program as follows −


$ python test.py

OUTPUT
Hello, Python!
IDLE
 IDLE (short for integrated development environment or integrated
development and learning environment) is an integrated development
environment for Python.
 A simple program to add two numbers
 Open a newfile in IDLE
write the following code

a=10
b=5
c=a+b
print (c)

save the file


Run (Run Module F5)

OUTPUT
15
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.
• It is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in
Python.
NAMING CONVENTIONS FOR PYTHON
IDENTIFIERS
1. Class names start with an uppercase letter. All other identifiers
start with a lowercase letter.
2. Starting an identifier with a single leading underscore indicates
that the identifier is private.
3. Starting an identifier with two leading underscores indicates a
strongly private identifier.
4. If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
RESERVE WORDS
 The following list shows the Python keywords. These are reserved
words and you cannot use them as constant or variable or any other
identifier names.
ASSIGNING VALUES TO VARIABLES

 Python variables do not need explicit declaration 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.
 The operand to the left of the = operator is the name of the variable
and the operand to the right of the = operator is the value stored in
the variable.

Counter = 100 # an integer


Si = 1000.0 # A floating point
MULTIPLE ASSIGNMENT
 Python allows us to assign a single value to several variables
simultaneously.
 For example −
>>>a = b = c = 1
 Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location.
 we can also assign multiple objects to multiple variables.
 For example −
>>>a, b, c = 1, 2, “john”
LINES AND INDENTATION
• Python doesn't use 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.
For example −
if True:
print ("True")
else:
print ("False")

The following block generates an error −


if True:
print ("Answer")
print ("True")
else:
print "(Answer")
print ("False")
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 are used to span the string across multiple lines.
For example, all the following are legal −
1. word = ‘word’
2. sentence = “This is a sentence.”
3. paragraph = """This is a paragraph. It is made up of multiple lines
and sentences."""
COMMENTS IN PYTHON

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

For example -
# My First comment
print ("Hello, Python!")
# second comment

This produces the following result −


Hello, Python!
COMMENTS IN PYTHON CONTD..
 We can type a comment on the same line after a statement or
expression

For Example—
name = “Vriddhi” # This is again comment

Python doesn't have multiple-line commenting feature. One should


comment each line individually as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
MULTIPLE STATEMENTS ON A SINGLE
LINE
• The semicolon ( ; ) allows multiple statements on the single line
given that neither statement starts a new code block.
• Here is a sample snip using the semicolon −
a1=3;b1=4;c=a1+b1;print(c)
MULTIPLE STATEMENT GROUPS AS
SUITES
1. A group of individual statements, which make a
single code block are called suites in Python.
2. Compound or complex statements, such as if, while,
def, and class require a header line and a suite.
3. 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.
For example −
if expression :
suite
elif expression :
suite
else : suite
DATA TYPES IN PYTHON
 Python has five standard data types −
1. Numbers
2. Strings
3. Lists
4. Tuples
5. Dictionary
PYTHON NUMBERS

 Number data types store numeric values, number objects are


created when assigned a value to them.
 Python supports four different numerical types −
1. int (signed integers)
2. long (long integers, they can also be represented in octal and
hexadecimal)*
3. float (floating point real values)
4. complex (complex numbers)
Note: All integers in python3 are represented as long integers. Hence
there is no separate number type as long.
Examples:
PYTHON ARITHMETIC OPERATORS

Assume variable “a” holds 10 and variable “b” holds 20 then


PYTHON COMPARISON OPERATORS/
RELATIONAL OPERATORS.
These operators compare the values on either sides of them and decide
the relation among them. Assume variable “a” holds 10 and variable “b”
holds 20 then
PYTHON ASSIGNMENT OPERATORS
Assume variable “a” holds 10 and variable “b” holds 20 then
SIMPLE INPUT/OUTPUT
 Python has two functions designed for accepting data
directly from the user:
• input()
• raw_input() [Note *older version accepts this]
1. raw_input()
raw_input() asks the user for a string of data (ended with a
newline), and simply returns the string. It can also take an
argument, which is displayed as a prompt before the user
enters the data. E.g.
>>> x=raw_input("enter value for x")
enter value for x 3
>>> x
' 3‘
>>> type(x)\
<type 'str'>
2. input()
input() uses raw_input to read a string of data, and
then attempts to evaluate it as if it were a Python
program, and then returns the value that results.

>>> x=input("enter value for x")


enter value for x 3
>>> x
3
>>> type(x)
<type 'int'>
 Output
The basic way to do output is the print statement.
>>>print ('Hello, world’)
Hello, world

To print multiple things on the same line separated by


spaces, use commas between them, like this:

print ('Hello,', 'World‘)


This will print out the following:
Hello, World
EXAMPLE

>>> for i in range(1,10):


print (i)
1
2
3
4
5
6
7
8
9
>>>print ("Hello“)
>>>print ("Hello", "world“)
Separates the two words with a space.

>>>print ("Hello", 34)


Prints elements of various data types, separating
them by a space.

>>>print ("Hello " + 34)


Throws an error as a result of trying to concatenate
a string and an integer.

>>>print ("Hello " + str(34))


Uses "+" to concatenate strings, after converting a
number to a string.
>>>sum=2+2; print ("The sum: %i"% sum)
Prints a string that has been formatted with the use of
an integer passed as an argument.

>>> formatted_string = "The sum: %i"% (2+2); print


(formatted_string)
Like the previous, just that the formatting happens
outside of the print statement.

>>>print ("Float: %0.3f"% 1.23456)


Outputs "Float: 1.235".
The number 3 after the period specifies the number of
decimal digits after the period to be displayed.

>>> print ("%s is %i years old"% ("John", 23))


Passes two arguments to the formatter.
PYTHON OPERATORS PRECEDENCE
TYPE CONVERSIONS

The value that is assigned to a given variable does not have


to be specified in the program. The value can come from the
user by use of the input function

name = input('What is your first name?')


What is your first name? John

 In this case, the variable name is assigned the string 'John'.


 If the user hit return without entering any value, name would
be assigned to the empty string ('').
 All input is returned by the input function as a string type.
For the input of numeric values,
the response must be converted to the appropriate type. Python
provides built-in type conversion functions int () and
float () for this purpose.
EXAMPLE
>>>line = input('How many credits do you have?')
>>>num_credits = int(line)
>>>line = input('What is your grade point average?')
>>>gpa = float(line)
or
>>>num_credits=int(input('How many credits do you
have?'))
>>>gpa=float(input('What is your grade point
average?'))

• All input is returned by the input function as a string


type.
• Built-in functions int() and float() can be used to
convert a string to a numeric type.
COERCION VS. TYPE CONVERSION

• Coercion is the implicit (automatic) conversion of operands to a


common type.
• Coercion is automatically performed on mixed-type expressions only
if the operands can be safely converted, that is, if no loss of
information will result.
The conversion of integer 2 to floating-point 2.0 below is a safe
conversion—
2 + 4.5 ➝ 2.0 + 4.5 ➝ 6.5 safe (automatic conversion of int to float)

• Type conversion is the explicit conversion of operands to a specific


type.
• Type conversion can be applied even if loss of information results.
Python provides built-in type conversion functions int() and float(),
with the int() function truncating results.

 float(2) + 4.5 ➝ 2.0 + 4.5 ➝ 6.5


 2 + int(4.5) ➝ 2 + 4 ➝ 6
 Conditional Statements:
if
if-else
nested if–else
 Looping:
for
while
nested loops
SYNTAX OF IF AND IF-ELSE
CONDITIONAL STATEMENTS.
o An if statement consists of a boolean expression followed
by one or more statements.
Syntax for if statement
if expression: statement(s)

o An if statement can be followed by an optional else


statement, which executes when the boolean expression is
FALSE.
Syntax for if –else statement
if expression:
statement(s)
else:
statement(s)
SYNTAX OF NESTED IF–ELSE STATEMENT
CONDITIONAL STATEMENTS
 You can use one if or else if statement inside
another if or else if statement(s).

The syntax of the nested if...elif...else construct may be:


Syntax
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
SYNTAX FOR WHILE LOOP.
 While loop Repeats a statement or group of
statements while a given condition is TRUE. It
tests the condition before executing the loop body.

The syntax of a while loop in Python


programming language is −
Syntax
while expression:
statement(s)
SYNTAX FOR, FOR LOOP.
 For loop Executes a sequence of statements
multiple times and abbreviates the code that
manages the loop variable.
It has the ability to iterate over the items of any
sequence, such as a list or a string.

Syntax
for iterating_var in sequence:
statements(s)
SYNTAX FOR NESTED FOR AND
NESTED WHILE LOOP
 You can use one or more loop inside any another while, for
or do..while loop.

Syntax for nested for loop


for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
 Syntax for a nested while loop statement in Python
programming language is as follows −
while expression:
while expression:
statement(s)
statement(s)
EXAMPLES
 If statements
a = 33
b = 200
if b > a:
print("b is greater than a")
 Indentation
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
 Elif
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
 Else
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
 else without the elif
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
 Short Hand If
if a > b: print("a is greater than b")
 Short Hand If ... Else
a=2
b = 330
print("A") if a > b else print("B")
 Multiple else statements on the same line
a = 330
b = 330
print("A") if a > b else print("=") if a ==
b else print("B")
 And
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
 Or
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
 Nested If

x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
PYTHON CONTROL STATEMENTS
 Controlling Loops
• As a rule, for and while loops execute all the
statements in their body on each iteration.
• However, sometimes it is handy to be able to
break that rule.
• Python supports the following control
statements:
1. Break :-- which terminates execution of the loop
immediately
2. Continue :-- which skips ahead to the next iteration.
3. Pass :-- The pass statement in Python is used when a
statement is required syntactically but you do not
want any command or code to execute.
PYTHON BREAK STATEMENT
• It terminates the current loop and resumes execution at the next
statement, just like the traditional break statement in C.
• The break statement can be used in both while and for loops.
 Syntax
The syntax for a break statement in Python is as follows −
break
 Flow Diagram
USAGE OF BREAK IN FOR STRUCTURE
 for letter in 'Python':
if letter == 'h':
break
print 'Current Letter :', letter

OUTPUT
Current Letter : P
Current Letter : y
Current Letter : t
USAGE OF BREAK IN WHILE STATEMENT:

 var = 10
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
print "Good bye!

OUTPUT
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
PYTHON 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.
• The continue statement can be used in both while and for loops.
 Syntax
The syntax for a continue statement in Python is as follows −
continue
 Flowdiagram
USAGE OF CONTINUE IN FOR
STRUCTURE

 for letter in 'Python':


if letter == 'h':
continue
print 'Current Letter :', letter

OUTPUT
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
USAGE OF CONTINUE IN WHILE
STRUCTURE

 var = 10
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!“
OUTPUT
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
PYTHON PASS STATEMENT
• It is used when a statement is required syntactically but
you do not want any command or code to execute.
• The pass statement is a null operation; nothing happens
when it executes.
• The pass is also useful in places where your code will
eventually go, but has not been written yet.
 Syntax
The syntax for a pass statement in Python is as follows −
pass
USAGE OF PASS IN FOR STRUCTURE

for letter in 'Python':


if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!“

OUTPUT
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

You might also like