0% found this document useful (0 votes)
4 views73 pages

Python Unit 1

The document provides an overview of Python programming, including its definition, history, and applications. It discusses the advantages of Python, its programming cycle, and differences between programming and scripting languages. Additionally, it covers installation, basic syntax, data types, and popular Integrated Development Environments (IDEs) for Python development.

Uploaded by

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

Python Unit 1

The document provides an overview of Python programming, including its definition, history, and applications. It discusses the advantages of Python, its programming cycle, and differences between programming and scripting languages. Additionally, it covers installation, basic syntax, data types, and popular Integrated Development Environments (IDEs) for Python development.

Uploaded by

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

PYTHON PROGRAMMING

By AYUSHI
Agenda:

❑ What is Python?
❑ Why Python?
❑ Differences between Programming and Scripting Language
❑ History of Python
❑ Scope of Python
❑ What can I do with python ?
❑ Who uses Python today?
❑ Why do people use python?
❑ Installing Python IDE
❑ A Sample Code
❑ Python Code Execution
❑ Running Python
❑ Python Basic (Variables, Strings, Data types, etc.)
❑ Operators and Expressions
WHAT IS PYTHON?
▪ Python is a general-purpose interpreted, interactive, object-oriented, and

high-level programming language.

▪ Python is an easy language to learn because of its simple syntax.

▪ Python can be used for simple tasks such as plotting or for more complex tasks

like machine learning.


PYTHON PROGRAMMING CYCLE
▪ Relatively shorter than other language.

▪ There is no compile or link step while it is inbuilt step.

▪ Python interpreter internally do the compilation.

▪ Python program simply imports library at run time and uses


the objects.

▪ Python : Run->test->Edit->Run

▪ Others: Run->Test->edit->Recompile->Link->Run
▪ Python is an interpreted, high-level, general-purpose programming

language. A python programming cycle consists of below main steps.


▪ Design a solution

▪ Write a code

▪ Test the code

▪ Debug the code

▪ Repeat 2-4 until the program runs correctly.

For more detail : https://problemsolvingcode.com/various-stages-in-the-


python-programming-cycle
▪ Traditional Programming Cycle ▪ Python Programming Cycle

▪ The programmer writes the code, ▪ The programmer writes the code and then
compiles it, and executes it. runs it.
▪ The code is compiled into an executable ▪ The code is directly interpreted by the Python
file. interpreter.
▪ The code is run on a computer. ▪ The code is run on a Python interpreter.
▪ The programmer must declare variables ▪ The programmer does not need to declare
before using them. variables before using them.
▪ The programmer needs to specify the data ▪ The programmer does not need to specify the
type of the variables. data type of the variables.
▪ The programmer needs to free the ▪ The interpreter automatically releases the
memory allocated for the variables. memory allocated for the variables.
▪ The programmer needs to handle memory ▪ The interpreter handles memory
management. management.
▪ The code is executed on a specific ▪ The code is executed on any platform that has
platform. a Python interpreter.
WHY PYTHON?
▪ It’s simple, and less complicated code which can be developed much lesser time than other languages and
easily maintained.

▪ Because a programmer's time to develop code is more expensive than a computer's time to run that code.
Python is a good language for programmers to stay very productive.

▪ Huge community, across a variety of domains.

▪ Great available libraries covering a lot of areas:

▪ NumPy, SciPy for scientific computing.

▪ scikit-learn is quite popular for machine learning applications

▪ Scrapy, BeautifulSoup for writing data scrapers and parsing HTML/XML.

▪ nltk for Natural Language Processing.

▪ IPython, which is like a super REPL.

▪ Django for web development.


DIFFERENCES BETWEEN PROGRAM AND SCRIPTING LANGUAGE
▪ A programming language is a computer language that is used to ▪ A scripting language is a type of programming language designed for a
communicate with computers using a set of instructions. runtime system to automate the execution of tasks.
▪ It is compiled language or compiler-based language. ▪ It is interpreted language or interpreter-based language.

▪ It is used to develop an application or software from scratch. ▪ It is used to combine existing components and automate a specific task.

▪ It runs or executes independently and does not depend on the parent ▪ It runs or executes inside another program.
(exterior) program ▪
▪ It uses an interpreter to convert source code into machine code.
▪ It uses a compiler to convert source code into machine code.
▪ As it uses an interpreter, hence the program is converted into machine
▪ As it uses a compiler, hence the complete program is converted into code line by line.
machine code in one shot.
▪ It is comparatively difficult to write code in a programming language,
▪ It is comparatively difficult to write code in a programming language, and and it requires numerous lines of code for each task.
it requires numerous lines of code for each task.
▪ The development time in a scripting language as a smaller number of
▪ The development time in programming languages is high as more lines lines are required.
are required.
▪ There is less maintenance cost.
▪ There is the high maintenance cost.
▪ All scripting languages are programming languages.
▪ All programming languages are not scripting languages.
▪ It does not create .exe file.
▪ It generates a .exe file.
▪ Scripting languages provide great support to user interface design, data
▪ Usually, programming languages do not support or provide very little types, and graphic design.
support for user interface designing, data types, and graphic designing.
▪ Some popular examples are Perl, Python, JavaScript, etc.
▪ Some popular examples are C, C++, Java, Scala, COBOL, etc.
HISTORY OF PYTHON
▪ Python laid its foundation in the late 1980s.
▪ The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in
Netherland.
▪ In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
▪ In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
▪ Python 2.0 added new features such as list comprehensions, garbage collection systems.
▪ On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
the fundamental flaw of the language.
▪ ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
▪ The following programming languages influence Python:
▪ ABC language.
▪ Modula-3
▪ Open sourced from the beginning.
HOW IT IS NAMED AS PYTHON?
When he began implementing Python,
Guido van Rossum was also reading the
published scripts from “Monty Python's
Flying Circus”, a BBC comedy series from
the 1970s.Van Rossum thought he needed
a name that was short, unique, and
slightly mysterious, so he decided to call
the language Python.
PYTHON’S BENEVOLENT DICTATOR FOR LIFE

“ Python is experiment in
how much freedom
programmers need. Too
much freedom and nobody
can read another’s code; too
little and expensiveness is
endangered.”
-Guido Van
Rossum
WHY WAS PYTHON CREATED?
“My original motivation for creating Python was the perceived need for a
higher level language in the Amoeba [operating systems] project.

I realized that the development of system administration utilities


in C was taking too long. Moreover, doing these things in the Bourne shell
wouldn’t work for a variety of reasons,…

So, there was need for a language that would bridge the gap
between C and the shell.”

- Guido Van Rossum


SCOPE OF PYTHON
▪ Science
▪ Bioinformatics

▪ System Administration
▪ Unix
▪ Web logic
▪ Web Sphere

▪ Web Application Development


▪ CGI
▪ JYTHON Servlets

▪ Testing Scripts
WHAT CAN WE DO WITH PYTHON?

System Programming

Graphical User Interface Programming

Internet Scripting

Component Integration

Database Programming

Gaming, Images, XML, Robot and more


WHO USES PYTHON TODAY?

▪ Python is being applied in real revenue-generating products by real companies.

▪ For instance:

▪ Google makes extensive use of Python in its web search system and employs
Python’s creator.
▪ Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for
hardware testing.
▪ ESRI uses Python as an end-user customization tool for its popular GIS mapping
products.
▪ The YouTube video sharing service is largely written in Python.
WHY DO PEOPLE USE PYTHON?
The following primary factors cited by Python users seem to be ▪ It’s portable
these: ▪ Python runs virtually every major platform

▪ Python is object-oriented used today.


▪ Structure supports such concepts as polymorphism, ▪ As long as you have Python compatible
operation overloading and multiple inheritance. interpreter installed, Python will run in
exactly same manner, irrespective of
▪ It’s powerful
platforms.
▪ Dynamic Typing
▪ It’s free (open source)
▪ Built-in types and tools
▪ Downloading and installing python is free
▪ Library Utilities
and easy.
▪ Third Party Utilities (e.g. Numpy, Scipy, Numeric)
▪ Source code is easily accessible.
▪ Automatic memory management
WHAT IS INTEGRATED DEVELOPMENT
ENVIRONMENT (IDE)
▪ IDE stands for Integrated Development Environment.

▪ IDE is basically a software pack that consist of equipment’s which are used for developing and
testing the software.

▪ A developer throughout SDLC uses many tools like editors, libraries, compiling and testing
platforms.

▪ IDE helps to automate the task of a developer by reducing manual efforts and combines all
the equipment’s in a common framework.

▪ If IDE is not present, then the developer has to manually do the selections, integrations and
deployment process. IDE was basically developed to simplify the SDLC process, by reducing
coding and avoiding typing errors.
PYTHON IDES
▪ Pycharm

▪ Jupyter Notebook

▪ Enthought Canopy

▪ IDLE(Default with Python Installation)

▪ Spyder

▪ Pydev

▪ Wing
IDLE
IDLE SCRIPT WRITER(FROM FILE SELECT NEW)
SAVE WITH .PY EXTENSION
IDLE IS A POPULAR INTEGRATED DEVELOPMENT LEARNING ENVIRONMENT WRITTEN IN
PYTHON AND IT HAS BEEN INTEGRATED WITH THE DEFAULT LANGUAGE.

▪ IDLE is a very simple and basic IDE which is mainly used by the beginner level developers
who want to practice on python development

▪ IDLE is developed purely in Python with the usage of Tkinter GUI toolkit

▪ It has a good feature of multi-window text editor which has many features like call tips, smart
indentation, undo and python colorizing.
OTHER EDITOR INTERFACES
PYCHARM IS ONE OF THE WIDELY USED PYTHON IDE WHICH WAS CREATED BY JET
BRAINS. IT IS ONE OF THE BEST IDE FOR PYTHON.
PYCHARM
Pros.
1. It comes with an intelligent code editor, smart code
navigation
2. PyCharm is integrated with features like debugging, testing,
deployments, and tools of the database.
3. PyCharm also provides support to python web development
frameworks, JavaScript, HTML, CSS etc.
Cons.
1. PyCharm is an expensive tool
2. The initial installation is difficult and may hang up in between
sometimes.
(SPYDER)IT IS FAMOUS FOR PYTHON DEVELOPMENT. IT WAS MAINLY
DEVELOPED FOR SCIENTISTS AND ENGINEERS TO PROVIDE A POWERFUL
SCIENTIFIC ENVIRONMENT FOR PYTHON
SPYDER
Pros.
1. It is a good IDE with syntax highlighting, auto code
completion feature
2. A developer can execute the code line by line or by the cell.
3. Can trace each step of the script execution smoothly.
Cons.
1. not capable of configuring which warning the developer
wants to disable.
2. Its performance reduces when too many plugins are invoked
at the same time.
JUPYTER NOTEBOOK
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.


GOOGLE COLAB
RESERVED WORDS
▪ Reserved 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. All the Python keywords contain lowercase letters only.
▪ and
▪ 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 ,None
LINES AND INDENTATION

▪ Python provides 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


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 −

▪ word = 'word' sentence = "This is a sentence." paragraph = """This is

a paragraph. It is made up of multiple lines and sentences."""


INSTALLING PYTHON

▪ Python is pre-installed on most Unix sytems, including

Linux and MacOS X.

▪ But for Windows operating systems user can download

from the
https://www.python.org/downloads/

-from the above link download latest version of python


IDE and install.
PYTHON INTERACTION
▪ There are two ways to interact with Python
i. Immediate Mode (command line based).
ii.Script Mode (GUI Based).
▪ In python (>>>) and (…) indicates taking input.
(remaining all indicates output in python).
NOTE : for input and output python provides functions like
input() and print().
TARGET CODE GENERATION PROCESS
▪ Python source file having extension(.py)
ex: “file_name.py”
▪ source file compiled by compiler and Produces a file with (.pyc
) extension file. it's also called as compiled sourcefile.it contains
intermediary code which is known as “BYTE CODE”.
ex: “file_name.pyc”
▪ BYTE CODE will Processed by INTERPRETER and produces
"TARGET CODE" file with an .pyo extension.
ex: “file_name.pyo”
EXAMPLE
⚫ Write a 1st program Print Hello
⚫ Simply the program is

>>> print(“ Hello World!”)


OR
>>> print('Hello World!‘)

⚫ After that save it as hello.py

.PY as Extension for Python


▪ Inputs:
a = input(“Enter Data”)
▪ Outputs:
print a, ‘\n’, type(a)
▪ Code Comment:
1) #Single line Comments
2) ””” Multi line
comments”””
▪ New line:
\n
VARIABLES

▪ A variable is a reference to a value stored in a computer’s memory.

▪ Variables can be sorted into a variety of categories (or data types)

such as numbers (int/float etc), Boolean values (true/false), and


sequences (strings, lists etc).
VARIABLES NAMING RULE
▪ A variable name must start with a letter or the underscore
character.

▪ A variable name cannot start with a number.

▪ A variable name can only contain alpha-numeric


characters and underscores (A-z, 0-9, and _ )

▪ Variable names are case-sensitive (age, Age and AGE are


three different variables)
Data Types
Data Types in Python:

1)Mutable - A variable is mutable if its value can be changed after creation. Examples of
mutable variables include lists, dictionaries, and sets.

2)Immutable - A variable is immutable if its value cannot be changed after creation. Examples
of immutable variables include int, float, bool, complex, strings, tuples, and sets.

i.Numbers

ii.Lists
Note : In python no need to define a
iii.Tuple variable as in like other programming
languages (C/C++), and there is no data
iv.Dictionary type for variable.
v.Strings
NUMBERS
▪ int Ex: var = 25
▪ long var = 12345678912
▪ float var = 1.2
▪ complex var = 1j
▪ bool var = True or False
Strings
▪ Strings can be represent by using single quotes or double quotes.

▪ ex : "String" or 'string'.

▪ In python we have multi line strings using triple quotes.

doc_string = """This is the 1st line.

This 2nd line.

This 3rd line. """ (or)

doc_string = '''This is the 1st line.

This second line.

This third line. '''


TYPE CASTING
▪ The conversion of one data type into the other data type is known as

type casting in python or type conversion in python.

▪ Python supports a wide variety of functions or methods like: int(), float(),

str(), ord(), hex(), oct(), tuple(), set(), list(), dict(), etc.

▪ Syntax :

var = datatype(var)

Note : To check the type of a variable we use type() function.


EXAMPLE
Operators
•Arithmetic Operator
•Relational Operator
•Logical Operator
•Bitwise Operator
•Assignment Operator
•Membership Operators
•Identity Operators
Arithmetic operator
•Exponent (**)
•Multiplication (*)
•Division (/)
•Modulus (%)
•Floor Division(//)
•Addition (+)
•Subtraction (-)
Relational operator
•Less Than (<)
•Greater Than (>)
•Equal to (==)
•Not Equal to (!=)
•Less than are Equal to (<=)
•Greater than are Equal to (>=)

"The result of relational operator


is either True or False"
Bitwise operator
•Bitwise Tilde (~)
•Bitwise Right shift (>>)
•Bitwise Left shift (<<)
•Bitwise AND (&)
•Bitwise Exponent (^)
•Bitwise OR (|)
Assignment operator
•Assignment ( = )
&=
•Compound Assignment
|=
+=
^=
-=
>>=
*= <<=
/=
NOTE: Assigning more than one variable at
%=
a time possible in python.
//= Example : a, b= 5,6
a value is 5
**= b value is 6.
PRACTICE:
1. >>> a = 10
9. >>>c <<= 2

10. >>>print(c) → 12
2. >>> b = 2

11. >>> print(c/5) → 2.4


3. >>> c = 3
12. >>> print(c//5) →2
4. >>> print(a//c) →3
13. >>> print(~c) → -13
5. >>> a+=2

→ 12 14. >>> print(a!=c) → False


6. >>> print(a)

→8 15. >>> a %= 5
7. >>>> print(b**3)

→-3 16. >>> print(a) →2


8. >>> print(~b)
Membership operator
•in : Evaluates to true if it finds a variable in the specified
sequence and false otherwise.
•Not in : Evaluates to true if it does not finds a variable in the
specified sequence and false otherwise.
•Ex1: a = 10
b = 20
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"
▪ Example:
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
if ( b not in list ):
print("Line 1 - b is available in the given list" )
else:
print("Line 1 - b is not available in the given
list“)
IDENTITY OPERATOR
▪ is : Evaluates to true if the variables on either side of the
operator point to the same object and false otherwise..
▪ Is not : Evaluates to false if the variables on either side of the
operator point to the same object and true otherwise.
▪ Ex1: a = 10

b = 20
if ( a is b):
print “Both are same"
else:
print “Both are not same"
Ex2:
a = 10
b = 20
if ( a is not b ):
print “Both are not same"
else:
print “Both are same"
DIFFERENCE BETWEEN IS AND ==
Parameters is Operator == Operator

The ‘is’ is known as the identity The ‘==’ is known as the


Name
operator. equality operator.

When the variables on either


When the variables on either
side of an operator point at the
side have the exact same value,
exact same object,
Uses the == operator evaluation is
the is operator’s evaluation is
true. Otherwise, it will evaluate
true. Otherwise, it will evaluate
as False.
as False.
LOGICAL OPERATOR
▪ Logical Not
▪ Logical And
▪ Logical Or
Note:
'Logical and', 'Logical or' are called as
short circuit operators.
i. In the case of AND if 1st argument
is Zero then the second statement is
not executed,
ii. In the case of OR if 1st argument is not Zero
then the second statement is not executed
OPERATOR PRECEDENCE
High 1. ** Exponentiation (raise to the power)
2. ~+- Complement, unary plus and minus (method
names for the last two are
+@ and -@)
3. * / % // Multiply, divide, modulo and floor
division
4. +- Addition and subtraction
5. >> << Right and left bitwise shift
6. & Bitwise 'AND‘
7. ^| Bitwise exclusive `OR' and regular
`OR'
8. <= < > >= Comparison operators
9. <> == != Equality operators
10. = %= /= //= -= += *= **= Assignment operators
11. is is not Identity operators
12. in not in Membership operators
Low 13. not or and Logical operators
EXPRESSIONS
▪ A combination of operands and operators is called an expression.

The expression in Python produces some value or result after being


interpreted by the Python interpreter.

▪ An example of expression can be : x=x+10. In this expression, the

first 10 is added to the variable x. After the addition is performed,


the result is assigned to the variable x.
EXAMPLE
EXAMPLES :
5 * 3 > 10 and 4 + 6 == 11
5 * 3 > 10 and 4 + 6 == 11
15 > 10 and 4 + 6 == 11
True and 4 + 6 == 11
True and 10 == 11
True and False
False
PRACTICE QUESTIONS
1. 12 or 10 → 12 7. 12 | 10 → 14

→ 10 12 & 10 →8
2. 12 and 10 8.

3. 0 or 12 → 12 9. 0 ^ 12 → 12

4. 3*2**2+5+7%3 → 18 10. a=3


→1 11. a &= True
5. 5*4%3-4+3

6. 4//2 + 9//3 and 4%2*5 12. print(a) →1


→0
SWAP THE 2 NOS. USING THIRD VARIABLE
a=5
b=10
temp= a
a=b
b=temp
SWAP THE 2 NOS. WITHOUT USING THIRD
VARIABLE
a=5
b=10
a=a+b
b=a-b
a=a-b
SWAP THE 2 NOS. WITHOUT USING THIRD
VARIABLE IN 1 LINE IN PYTHON
a,b=5,10
a,b=b,a
INPUT A 2 DIGIT NUMBER AS STRING THEN
ADD ALL THE NUMBERS PRESENT IN STRING
num=“234”
num1,num2,num3=int(num[0]),int(num[1]),int(num[2])
sum=num1+num2+num3
print(sum)
ANY QUESTIONS?
TEXT BOOKS:
1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3, Shroff/O‘Reilly

Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)

2. Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network Theory Ltd.,

2011.

3. John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT Press , 2013

4. Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary Approach,

Pearson India Education Services Pvt. Ltd., 2016.

5. Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015.

6. Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.

7. Charles Dierbach, ―Introduction to Computer Science using Python: A Computational ProblemSolving Focus, Wiley India

Edition, 2013.

8. Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using Python

3‖, Second edition, Pragmatic Programmers, LLC, 2013


THANK YOU

You might also like