0% found this document useful (0 votes)
132 views66 pages

Python Language: Introdction

Python is an interpreted, interactive, object-oriented scripting language that is easy to learn and widely used. It supports features like indentation, dynamic typing, garbage collection, and has a large standard library. Python code is commonly written and executed using an interpreter, though it can also be compiled into bytecode for faster execution.

Uploaded by

supriya mandal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views66 pages

Python Language: Introdction

Python is an interpreted, interactive, object-oriented scripting language that is easy to learn and widely used. It supports features like indentation, dynamic typing, garbage collection, and has a large standard library. Python code is commonly written and executed using an interpreter, though it can also be compiled into bytecode for faster execution.

Uploaded by

supriya mandal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 66

PYTHON LANGUAGE

INTRODCTION
What is Scripting Language?

• A scripting language is a “wrapper” language that integrates OS functions.


• The interpreter is a layer of software logic between your code and the
computer hardware on your machine.
Wiki Says:

• The “program” has an executable form that the computer can use directly to
execute the instructions.

• The same program in its human-readable source code form, from which
executable
programs are derived (e.g., compiled)

• Python is scripting language, fast and dynamic.


Python is called ‘scripting language’ because of it’s scalable interpreter,
What is Python?

Python is a high-level programming language which is:

▪ Interpreted: Python is processed at runtime by the interpreter. (Next


Slide)

▪ Interactive: You can use a Python prompt and interact with the
interpreter
directly to write your programs.

▪ Object-Oriented: Python supports Object-Oriented technique of


programming.

▪ Beginner’s Language: Python is a great language for


the beginner-level
programmers and supports the development of a wide range of
Interpreters Versus
Compilers

• The first thing that is important to understand about Python is that


it is an interpreted language.

• There are two sorts of programming languages: interpreted ones


and compiled ones. A compiled language is what you are
probably used to if you have done any programming in the
past. The

• process for a compiled language is as follows:


• Create source file using text edit□
• Use compiler to syntax check and convert source file into
binary □

• Use linker to turn binary files into executable format□


• Run the resulting executable format file in the operating
system.
• The biggest difference between interpreted code and compiled code
is that
an interpreted application need not be “complete.”

• You can test it in bits and pieces until you are satisfied with the
results and put them all together later for the end user to
use.
Python Features

▪ Easy to learn, easy to read and easy to maintain.


▪ Portable: It canrun on varioushardware and hasthe
platforms same interface on all platforms.

▪ Extendable: You can add low-level modules to the Python interpreter.


▪ Scalable: Python provides a good structure and support for large
programs.

▪ Python has support for an interactive mode of testing and


debugging.
▪ Python has a broad standard library cross-platform.
▪ Everything in Python is an object:variables,functions, even
code. Every object has an ID, a type, and a
More Features
..

▪ Python provides interfaces to all major commercial databases.


▪ Python supports functional and structured programming methods as
well as
OOP.

▪ Python provides very high-level dynamic data types and supports


dynamic
type checking.

▪ Python supports GUI applications


▪ Python supports automatic garbage collection.
▪ Python can be easily integrated with C, C++, and Java.
Why
Python
Easy to read ✔ Python scripts have clear syntax, simple structure and very few
protocols to remember before programming.

Easy to Maintain ✔ Python code is easily to write and debug. Python's success is that its source code is
fairly
easy-to-maintain.
Portable ✔ Python can run on a wide variety of Operating systems and platforms and providing
the
similar interface on all platforms.
Broad Standard Libraries ✔ Python comes with many prebuilt libraries apx. 21K
High Level programming ✔ Python is intended to make complex programming simpler. Python deals with
memory addresses, garbage collection etc internally.

Interactive ✔ Python provide an interactive shell to test the things before implementation. It
provide the user the direct interface with Python.

Database Interfaces ✔ Python provides interfaces to all major commercial databases. These
interfaces are pretty easy to use.

GUI programming ✔ Python supports GUI applications and has framework for Web. Interface to
tkinter, WXPython, DJango in Python make it .
History of Python

▪ Python was conceptualized by Guido Van Rossum in


the late
1980s.

▪ Rossum published the first version of Python code


(0.9.0) in February 1991 at the CWI (Centrum Wiskunde
& Informatica) in the Netherlands , Amsterdam.

▪ Python is derived from ABC programming language,


which is a general-purpose programming language that
had been developed at the CWI.

▪ Rossum chose the name "Python", since he was a big


fan of
Monty Python's Flying Circus.

▪ Python is now maintained by a core development team


at the institute, although Rossum still holds a vital role in
Python Versions

Release dates for the major and minor


versions:
✦ Python 1.0 - January 1994
▪ Python 1.5 - December 31, 1997
▪ Python 1.6 - September 5, 2000
✦ Python 2.0 - October 16, 2000
▪ Python 2.1 - April 17, 2001

▪ Python 2.2 - December 21, 2001


▪ Python 2.3 - July 29, 2003

▪ Python 2.4 - November 30, 2004


▪ Python 2.5 - September 19, 2006
Python time line
Key Changes in Python 3.0

✦ Python 2's print statement has been replaced by the print()


function.
Old New
: :
✦ There is only one integer type left, int.
✦ Some methods such as map() and filter( ) return iterator objects in
Python 3 instead of lists in Python 2.
✦ In Python 3, a TypeError is raised as warning if we try to compare
unorderable types. e.g. 1 < ’ ', 0 > None are no longer valid
✦ Python 3 provides Unicode (utf-8) strings while Python 2 has
ASCII str(
) types
A new and separate
built-in string unicode( ). method
formatting format()
✦ replaces
the % string
formatting operator.
Key Changes in Python 3.0

✦ In Python 3, we should enclose the exception argument in


parentheses.
Old New
: :

✦ In Python 3, we have to use the as keyword now in the handling of


exceptions.

Old New
: :

✦ The division of two integers returns a float instead of an integer. "//"


ccan be used to have the "old" behavior.
Python

Syntax
Basic Syntax

▪ Indentation is used in Python to delimit blocks. The number of


▪ sniblock
pdaecnetsedishte svaamriaebalem,ounb.tut
must be
all statements
within the same
The header line for compound statements, such as if, while, def,
and
□Error!
class should be terminated with a colon ( : )

▪ The semicolon ( ; ) is optional at the end of stat


ement. Printing to the Screen:

▪ Reading Keyboard Input:


▪ Comments
•Single line:
•Multiple lines:
Variables

▪ Python is dynamically typed. You do not


need to declare variables!

▪ The declarationhappens
automatically when you assign
a value to a variable.

▪ Variables can change type, simply by


assigning them a new value of a
different type.

▪ Python allows you to assign a single value


to
several variables simultaneously.

▪ You can also assign multiple objects to


Python Data
Types
Numbers

▪ Numbers are Immutable objects in Python that cannot change their


values.

▪ There are three built-in data types for numbers in Python3:


• Floating-point
Integer (int)
numbers (float)
(not used much in Python
• Complex numbers: <real part> + <imaginary programming)
▪ Compmaro>t nj Function Description
Number int(x) to convert x to an integer
Functions
float(x) to convert x to a floating-point number
abs(x) The absolute value of x
cmp(x,y) -1 if x < y, 0 if x == y, or 1 if x > y
exp(x) The exponential of x: ex
log(x) The natural logarithm of x, for x> 0
pow(x,y) The value of x**y
sqrt(x) The square root of x for x > 0
Strings

▪ Python Strings are Immutable objects that cannot change their


values.

▪ You can update an existing string by (re)assigning a variable to another string.


▪ Python does not support a character type; these are treated as strings of length
one.

▪ Python accepts single ('), double (") and triple (''' or """) quotes to denote
string literals.
▪ String indexes starting at 0 in the beginning of the string and working their way
from -1
at the end.
Strings

▪ String Formatting

▪ Common String Operators


A sume
Operator string
Description variable a holds 'Hello' and variable b holds
Example
s 'Python’
+ Concatenation - Adds values on either side of the operator a + b will give
HelloPython
* Repetition - Creates new strings, concatenating multiple a*2 will give HelloHello
copies of the same string
[] Slice - Gives the character from the given index a[1] will give
e a[-1] will
give o
[:] Range Slice - Gives the characters from the given range a[1:4] will give ell
in Membership - Returns true if a character exists in the given ‘H’ in a will give True
string
Strings
▪ Common String
Method Description
Methods
str.count(sub, Counts how many times sub occurs in string or in a substring of
beg= string if starting index beg and ending index end are given.
0,end=len(str))
str.isalpha() Returns True if string has at least 1 character and all
characters are alphanumeric and False otherwise.
str.isdigit() Returns True if string contains only digits and False otherwise.
str.lower() Converts all uppercase letters in string to lowercase.
str.upper() Converts lowercase letters in string to uppercase.
str.replace(old, new) Replaces all occurrences of old in string with new.
str.split(str=‘ ’) Splits string according to delimiter str (space if not
provided) and returns list of substrings.
str.strip() Removes all leading and trailing whitespace of string.
str.title() Returns "titlecased" version of string.

▪ Common String str(x) :to convert x to a string


Functions len(string):gives the total length of the
string
Lists

▪ A list in Python is an ordered group of items or elements, and these list


elements don't have to be of the same type.

▪ Python Lists are mutable objects that can change their values.
▪ A list contains items separated by commas and enclosed within square
brackets.

▪ List indexes like strings starting at 0 in the beginning of the list and working their
way from -1 at the end.

▪ Similar to strings, Lists operations include slicing ([ ] and [:]) , concatenation


(+),
repetition (*), and membership (in ).
□ access
□ slice
▪ This example shows how to access, update
□ update
and delete list elements:

□ delete
Lists

▪ Lists can have sublists as elements and these sublists may contain other
sublists
as well.

▪ Common List
Functions Function Description
cmp(list1, list2) Compares elements of both lists.
len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
min(list) Returns item from the list with min value.
list(tuple) Converts a tuple into list.
Lists
Method Description
▪ Common List list.append(obj) Appends object obj to list
Methods
list.insert(index, Inserts object obj into list at offset index
obj)
list.count(obj) Returns count of how many times obj occurs in
list
list.index(obj) Returns the lowest index in list that obj appears
list.remove(obj) Removes object obj from list
list.reverse() Reverses objects of list in place
list.sort() Sorts objects of list in place

▪ List Comprehensions
Each list comprehension consists of an expression followed by a
for clause. □ List comprehension
Python Reserved Words

A keyword is one that means something to the language. In other words, you
can’t use a reserved word as the name of a variable, a function, a class, or a
module. All the Python keywords contain lowercase letters only.

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Tuples

▪ Python Tuples are Immutable objects that cannot changed once they
be have been
created.

▪ A tuple contains it ems separated by commas and enclosed in parentheses instead


of square s. □ access
bracket □ No update

▪ You can update an existing tuple by (re)assigning a variable to another


tuple.

▪ Tuples are faster than lists and protect your data against accidental changes to
these data.

▪ The rules for tuple indices are the same as for lists and they have the same
operations,
functions as well.
Hash Table

• Hashing is a technique that is used to uniquely identify a specific


object
from a group of similar objects.

Assume that you have an object and you want to


assign a key to it to make searching easy.

To store the key/value pair, you can use a


simple array like a data structure where keys
(integers) can be used directly as an index to
store values.
However, in cases where the keys are large
and cannot be used directly as an index, you
should use hashing.
Dictionary

▪ Python's dictionaries are kind of hash table type which consist of


key-value pairs
of unordered elements.
• Keys : must be immutable data types ,usually numbers or strings.
• Values : can be any arbitrary Python object.
▪ Python Dictionaries are mutable objects that can change their values.
▪ A dictionary is enclosed by curly braces ({ }), the items are separated by
commas, and each key is separated from its value by a colon (:).

▪ Dictionary’s values can be assigned and accessed using square braces


([]) with a key to obtain its value.
Dictionary
▪ This example shows how to access, update and delete dictionary
elements:

▪ The
output:
Dictionary

▪ Common Dictionary Functions


• cmp(dict1, dict2) : compares elements of both dict.
• len(dict) : gives the total number of (key, value) pairs in the
dictionary.

▪ Common Dictionary Methods


Method Description
dict.keys() Returns list of dict's keys
dict.values() Returns list of dict's values
dict.items() Returns a list of dict's (key, value) tuple pairs
dict.get(key, For key, returns value or default if key not in dict
default=None)
dict.has_key(key) Returns True if key in dict, False otherwise
dict.update(dict2) Adds dict2's key-values pairs to dict
dict.clear() Removes all elements of dict
Python Control
Structures
Conditionals
▪ In Python, True and False are Boolean objects of class 'bool' and they are
immutable.

▪ Python assumes any non-zero and non-null values as True, otherwise it is


False value.

▪ Python does not provide switch or case statements as in other languages.


▪ Syntax:
if Statement if..else Statement if..elif..else Statement
▪ Exampl
e:
Conditionals

▪ Using the conditional expression


Another type of conditional structure in Python, which is very convenient and easy
to read.


Loops

▪ The For
Loop

▪ The while
Loop
Loops
Loop Control
S break
tatements
:Terminates statement and execution to the
▪ transfers
the
iomompediately following
lloop. statement
the

▪ continue:Causes the loop to skip the remainder of its body and immediately
retest its
condition prior to
reiterating.

▪ pass when a statement is syntacticallybut you do


:Used not required any command
want or code to execute.
Python
Functions
Functions

A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of
code reusing.

Defining a Function

• Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation
string of
the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same
as return None.
Functions

▪ Function
Syntax

▪ Function
Argume
nts
You can call a function by using any of the following types of
arguments:

• Required arguments: the arguments passed to the function in


correct positional order.

• Keyword arguments: the function call identifies the arguments


by the
parameter names.
Functions

• Variable-length arguments: This used when you need to process unspecified


additional
arguments. An asterisk (*) is placed before the variable name in the function
declaration.
Python File
Handling
File Handling

fileObject = open(file_name [, access_mode][, buffering])


▪ File opening
Common access modes:

• “r” opens a file for reading only.


• “w” opens a file for writing only. Overwrites the file if the file exists.
Otherwise, it creates a new file.

• “a” opens a file for appending. If the file does not exist, it creates a
new file
for writing.
▪ Closing a file fileObject.close()
The close() method flushes any unwritten information and closes the file
object.
File Handling

fileObject.read([count])
▪ Reading a file
• The read() method reads the whole file at once.
• The readline() method reads one line each time from
the file.

• The readlines() method reads all lines from the file in a


list.
fileObject.write(string)
▪ Writing in a file
The write() method writes any string to an open
file.
Python Exception
Handling
Exception
Handling
▪ Common Exceptions in Python:
NameError - TypeError - IndexError - KeyError -
Exception

▪ Exception Handling Syntax:

▪ An empty except statement can catch any exception.


▪ finally clause: always executed befor e finishing try
statements.

1
7
EXCEPTION NAME DESCRIPTION
Exception Base class for all exceptions
Raised when the next() method of an
StopIteration
iterator does not point to any object.
SystemExit Raised by the sys.exit() function.
Base class for all built-in exceptions except
StandardError
StopIteration and SystemExit.
Base class for all errors that occur for
ArithmeticError
numeric
calculation.
Raised when a calculation exceeds
OverflowError
maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation
fails.
Raised when division or modulo by zero
ZeroDivisionError
takes place for all numeric types.

AssertionError Raised in case of failure of the Assert


statement.
AttributeError Raised in case of failure of attribute reference or assignment.

Raised when there is no input from either the raw_input() or input() function
EOFError
and the end of file is reached.
ImportError Raised when an import statement fails.
KeyboardInter Raised when the user interrupts program execution, usually by pressing Ctrl+c.
rupt
LookupError Base class for all lookup errors.
IndexErro Raised when an index is not found in a sequence.
r Raised when the specified key is not found in the dictionary.
KeyError
NameError Raised when an identifier is not found in the local or global namespace.

UnboundLoc
Raised when trying to access a local variable in a function or method but no value
al Error
has
Environment
E rror been assigned to it.
Base class for all exceptions that occur outside the Python environment.
Raised when an input/ output operation fails, such as the print statement or the
IOError
open() function when trying to open a file that does not exist.
Raised for operating system-related errors.
IOError
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.
Raised when the interpreter finds an internal problem, but when this
SystemError error is encountered the Python interpreter does not exit.

Raised when Python interpreter is quit by using the sys.exit() function. If not
SystemExit handled in the code, causes the interpreter to exit.
Raised when an operation or function is attempted that is invalid for the
TypeError
specified data type.
Raised when the built-in function for a data type has the valid type of
ValueError arguments, but the arguments have invalid values specified.

RuntimeError Raised when a generated error does not fall into any category.

Raised when an abstract method that needs to be implemented in an inherited


NotImplementedError class is not actually implemented.
Python
Modules
Modules

▪ A module is a file consisting of Python code that can define functions, classes
and variables.

▪ A module allows you to organize your code by grouping related code which
makes the code easier to understand and use.

▪ You can use any Pyt hon source file as a module by ecuting an import
statement ex

▪ Python's from statement lets you import specific attributes from a module into
the
current namespace.

▪ import * statement can be used to import all names from a module into the
current
Python Object
Oriented
Python Classes

□ Class variable

□Class
constructor

Output □
Python Classes

▪ Built-in class functions


• getattr(obj, name[, default]) : to access the attribute of object.
• hasattr(obj,name) : to check if an attribute exists or not.
• setattr(obj,name,value) : to set an attribute. If attribute does not exist,
then it
would be created.

• delattr(obj, name) : to delete an attribute.


▪ Data Hiding You need to name attributes with a double underscore prefix,
and those attributes then are not be directly visible to outsiders.
Class
Inheritance
Python vs.
Java
Code
Examples
Python vs. Java

▪ Hello
World
Ja Python
va

▪ String
Operations
Python
Java
Python vs. Java

▪ Collectio
ns

Java Python
Python vs.
▪ Class and Java
Inheritance
Java

Pytho
n


Python Useful
Tools
Useful Tools

▪ Python IDEs
•Vim
•Eclipse with
PyDev
•Sublime
Text

•Emacs
•Komodo
Edit
Useful Tools

▪ Python Web
Frameworks
•Django
•Flask
•Pylons
•Pyrami
d

•Turbo
Who Uses
Python?
Organizations Use Python

• Web Development :Google, Yahoo


• Games :Battlefield 2, Crystal Space
• Graphics :Walt Disney Feature Animation, Blender
3D

• Science :National Weather Service, NASA, Applied


Maths

• Software Development :Nokia, Red Hat, IBM


• Education :University of California-Irvine,
SchoolTool

• Government :The USA Central


References
1 Python-course.eu, 'Python3 Tutorial: Python Online Course', 2015. [Online].
Available: http://www.python-course.eu/python3_course.php.

2www.tutorialspoint.com, 'Python tutorial', 2015. [Online].


Available: http://www.tutorialspoint.com/python/index.htm.

3Wikipedia, 'History of Python', 2015. [Online]. Available:


https://en.wikipedia.org/wiki/History_of_Python#Version_release_d
ates.

4 Docs.python.org, 'What's New In Python 3.0’, 2015. [Online].


Available: https://docs.python.org/3/whatsnew/3.0.html.

5Sebastianraschka.com, 'Python 2.7.x and Python 3.x key differences',


2015. [Online].
Available:
http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html.

6Programcreek.com, 'Java vs. Python: Why Python can be more productive?', 2015.
[Online]. Available:
http://www.programcreek.com/2012/04/java-vs-python-why-python-can-be-more-
Referenc
7Stsdas.stsci.edu,
'A Quick Tour of
Available: http://stsdas.stsci.edu/pyraf/python_quick_tour.html.
Pytheons,' 2015.
8Lynda.com - A LinkedIn Company, 'Python 3 Essential Training | Lynda.com Training',
2015. [Online]. Available: [Online].
http://www.lynda.com/Python-3-tutorials/essential-training/62226-2.html.

9Pymbook.readthedocs.org, 'Welcome to Python for you and me — Python for you


and me 0.3.alpha1 documentation', 2015. [Online]. Available:
http://pymbook.readthedocs.org/en/latest/index.html.

10Code Geekz, '10 Best Python IDE for Developers | Code Geekz', 2014. [Online].
Available: https://codegeekz.com/best-python-ide-for-developers/.

11K. Radhakrishnan, 'Top 10 Python Powered Web Frameworks For Developers',


Toppersworld.com, 2014. [Online]. Available:
http://toppersworld.com/top-10-python-powered-web- frameworks-for-developers/.
[12] Wiki.python.org, 'OrganizationsUsingPython - Python Wiki', 2015. [Online].
Available: https://wiki.python.org/moin/OrganizationsUsingPython.
Thank
You

You might also like