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

Unit 2 - final

Uploaded by

jankar123
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)
5 views

Unit 2 - final

Uploaded by

jankar123
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/ 69

Unit – 2

Topics Covered in Unit -2


Python interpreter and interactive mode;
values and
types: int, float, booleans, strings, and lists;
variables,
expressions, statements, tuple assignment,
precedence
of operators, comments; modules and
functions,
function definition and use, flow of execution,
parameters and arguments; Illustrative
What is python?
 Python is an open source, object-oriented,
high-level powerful programming language.
 Developed by Guido van Rossum in the early
1990s. Named after Monty Python.
 Python runs on many Unix variants, on the
Mac, and on Windows 2000 and later.
 Python was designed to be a highly readable
language.
 The syntax of the Python programming
language is the set of rules which defines how
a Python program will be written.
Python Program
 Python programs are composed of modules
 Modules contain statements
 Statements contain expressions
 Expressions create and process objects
Features of Python
• Simple
• Easy to learn
• Versatile
• Free and open source
• High level language
• Interactive
• Portable
• Object oriented
• Interpreted
• Dynamic
• Extensible
• Embeddable
• Extensive libraries
• Secure
• Easy Maintenance
• Robust
• Multi-threaded
• Garbage Collection
Features of python
Simple:
o It is a simple and small language.
o Reading a program written in python feels almost like reading
English.
Easy to learn:
o It is clearly defined and easily readable.
o The structure of the program is very simple.
o It uses few keywords and a clearly defined syntax.
Versatile:
o Python supports development of a wide range of applications
ranging from simple text processing to WWW browsers to
games.
Free and open source:
o Python is a example of an open source software.
o Anyone can freely distribute it, read the source code, edit it,
and even use the code to write new(free) programs.
Features of python
High-level Language:
o When writing programs in python, the programmer’s don’t have to
worry about the low-level details like managing memory used by
the program.
Interactive:
o Programs in python work in interactive mode which allows
interactive testing and debugging of pieces of code.
o Programmers can easily interact with the interpreter directly at
the python prompt.
Portable
o It uses wide variety of hardware platform and has same interface
on all platforms.
o Programs can work on any operating system like Linux, windows,
FreeBSD, Solaris, OS/2, AROS, AS/400, BeOS, OS/390, Palm
OS,QNX, VMS.
Features of python
Object Oriented:
o It supports object-oriented as well as procedure
oriented style of programming.
o It encapsulates data and functionalities within objects.
o Implementing OOP’s concepts.
Interpreted
o Python is processed at run-time by the interpreter.
o No need to compile a program before executing it.
o Simply run the program.
o Python converts the source code into an intermediate
form called bytecode, which is translated in to the
native language.
Features of python
Dynamic
o It executes dynamically.
o Programs written in python can be copied and used for flexible
development of applications.
o If there is any error, it is reported at run-time to allow
interactive program.
Extensible
o It is an open source software.
o Anyone can add low level modules
o These modules enable programmers to add or customize their
tools to work more efficiently.
Embeddable
o Programmers can embed python within their c, c++, corba and
java to give scripting capabilities for users.
Features of python
Extensive:
o It has huge libraries that is easily portable across different
platforms.
Easy Maintenance:
o Code written in python is easy to maintain.
Secure:
o Python language environment is secure from tampering.
o Models can be distributed to prevent altering the source
code.
Robust:
o Python programmers cannot manipulate memory directly.
o For every syntactical mistake, a simple and easy to interpret
message is displayed.
Features of python
Multi-threaded
o Python supports multi-threading.
o It executing more than one process of a
program simultaneously.
o It also allows programmers to perform
process management tasks.
Garbage Collection:
o Python run time environment handles
garbage collection of all python objects.
Applications of python
 Can be used as an Embedded Scripting Language
 Creating 3D Software (Eg:Maya)
 Web and Internet Development (Eg: Quora, Odoo)
 Scientific and Numeric Computing
 Desktop GUIs
 Operating Systems (Eg: Ubuntu)
 Software Development (Eg: Apple’s Swift, Cobra)
 Prototyping
 Network Programming
 Business / Enterprise Applications
 Education
 Mobile Applications
 Database Access
 Games and Graphical Applications (Eg: Civilization IV, Disney’s
Toontown Village)
POPULAR APPLICATIONS BUILT
USING PYTHON

Google search engine


BitTorrent
Youtube
Dropbox
Cinema 4D, etc
PYTHON INTERPRETER
 Python is an interpreted language because they are executed by

an interpreter.

 Interpreter takes high level program as input and executes what

the program says.

 It translates program as one statement at a time

 It takes less amount of time to analyze the source code but the

overall execution time is slower.

 It continues translating the program until the first error is met, in

which case it stops. So debugging is easy.

 Executes statements from top to bottom


INTERPRETER AND COMPILER
PYTHON INTERPRETER
INTERPRETER COMPILER

Translates program one statement at a time. Scans the entire program and translates it as a
whole into machine code.
It takes less amount of time to analyze the source It takes large amount of time to analyze the
code but the overall execution time is slower. source code but the overall execution time is
comparatively faster.
No intermediate object code is generated, hence Generates intermediate object code which further
are memory efficient. requires linking, hence requires more memory.

Continues translating the program until the first It generates the error message only after scanning
error is met, in which case it stops. Hence the whole program. Hence debugging is
debugging is easy. comparatively hard.
Programming language like Python, Ruby use Programming language like C, C++ use
interpreters. compilers.
DOWNLOADING & RUNNING PYTHON PROGRAM
from https://www.python.org/  Downloads 
Download for Windows. Once selected, it will
start to download. A Python package
including python exe, module docs and
documentation.
There are two ways to run a Python program
– Interactive mode and Script mode
Interactive Mode

Interactive mode is a command line shell which


gives immediate feedback for each statement, while
running previously fed statements in active memory.
Directly interacts with the interpreter
What is typed is immediately run in interactive
mode
Can be used as a calculator
Not suitable if lines of code are more
Use: can be used widely for testing
To run a program in interactive mode, open python
IDLE
Script Mode

Used for programs with more number of lines


Two ways of writing the python program in script
mode are
Method 1 - Using the editor available in IDLE.
Open IDLE -> File -> New File.
Method 2 - Using any editor such as Notepad.
The program must be saved with “.py” extension
To run the .py file
For Method 1, just press F5 and output will be
displayed
For Method 2, Open Cmd prompt, traverse to
the program location and just type
<filename.py> to run the file
Method 1 can also be executed using Cmd
prompt
VALUES AND TYPES

The data types available in Python are


Numbers
Boolean
Strings
List
Tuple
Dictionary
Numbers
The numbers represent the Integers, Floating
Point Numbers and Complex Numbers
The data type of the variable can be found
using type (variable_name) function.
Arithmetic operations are applied on
numbers.
The imaginary part in complex numbers is
represented using j or J.
EXAMPLES
>>> a=9
>>> type(a)
<class 'int'>
>>> a=10.9
>>> type(a)
<class 'float'>
>>> s='hello'
>>> type(s)
<class 'str'>
EXAMPLES
BOOLEAN
A Boolean variable can take only two values,
True or False. Boolean values are mainly
used in logical expressions.
Boolean expressions are used in conjunction
with IF statements
Boolean operations are performed using the
keywords – and, or, not
Example of Boolean Operators
1. b = 30 > 45
b
Output: false
2. (30 > 45) or (27 < 30)
Output: True
3. not (3 > 4)
Output: True
4. >>> 3>4
O/p : False
5. >>> test=(3>4)
>>> test
O/p :False
6. >>> type(test)
O/p: <class 'bool'>
STRINGS
 A Strings can be given inside any of these symbols
 Single quote - ‘ ‘
 Double quote - “ “
 Triple quote - ‘’’ ‘’’
 When triple quotes are used, then multiple lines can be
given in interactive mode
Arithmetic operations can’t be applied on
strings except + and *.
The + operator is used to concatenate the
strings and * operator repeats the string
The default input type is string in Python
String concatenation can also be performed
typing the strings adjacently.

In order to print strings with ‘t or ‘n, they


must be printed as Raw Strings. Else it will
be mistaken for tab space or new line
character
Similarly, to print ‘t, ‘s in between the
sentences, they must be preceded by an
escape character \

In order to print double quotes within double


quotes, the double quotes can be preceded
with a backslash as given below
 The string can be formatted using the built in format
function as given below:
 Here ‘<’ symbol performs left justification, ‘>’ perform
right justification and ‘^’ performs centre justification

 To summarize, the escape sequences can be tabulated


along with the purpose as
If the string has to be represented in any
other language than English then it can be
specified as Unicode text using ‘u’. This can
be given as below:
>>> u"sample"
'sample'
The prefix ‘u’ specifies that the file contains
text that is written in language other than
English.
LISTS
A List is a sequence of values. The elements or items
in a list can be of any data type.
The items in a list are enclosed within a square bracket
[]
Examples: [10, 89, 87, 45, 36] [‘python’, ‘java’,
‘smalltalk’] etc
The elements in a list need not be of the same data
type. Example: [12, 56.78, ‘abc’] [10, 20, 30]]
This example contains a list within another list – nested
list. Example: [23, 34.67, ‘apple’, [56, ‘as’, 34.55].
The list may be empty, i.e: with no elements – empty
list. Example: a = [ ]
The syntax for accessing the elements of a
list is by using the square bracket. The index
is specified inside the brackets.
The list indices start at 0. For example, in
order to access the third element in the list,
list_name [2] is given.
Python allows negative indexing also. That is,
the index of -1 retrieves the last item.
Lists are mutable. Here in the example
shown, fruits [2] shows ‘mango’ and after
reassigning the values, it will be showing
‘pomegranate’
A List is a sequence of values. The elements
or items in a list can be of any data type.
TUPLES
A Tuple is similar to list as it also consists of
sequence of values.
The values are separated using commas and
are enclosed within parentheses ( ).
The main difference between the list and tuple
is that lists are mutable (i.e: the values in a list
can be changed) while tuples are immutable
(i.e: the values in a tuple cannot be changed
The elements or items in a list can be of any
data type.
DICTIONARY
Python can store data in key – value pairs and the
data type used for this is called Dictionary.
The key values are strings and value can be of
any data type
The key value pairs are enclosed within curly
brackets { }.
The key value pair is separated using colon (:)
To access the value, the key is specified inside a
square bracket [ ]. Eg:
Dictionaries are used for fast retrieval
Like lists, dictionaries are mutable, i.e: the
values can be changed
variables
Rules for defining a variable are:
Variable names must be meaningful and they
should start with a letter (Uppercase or
lowercase) or underscore ( _ ) character.
They can contain both names and numbers, but
shouldn’t start with a number
Punctuation marks are not allowed within
variables
Variable names shouldn’t use keywords and
they are case sensitive. The variable ‘age’ is
different from ‘AGE’.
Examples of valid variable names are: a,
jit0213, honey_farm, _example, etc.
Type of the variable can be found using type
keyword
Python allows multiple variables to be assigned
with a single value, simultaneously. In this example,
the variables a, b, c, d are assigned as 56.
>>> a = b = c = d = 56
Also Python allows different values to multiple
variables. Eg: here the variables a, b, c, d are
assigned to 1, 2, 3, 4 respectively.
>>> a, b, c, d = 1, 2, 3, 4
Variables can be declared again for other values.
For instance, variable ‘a’ can be assigned with an
integer and later it can be changed to string.
Variables can be either a Local variable or a
Global variable. Local variables are those that
are defined inside a function and global
variables are those that are defined outside. A
variable defined inside a function can be
made as a global variable when it is defined
to be global.
Similarly, variable can be deleted using del
command.
Find if the following variable names are valid
or not:
1. >>> 72zombies = ‘globe’
2. google@ = 485123
3. abc = 43
4. def = ‘ I am used in function’
5. a = 02
EXPRESSIONS
An expression is a combination of values,
variables, and operators.
A value is a fundamental thing – like string or a
number – that a program manipulates. Examples
of Values are “Hello”, ‘Hai’, 4.6, 59, etc.
In Python, an expression must have atleast one
operand and one or more operators.
Operand  value on which the operator is
applied. Eg: A + B * C – D. In this expression, A,
B, C, D are operands and +, *, - are operators.
When an expression is typed, the interpreter
evaluates it and finds the value of the
expression.
When an expression has more than one
operator, then the Python interpreter
evaluates it based on operator precedence.
ARITHMETIC OPERATORS
OPERATOR PURPOSE

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operator

** Exponentiation

// Floor Division

^ Bitwise Operator, XOR


Operator precedence
The operator precedence is in the order of
Parentheses, Exponentiation, Division,
Multiplication, Addition and Subtraction –
PEDMAS
Operators with same precedence are
evaluated from left to right.
Operator precedence
Rank Operator Meaning
1 () Parenthesis
2 ** Exponential
3 *,/,%,// Multiplication,
division , modulo ,
floor division
4 +,- Addition ,
Subtraction
Operator Precedence Examples
Exponent and Multiplication
 Exponent will always run before the
multiplication equation.
Example:
#Exponent Runs First
>>> 2 ** 4 + 2
Output : 18
#If
>>> 2 * 4 ** 2
Output : 32.
Exponent and division
Exponent will always run before a division
equation.
Example:
#Exponent runs first
>>> 4 / 2 ** 6
Output : 0.0625
Multiplication and division
 In this scenario Python will run the equation
from left to right since multiplication and
division have the precedence.
 Take a look at the example below.
Example:
#In this case division is ran first
then multiplied by 3
>>> 5 / 4 * 3
Output : 3.75
#In this case 3 is multiplied by 4
then divided by 5
>>> 3 * 4 / 5
Multiplication and Addition
 Multiplication will run before an addition equation
since multiplication has more precedence over
addition. Here is an example.
Example :
>>> 2 + 4 * 4
Output : 18

Addition and Subtraction


 In this scenario the equation will run left to right
since addition and subtraction are on the same level.
Example:
>>> 2 + 3 - 5 + 8 - 4
+ 2 - 9
Output: -3
COMMENTS

In order to add notes to the programs,


Comments are given in natural language to
say what the program is doing.
Comments in Python start with the # symbol.
The comment appears on a line by itself or it
can be given at the end of a line
Everything from the # to the end of the line
is ignored and it has no effect on the
execution of the program.
COMMENTS

Comments are most useful to document non-


obvious features of the code. It helps the
reader to understand what the code does.
But the main drawback in Python is it does
not support multiline comment.
TUPLE ASSIGNMENT
Python has a very powerful tuple
assignment feature that allows a tuple of
variables on the left of an assignment to be
assigned values from a tuple on the right of the
assignment.
That is, left side is a tuple of variables and right
side is the tuple of values.
Number of variables on the left must be equal to
the number of values on the right.
When the number of variables on the left is equal
to the number of variables on the right, then each
value will be assigned to one variable each.
When the number of variables on the left is
one and the number of variables on the right
is more, then each value will be assigned to
that one variable, similar to the concept of
arrays
When the number of variables on the left is
greater to the number of variables on the
right, then an error will occur
The statement x, y, z = a is equivalent to x =
a[0], y = a[1] and z = a[2]
This concept is very useful in swapping two
variables using a single sentence. Example: to
swap two variables a and b whose values are
100 and 555 respectively, just give a, b = b, a
Additionally, the the right side can be any
kind of sequence, like string, list or tuple.
For example, to split a URL into host_name,
site_name and domain:
Illustrative Programs:
1. Exchange the values of two variables
Program:
To take input from the user
a = input(‘Enter value of a: ‘)
b = input(‘Enter value of b: ‘)
a = 25
b = 200
# create a temporary variable and swap the values
temp = a
a=b
b = temp
print(‘The value of a after swapping: {}’.format(a))
print(‘The value of b after swapping: {}’.format(b))
Output:
The value of a after swapping: 200
The value of b after swapping: 25
Circulate the values of n variables
Distance between two points
Program:
def dis(x1,y1,x2,y2):
dist=((x1-x2)**2+(y1-y2)**2)**.5
return(dist)
Output:
dis(10,20,30,50)
36.05551275463989
Thank You

You might also like