0% found this document useful (0 votes)
36 views

Intro To Python

Python book,this book will learn you the principle of programming and python,including algorithms and web-tech

Uploaded by

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

Intro To Python

Python book,this book will learn you the principle of programming and python,including algorithms and web-tech

Uploaded by

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

INTRODUCTION TO

PYTHON
Program

• A program is a set of instructions that a computer uses to


perform a specific function. Programs are created using specific
programming languages.

• A computer program is a sequence of instructions written using


a Computer Programming Language to perform a specified task
by the computer.
Applications of Computer Programs

• To create software like MS Word, MS Excel, Adobe Photoshop,


Internet Explorer, Chrome, etc.

• To develop graphics and special effects in movie making

• To perform Ultrasounds, X-Rays, and other medical examinations

• To support features in mobile phones such as SMS, Chat, and voice


communication.
Programming Languages
• A programming language is a vocabulary and set of grammatical
rules for instructing a computer or computing device to perform
specific tasks

• The main functions of a programming language are to store and


manipulate data, control hardware, provide security, and be an
understandable medium for humans.

• Programming languages use standardized functions to communicate


with each other, so compatible devices can communicate.
Types of Programming Languages

• Programming languages can be classified –


1. Based on levels of abstraction
Low Level Programming Language
High Level Programming Language
Types of Programming Languages

2. According to purpose
Procedural Programming Language
Functional Programming Language
Scripting Programming Language
Object-oriented Programming Language
Low Level Programming Language

• provides no abstraction from the hardware

• represented in 0 or 1 forms

• e.g., Machine level language, Assembly language


High Level Programming Language

• allows a programmer to write the programs which are


independent of a particular type of computer
• closer to human languages than machine-level languages
• while writing a program, whole attention needs to be paid to the
logic of the problem
• compiler is required to translate a high level language into a
low-level language
Procedural Programming Language

• Uses statements to specify actions, allowing a programmer to


write instructions, called procedures, that a computer can
execute

• These instructions tell a computer what operations to perform


on given data and how these operations should be performed

• e.g., COBOL, BASIC, C


Functional Programming Language

• emphasizes functions that return values, which can be used by


other functions or be assigned as values to variables or data
structures

• treats computation as the evaluation of mathematical functions


and avoids state and mutable data

• LISP, Python
Scripting Programming Language

• supports scripts

• scripts are programs written for a special run-time environment


that automate tasks normally performed by humans

• JavaScript, PHP, Ruby


Object-Oriented Programming Language

• supports object-oriented analysis and design

• become increasingly popular since the mid-1980s

• universally supported in modern programming languages

• e.g., C++, Java


Use of Programming Languages

• Programming Languages are used by –


Software Developer
Systems Analyst
Web Developer
Systems Engineer
Application Developer
History of Python

• Foundation of Python was laid in late 1980s.

• After that, Guido Van Rossum began doing its application-


based work in December of 1989 at CWI in the Netherlands

• The programming language in which Python is said to have


succeeded is ABC Programming Language, that had feature of
exception handling
History of Python

• Python was finally released in 1991.

• When it was released –


It used a lot fewer codes to express the concepts, when
compared with C, C++ and Java
It had more than enough capability to provide classes with
inheritance, several core data types exception handling and
functions
About Python

• Python is an object-oriented, high level language, interpreted,


dynamic and multipurpose programming language

• Python is easy to learn, powerful and versatile scripting


language which makes it attractive for Application Development

• Python's syntax and dynamic typing with its interpreted nature, make
it an ideal language for scripting and rapid application development
in many areas
About Python

• Python supports multiple programming pattern, including object


oriented programming, imperative and functional programming or
procedural styles.

• Python can be used in different domains as web, 3D CAD etc.,


that’s why it is known as multipurpose language

• Python is dynamically typed, so no need to specify datatype while


declaring variable
About Python

• Python makes the development and debugging fast because


there is no compilation step included in python development
and edit-test-debug cycle is very fast
Features of Python
• Easy to Use
High level language
Programmer friendly language

• Expressive Language
Code is easily understandable

• Interpreted Language
Interpreter executes the code line by line at a time
Debugging is easy, suitable for beginners
Features of Python

• Cross-platform Language
Run equally on different platforms such as Windows, Linux, Mac etc.
Portable language

• Open Source
Freely available on www.python.org

• Object-oriented Language
Concept of classes and objects exist
Features of Python

• Large Standard Library


Has large and broad library

• GUI Programming
Graphical user interfaces can be developed using Python

• Integrated Language
Python can be easily integrated with languages like C, C++,
JAVA etc
What can Python do?

• Python can be used


- on a server to create web applications
- alongside software to create workflows
- to connect to database systems
- to read, write and modify files
- to handle big data and perform complex mathematics
- for rapid prototyping, or for production-ready software
development
Python Applications

• Console based Applications


e.g., Ipython

• Audio / Video based Applications


e.g., TimPlayer, cplay

• 3D CAD Applications
e.g., Fandango with full features of CAD
Python Applications

• Web based Applications


e.g., PythonWikiEngines, Pocoo

• Enterprise Applications
e.g., OpenErp, Tryton

• Applications for Images


e.g., Vpython, imgSeek
Python Installation

• Installation on Windows –
Download latest version of Python from www.python.org

• DOS Prompt –
To use Python from the Windows command line, need to
set the PATH variable
Control Panel → System → Advanced →
Environment Variables
Specify value for PATH variable in the System Variables section
Running Python

• There are 3 ways to execute Python program –


1. Using interactive interpreter

2. Script from command line

3. Using Integrated Development Environment (IDLE)


Interactive Interpreter
Identifiers

• Identifiers are the names given to the fundamental building


blocks in a program.

• These can be variables, class, object, functions, lists,


dictionaries etc.
Identifiers

• There are certain rules defined in Python for naming identifiers –


• An identifier is a long sequence of characters and numbers.
• No special character except underscore ( _ ) can be used as an
identifier.
• First character of an identifier can be character, underscore ( _ ) but not
digit
• Keyword should not be used as an identifier name.
• Python is case sensitive. So using case is significant.
Identifiers

• There are some conventions in Python for naming identifiers –


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

• Keywords are special reserved words which convey a special


meaning to the compiler/interpreter.

• Each keyword have a special meaning and a specific


operation.

• These keywords may not be used as constant or variable or any


other identifier names
Keywords
• List of Keywords used in Python are –
Output Statement

• There are two ways to get the output, i.e., to write values –
1. Expression Statements
2. print() function
Variables

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

• Variable is a reference to an object.

• Variable is not a value.

• More than one variable can refer to the same object.


Assigning Values to Variable

• 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 to sign (=) is used to assign values to variables.

• e.g., number = 100


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 –
Multi-line statements

• Statements contained within the [], {} or () brackets do not


need to use the line continuation character.

• Example –
Multiple Statements on Single Line

• The semicolon ( ; ) allows multiple statements on the single line


given that neither statement starts a new code block.

• Example –
x = 10; y = 20; print(x);
Quotations

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

• Example –
Multiple Assignments to Variable

• In python, it is allowed to assign a single value to several


variables simultaneously.

• 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
Multiple objects to Multiple variables

• In python, it is allowed to assign multiple objects to multiple


variables on single line.

• Example –
a, b, c = 1, 2, ‘python’
Here, two integer objects with values 1 and 2 are
assigned to variables a and b, and one string object with
the value ‘python’ is assigned to the variable c.
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 ( : ).
Multiple Statement Groups as Suites

• Header lines are followed by one or more lines, which make


up the suite.

• Example –
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 by the same
amount.
Indentation

• Example of Valid block –

• Example of Invalid block -


Indentation

• In Python, all the continuous lines indented with similar number


of spaces would form a block
Comments

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

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


expression.
Multiline Comments

• There are two ways by which multiline comments can be added


in Python.

• They are -
1. Consecutive single-line comment (#)
2. Using a Multi-line string as a comment ( triple quotes)
(Since python will ignore string literals that are not
assigned to a variable)
Standard Data Types

• Python has following standard data types -

• Numeric
• String
• Boolean
• List
• Tuple
• Set
• Dictionary
Getting Data Type

• We can get the datatype of any object using the type() function.

• e.g., x = 100
print(type(x))
- will print datatype of x
Numeric Type

• Numeric data type store numeric values.

• Number objects are created when you assign a value to them.

• e.g., num1 = 100

• Single or multiple objects can be deleted using del statement.

• e.g., del num1, num2


Numeric Types

• Python supports three different numerical types as –

1. Integers
Value is represented by int class
Contain positive or negative whole numbers
There is no limit to how long an integer value can be
e.g., x = 12
Numeric Types
2. Float
Value is represented by the float class
Store a real number with a floating-point representation
e.g., x = 43.58

3. Complex
Value is represented by a complex class
Specified as (real part) + (imaginary part)j
e.g., x = 2 + 3j
Strings

• Strings in Python are identified as a contiguous set of


characters between quotation marks.

• There are 3 ways to quote strings –


1. 'Single Quotes’
2. "Double Quotes"
3. """Triple Quotes""" or '''triple quotes'''
Strings

• In case, single quote is part of string, then either it should be


embedded in double quotes or \ can be used to escape quotes.

• Example –
To print doesn’t, two ways are there –
1. “doesn’t” (using double quotes)
2. ‘doesn\’t’ (using \ )
Strings

• Similarly, when double quote is part of string, then either it


should be embedded in single quotes or \ can be used to
escape quotes.

• Example –
To print “Yes”, he said, two ways are there –
1. ‘ “Yes”, he said ’ (using single quotes)
2. “ \“Yes \”, he said ” (using \ )
Strings

• In case, single quote as well as double quote is part of string,


then either it should be embedded in triple quotes or \ can be
used to escape quotes.

• When \ is used, print() function produces a more readable


output, by omitting the enclosing quotes and by printing
escaped and special characters.
Strings

• Example –
1. ‘ “Isn\’t it,” they said. ’
prints the string as it is with enclosing quotes
‘ “Isn\’t it,” they said. ’
2. print(‘ “Isn\’t it,” they said. ’ )
prints the string without enclosing quotes and
escaped characters
“Isn’t it,” they said.
Strings

• Similarly, print() function produces a more readable output


when used with newline character \n.

• The print() function omits the enclosing quotes and prints


escaped and special characters
Strings

• Example –
1. str = ‘ First Line \n Second Line ’
prints str as it is with enclosing quotes and \n
‘ First Line \n Second Line ’
2. print( str )
prints the string without enclosing quotes and
producing new line
First Line
Second Line
Strings

• In some cases, we want to print the string that has \ character


as it is along with \ character.

• This means, if we don’t want python to interpret characters


prefaced by \ character as special characters, raw strings can
be used by adding r before the first quote.

• e.g., print(r‘C:\user\bin’)
Strings

• Triple quotes can be used –


when the string is too long to span multiple lines
when the string contains single quote as well as
double quote
Strings

• Multiple variables storing string values can be printed together


on a single line using print() function as –
1. x = ‘Python’; y = ‘is’; z = ‘course’
print(x, y, z)
- will print Python is course
2. x = ‘Python ’; y = ‘is ’; z = ‘course’
print(x + y + z)
- will print Python is course
Boolean

• Can have one of the two built-in values, True or False

• Boolean objects that are equal to True and those equal to


False are represented

• It is denoted by the class bool

• e.g., x = True
List

• Lists are Python's compound data types

• A list contains items separated by commas and enclosed within


square brackets ([])

• Lists are somewhat similar to arrays in C

• The difference is that all the items belonging to a list can be of


different data type
List

• Lists are indexed, so lists can have items with the same value.
e.g., list1 = [“Apple”, “Banana”, “Grapes”]
list2 = [“Apple”, “Banana”, “Grapes”, “Banana”, “Apple”]
Here, list1 and list2 are valid lists.

• List is changeable, it means that we can change, add, and


remove items in a list after it has been created
List

• Lists are ordered, it means that the items have a defined order
and that order will not change.

• If you add new items to a list, the new items will be placed at
the end of the list.
Tuple

• A tuple is another sequence data type in Python that is similar


to the list.

• A tuple consists of a number of values separated by commas


and enclosed within parentheses, i.e., ()

• e.g., fruits = (“Apple”, “Banana”, “Grapes”)


Tuple

• Similar to lists, tuples are indexed, so tuples can have items


with the same value, i.e., allow duplicate values

• Tuples are ordered, it means that the items have a defined


order and that order will not change

• Tuples are unchangeable, it means that we can not change,


add or remove items after the tuple has been created
Set

• A set is also sequence data type in Python that is similar


to the tuple.

• A set consists of a number of values separated by commas


and enclosed within curly brackets, i.e., { }

• e.g., fruits = {“Apple”, “Banana”, “Grapes”}


Set

• Unlike tuples, set is unordered, it means that the items in a


set do not have a defined order.

• Set items can appear in a different order every time we use


them, and cannot be referred to by index or key.

• As there is no index, set cannot have two items with the same
value.
Set
• In case two items with same value are added, duplicate values
are ignored.

• e.g., fruits = {“Apple”, “Banana”, “Grapes”, “Banana”}


print(fruits)
- will print {“Apple”, “Banana”, “Grapes”}

• We can add or remove items to and from set, but we cannot


change the items after the set has been created.
Dictionary

• Python's dictionaries work like associative arrays

• Dictionaries are written using curly brackets and consist of


key-value pairs.

• A dictionary key can be any Python type, but are usually


numbers or strings.
Dictionary

• A dictionary value can be any arbitrary Python object.

• e.g., d = {1: ‘Apple’, 2: ‘Banana’, 3: ‘Grapes’}

• Dictionaries are ordered, it means that the items have a


defined order and that order will not change
Dictionary

• Dictionaries are changeable, it means that we can change, add


or remove items after the dictionary has been created.

• Dictionary values can be accessed using square brackets, in


which key is specified. e.g., print(d[1])

• Dictionaries cannot have two items with the same key, i.e., it
does not allow duplicate keys.
Dictionary

• In case two items are added for the same key, newly added
value will be considered and previous key-value pair is ignored

• e.g., fruits = {1: “Apple”, 2: “Banana”, 2: “Grapes”, 3: “Orange”}


print(fruits)
- will print {1: “Apple”, 2: “Grapes”, 3: “Orange”}
Reading User Input

• Python allows for user input, i.e., we can ask the user for input.

• It uses the input() method for accepting user input.

• e.g., name = input(“Enter your name : ”)


Data Type Conversion

• To perform conversions between the built-in types use the


name of the datatype as a function.

• Several built-in functions to perform conversion from one data


type to another are available.
Data Type Conversion

• int(x, [base]) -
This function converts x to integer
‘base’ specifies the base if x is string
e.g., x = ‘10010’
ans = int(x, 2)
print(ans)
This will print 18
Data Type Conversion

• float(x) –
This function converts x to a floating-point number.
e.g., x = ‘10010’
ans = float(x)
print(ans)
This will print 10010.0
Data Type Conversion

• ord(x) -
This function converts a single character to its integer value
e.g., x = ‘4’
ans = ord(x)
print(ans)
This will print 52
Data Type Conversion

• hex(x) –
This function converts an integer to a hexadecimal string
e.g., x = 56
ans = hex(x)
print(ans)
This will print 0x38
Data Type Conversion

• oct(x) –
This function converts an integer to an octal string
e.g., x = 56
ans = oct(x)
print(ans)
This will print 0o70
Data Type Conversion

• tuple(x) –
This function converts x to a tuple
e.g., x = ‘python’
ans = tuple(x)
print(ans)
This will print - (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
Data Type Conversion

• set(x) –
This function converts x to a set
e.g., x = ‘sicsr’
ans = set(x)
print(ans)
This will print – {‘c’, ‘i’, ‘s’, ‘r’}
Data Type Conversion

• list(x) –
This function converts x to a list
e.g., x = ‘sicsr’
ans = list(x)
print(ans)
This will print – [‘s’, ‘i’, ‘c’, ‘s’, ‘r’]
Data Type Conversion

• dict(x) –
This function converts tuple x into a dictionary, provided that
tuple x has sequence of (key, value)
e.g., x = ((‘a’, 1),(‘b’, 2),(‘c’, 3))
ans = dict(x)
print(ans)
This will print – {‘a’: 1, ‘b’: 2, ‘c’: 3}
Data Type Conversion

• str(x) –
This function converts integer x to a string representation
e.g., x = 12
ans = str(x)
print(ans)
This will print – 12
Data Type Conversion

• complex(real, [imag]) –
This function converts real number to complex number
ans = complex(3, 4)
print(ans)
This will print – (3 + 4j)
Data Type Conversion

• chr(x) –
This function converts integer x to its corresponding ASCII
character.
e.g., x = 65
ans = chr(x)
print(ans)
This will print – A
Operators

• Operators are the symbols which tells the Python interpreter to


perform some mathematical or logical operation

• The values used by the operator are called operands.


Operators

• Python supports following types of operators -

• Arithmetic Operators
• Comparison Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Identity Operators
• Membership Operators
Arithmetic Operators

• Addition(+) –
Adds values on either side of the operator

• Subtraction(-) –
Subtracts right hand operand from left hand operand

• Multiplication (*) –
Multiplies values on either side of the operator
Arithmetic Operators

• Division(/) –
Divides left hand operand by right hand operand

• Modulus(%) –
Divides left hand operand by right hand operand and
returns remainder
Arithmetic Operators

• Exponent (**) –
Performs exponential (power) calculation

• Floor Division (//) –


Divides left hand operand by right hand operand and the
result is shown after removing decimal point from the
quotient (if any)
Comparison Operators

• Equal (==) –
Checks if the value of two operands is equal or not
Returns true when the values are equal

• Not Equal (!=) –


Checks if the value of two operands is equal or not
Returns true when the values are not equal
Comparison Operators

• Greater than (>) –


Checks if the value of left operand is greater than the value
of right operand
Returns true if left operand is greater

• Less than (<) –


Checks if the value of left operand is less than the value
of right operand
Returns true if right operand is greater
Comparison Operators

• Greater than or equal to (>=) –


Checks if the value of left operand is greater than or equal to the
value of right operand
Returns true if left operand is greater or equal to right operand

• Less than or equal to (<=) –


Checks if the value of left operand is less than or equal to the
value of right operand
Returns true if left operand is less than or equal to right operand
Assignment Operators

• Simple Assignment operator (=) –


Assigns the value of the right expression or right operand to
the left operand

• Add AND assignment operator (+=) –


Adds right operand to the left operand and assigns the
result to the left operand
Assignment Operators

• Subtract AND assignment operator (-=) –


Subtracts right operand from the left operand and assigns
the result to the left operand

• Multiply AND assignment operator (*=) –


Multiplies right operand with the left operand and assigns
the result to the left operand
Assignment Operators

• Divide AND assignment operator (/=) –


Divides left operand with the right operand and assigns
the result to the left operand

• Modulus AND assignment operator (%=) –


Takes modulus using two operands and assigns the result
to the left operand
Assignment Operators

• Exponent AND assignment operator (**=) –


Performs exponential (power) calculation on left operand
as of right operand and assigns the result to left operand

• Floor Division AND assignment operator (//=) –


Performs floor division on left operand using right operand
and assigns the result to the left operand
Logical Operators
• Logical AND operator (and) –
If both the operands are true, then it results in true

• Logical OR operator (or) –


If any of the two operands is true, then it results in true

• Logical NOT operator (not) –


It reverses logical state of its operand.
If the operand is true, it results in false and vice versa
Bitwise Operators
• Bitwise operator works on bits and perform bit-by-bit operation.

• Bitwise AND operator (&) –


The result bit will be 1 if both bits in two operands at the
same position are 1. If not, result bit is 0.

• Bitwise OR operator (|) –


The result bit will be 0 if both the bits in two operands at the
same position are 0, otherwise, result bit is 1.
Bitwise Operators

•Bitwise XOR operator (^) –


The result bit will be 1 if bits in both the operands at
the same position are different. If not, result bit is 0.

• Negation operator (~) –


It is unary operator
It results in bitwise complement of the operand
Bitwise Operators

•Bitwise Left Shift operator (<<) –


Shift bits towards left by pushing zeros in from the right
and let the leftmost bits fall off

• Bitwise Right Shift operator (>>) –


Shift bits towards right by pushing zeros in from the left
and let the rightmost bits fall off
Identity Operators
• Identity operators compare the memory locations of two objects.

• is –
Returns True if both variables are the same object or
point to the same object

• is not –
Returns True if both variables are not the same object
or point to different objects
Identity Operators
• To check the memory location, id() function is used, that returns
a unique id for the specified object.

• All objects in Python has its own unique id, which is assigned to
the object when it is created.

• The id is the object's memory address, and will be different each


time we run the program. (except for some object that has a
constant unique id, like integers from -5 to 256)
Membership Operators
• Membership operators are used to test for the membership of a
sequence in an object. Sequence can be strings, lists or tuples.

• in –
Returns True if a sequence with the specified value is
present in the object

• not in –
Returns True if a sequence with the specified value is not
present in the object
Operator Precedence

• Operator precedence describes the order in which operations


are performed.

• It determines the grouping of terms in an expression, which in


turn, affects how an expression is evaluated

• If two operators have the same precedence, the expression is


evaluated from left to right.
Operator Precedence
1. ()
2. **
3. +x, -x, ~x
4. *, /, //, %
5. +, -
6. <<, >>
7. & - Bitwise AND
8. ^ - Bitwise XOR
9. | - Bitwise OR
10. ==, !=, >, >=, <, <=, is, is not, in, not in
11. not - Logical NOT
12. and - Logical AND
13. Or - Logical OR

You might also like