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

Python Notes (KNC-402) UNIT-1

Uploaded by

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

Python Notes (KNC-402) UNIT-1

Uploaded by

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

UNIT 1

Introduction
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990.
Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not after
Python-the snake.
Python 3.0 was released in 2008.
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable.
 Python is Interpreted − Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it. This is similar to
PERL and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.

History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the
Netherlands.
 Python is derived from many other languages, including Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
 Python is copyrighted. Like Perl, Python source code is now available under the
General Public License (GPL).
 Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing its progress.
 Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.
 Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward
compatible with Python 2. The emphasis in Python 3 had been on the removal
of duplicate programming constructs and modules so that "There should be one
-- and preferably only one -- obvious way to do it." Python 3.8.0, documentation
released on 14 October 2019 is the latest version of Python 3.
Python Features
Python's features include −
 Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows a student to pick up the language quickly.

1|P ag e Python Programming (KNC-402)


 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of code.
 Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
 Scalable − Python provides a better structure and support for large programs
than shell scripting.
Python is an easy to learn, powerful programming language. It has efficient high-level
data structures and a simple but effective approach to object-oriented programming.
Python’s elegant syntax and dynamic typing, together with its interpreted nature, make
it an ideal language for scripting and rapid application development in many areas on
most platforms.

2|P ag e Python Programming (KNC-402)


Python IDE:
Python is available at: https://www.python. org/

3|P ag e Python Programming (KNC-402)


On a Linux machine or a Mac you can check to see if Python 3 is installed by opening a
terminal window and typing python at the prompt. If Python is not installed, you can
download it at the python.org website.

After installing Python, you should be able to invoke Python on the command line in a
terminal window by typing the name of the program.

This opens the Python Interpreter, where you can run Python code directly in the
terminal by typing ‘python’ and hitting the Enter key:

4|P ag e Python Programming (KNC-402)


Interactive Mode

When commands are read from a tty, the interpreter is said to be in interactive mode.
In this mode it prompts for the next command with the primary prompt, usually three
greater-than signs (>>>); for continuation lines it prompts with the secondary prompt,
by default three dots (...). The interpreter prints a welcome message stating its version
number and a copyright notice before printing the first prompt:

$ python3.8
Python 3.8 (default, Sep 16 2015, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more
information.
>>>

Continuation lines are needed when entering a multi-line construct. As an example,


take a look at this if statement:

>>>

>>> the_world_is_flat = True


>>> if the_world_is_flat:
... print("Be careful not to fall off!")
...
Be careful not to fall off!

5|P ag e Python Programming (KNC-402)


Interacting with Python Programs:
First Python Program on shell-

>>> 4+5

Out put is-----9

----------------------------

>>> “ Hello Students”

Output is---‘Hello Students’

-------------------------------

>>>print(“Hello, Students”)

output is ---- Hello, Students

--------------------------------------------------

name=input("Enter your name: ")

Enter your name: Sachin Tendulkar

>>> name

'Sachin Tendulkar'

>>> print(name)

Sachin Tendulkar

---------------------------------------------

Program to add two numbers


>>> a=int(input("Enter first number-:"))

Enter first number-:10

>>> b=int(input("Enter second number-:"))

Enter second number-:20

>>> c=a+b

>>> print("Sum = ", c)

6|P ag e Python Programming (KNC-402)


Sum = 30

----------------------------------

a=input("enter first number-")

enter first number-10

>>> b=input("enter second number-")

enter second number-20

>>> c=a+b

>>> c

'1020'

>>> print(c)

1020

----------------------------------------

Program to calculate area of circle


>>> radius=int(input("Enter the radius of circle--"))

Enter the radius of circle--10

>>> area=3.14*radius*radius

>>> print("Area of circle is--",area)

Area of circle is-- 314.0

----------------------------------------------------------------------------------

Program to calculate Simple Interest


>>> p=int(input("Enter principle Amount-"))

Enter principle Amount-1000

>>> r=float(input("Enter rate of interest--"))

Enter rate of interest--3.5

>>> t=float(input("Enter time--"))

7|P ag e Python Programming (KNC-402)


Enter time--2

>>> SI=(p*r*t)/100

>>> print("Simple Interest =",SI)

Simple Interest = 70.0

----------------------------------------------------------------

Elements of Python:
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. Thus, NAME and name are two
different identifiers in Python.
Here are naming conventions for Python identifiers −
 Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
 Starting an identifier with a single leading underscore indicates that the
identifier is private.
 Starting an identifier with two leading underscores indicates a strong private
identifier.
 If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.

Reserved Words
 The following list shows the Python keywords. These are reserved words and
you cannot use them as constants or variables or any other identifier names. All
the Python keywords contain lowercase letters only.

and exec not

as finally or

assert for pass

break from print

8|P ag e Python Programming (KNC-402)


class global raise

continue if return

def import try

del in while

elif is with

else lambda yield

except

Lines and Indentation


Python does not use braces({}) to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which is
rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount. For example –

if True:

print ("True")

else:

print ("False")

However, the following block generates an error −

if True:

print ("Answer")

print ("True")

else:

print ("Answer")

print ("False")

9|P ag e Python Programming (KNC-402)


Multi-Line Statements
Statements in Python typically end with a new line. Python, however, allows the use of
the line continuation character (\) to denote that the line should continue. For example

total = item_one + \

item_two + \

item_three

The statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

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

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

# First comment

print ("Hello, Python!") # second comment

For multiple-line commenting feature. You have to comment each line individually as
follows −

# This is a comment.

# This is a comment, too.

# This is a comment, too.


10 | P a g e Python Programming (KNC-402)
# I said that already.

Or by three times double quotes (“””) or single quotes (‘’‘)

“””This is a comment.

This is a comment, too.

This is a comment, too.

I said that already.”””

‘’’This is a comment.

This is a comment, too.

This is a comment, too.

I said that already.’’’

Variables
Variables are nothing but reserved memory locations to store values. It means that
when you create a variable, you reserve some space in the memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data
types to the variables, you can store integers, decimals or characters in these
variables.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal
sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand
to the right of the = operator is the value stored in the variable. For example –

-----------------------------------
>>> a=10
>>> a
10
>>> b=20.58
>>> b
20.58
>>> c='PYTHON'
>>> c
' PYTHON '
---------------------------------

11 | P a g e Python Programming (KNC-402)


Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example –

a = b = c = 1

Here, an integer object is created with the value 1, and all the three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables. For example −

a, b, c = 1, 2.5, "Viraat"

Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "ITS" is assigned to the variable c.

Standard Data Types


Python has various standard data types that are used to define the operations possible
on them and the storage method for each of them.
Python has five standard data types −
1) Numbers
2) String
3) List
4) Tuple
5) Dictionary

Python Numbers
Number data types store numeric values. Number objects are created when you assign
a value to them. For example −

a = 10
b = 20

You can also delete the reference to a number object by using the del statement. You
can delete a single object or multiple objects by using the del statement.
For example −

del a
del a, b

Python supports three different numerical types −


1) int (signed integers)
2) float (floating point real values)

3) complex (complex numbers)

12 | P a g e Python Programming (KNC-402)


All integers in Python3 are represented as long integers. Hence, there is no separate
number type as long.

Examples
Here are some examples of numbers −

int float complex

10 0.05 3.14j

100 15.20 45.j

-786 -21.9 9.322e-36j

A complex number consists of an ordered pair of real floating-point numbers denoted


by x + yj, where x and y are real numbers and j is the imaginary unit.

Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way to end -1.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −

str = 'Computer Science’

print (str) # Prints complete string

print (str[0]) # Prints first character of the string

print (str[2:5]) # Prints characters starting from 3rd to 5th

print (str[2:]) # Prints string starting from 3rd character

print (str * 2) # Prints string two times

print (str + "Engineering") # Prints concatenated string

This will produce the following result –

---------------------------------------------------

>>> str='Computer Science'

13 | P a g e Python Programming (KNC-402)


>>> print(str)
Computer Science
>>> print(str[0])
C
>>> print(str[2:5])
mpu
>>> print(str[2:])
mputer Science
>>> print(str*2)
Computer ScienceComputer Science
>>> print(str+"Engineering")
Computer ScienceEngineering

------------------------------------------------------------------------------

Python Lists
Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To
some extent, lists are similar to arrays in C. One of the differences between
them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator. For example −

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

newlist = [123, 'john']

print (list) # Prints complete list

print (list[0]) # Prints first element of the list

print (list[1:3]) # Prints elements starting from 2nd till 3rd

print (list[2:]) # Prints elements starting from 3rd element

print (newlist * 2) # Prints list two times

print (list + newlist) # Prints concatenated lists

This produces the following result −

['abcd', 786, 2.23, 'john', 70.2]


14 | P a g e Python Programming (KNC-402)
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Add Elements to a List-


One can use the method insert, append and extend to add elements to a List.
The insert method expects an index and the value to be inserted.
>>> List.insert(0,"Yes")

Deletion in List-
>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a=[1,2,3]
>>> del a[1]
>>> a
[1, 3]
>>> a= [1,2,3]
>>> a.pop(1)
2
>>> a
[1, 3]
>>>
 remove removes the first matching value, not a specific index:
 del removes the item at a specific index:
 and pop removes the item at a specific index and returns it.

Built-in List Functions


S.No. Function & Description

cmp(list1, list2)
1
No longer available in Python 3.

15 | P a g e Python Programming (KNC-402)


len(list)
2
Gives the total length of the list.

max(list)
3
Returns item from the list with max value.

min(list)
4
Returns item from the list with min value.

list(seq)
5 Converts a tuple into list.

S.No. Methods & Description

list.append(obj)
1
Appends object obj to list

list.count(obj)
2
Returns count of how many times obj occurs in list

list.extend(seq)
3
Appends the contents of seq to list

list.index(obj)
4
Returns the lowest index in list that obj appears

list.insert(index, obj)
5
Inserts object obj into list at offset index

list.pop(obj = list[-1])
6
Removes and returns last object or obj from list

list.remove(obj)
7
Removes object obj from list

16 | P a g e Python Programming (KNC-402)


list.reverse()
8
Reverses objects of list in place

list.sort([func])
9
Sorts objects of list, use compare func if given

Python Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences, just
like lists. The main difference between the tuples and the lists is that the
tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists
use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally,


you can put these comma-separated values between parentheses also.

tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed
within parenthesis.

The main difference between lists and tuples are − Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses
( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For
example −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

newtuple = (123, 'john')

print (tuple) # Prints complete tuple

print (tuple[0]) # Prints first element of the tuple

print (tuple[1:3]) # Prints elements starting from 2nd till 3rd

print (tuple[2:]) # Prints elements starting from 3rd element

print (newtuple * 2) # Prints tuple two times

print (tuple + newtuple) # Prints concatenated tuple

This produces the following result −

('abcd', 786, 2.23, 'john', 70.2)

17 | P a g e Python Programming (KNC-402)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

tuple[2] = 1000 # Invalid syntax with tuple

list[2] = 1000 # Valid syntax with list

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrong
with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement.

Basic Tuples Operations


Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in
the previous chapter.

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1,2,3) : print (x, end = ' ') 123 Iteration

Built-in Tuple Functions

18 | P a g e Python Programming (KNC-402)


Python includes the following tuple functions −

S.No. Function & Description

cmp(tuple1, tuple2)
1
Compares elements of both tuples.

len(tuple)
2
Gives the total length of the tuple.

max(tuple)
3 Returns item from the tuple with max value.

min(tuple)
4
Returns item from the tuple with min value.

tuple(seq)
5
Converts a list into tuple.

Python Dictionary
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary without
any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary
can be of any type, but the keys must be of an immutable data type such as strings,
numbers, or tuples.
For example −

dict = {}

dict['one'] = "This is one"

dict[2] = "This is two"

newdict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key

print (dict[2]) # Prints value for 2 key

19 | P a g e Python Programming (KNC-402)


print (newdict) # Prints complete dictionary

print (newdict.keys()) # Prints all the keys

print (newdict.values()) # Prints all the values

This produces the following result −

This is one
This is two
{'name': 'john', 'dept': 'sales', 'code': 6734}
dict_keys(['name', 'dept', 'code'])
dict_values(['john', 'sales', 6734])

Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry.

Delete Dictionary Elements


You can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name'] # remove entry with key 'Name'

dict.clear() # remove all entries in dict

del dict # delete entire dictionary

print ("dict['Age']: ", dict['Age'])

print ("dict['School']: ", dict['School'])

Properties of Dictionary Keys


Dictionary values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys –

(a) More than one entry per key is not allowed. This means no duplicate key is
allowed. When duplicate keys are encountered during assignment, the last assignment
wins. For example −

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}

print ("dict['Name']: ", dict['Name'])

20 | P a g e Python Programming (KNC-402)


When the above code is executed, it produces the following result −
dict['Name']: Manni

(b) Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.

Built-in Dictionary Functions and Methods


Python includes the following dictionary functions −

S.No. Function & Description

cmp(dict1, dict2)
1
No longer available in Python 3.

len(dict)
2 Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.

str(dict)
3 Produces a printable string representation of a dictionary

type(variable)
4 Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.

Python includes the following dictionary methods −

S.No. Method & Description

dict.clear()
1
Removes all elements of dictionary dict

dict.items()
2 Returns a list of dict's (key, value) tuple pairs

dict.keys()
3 Returns list of dictionary dict's keys

21 | P a g e Python Programming (KNC-402)


dict.update(dict2)
4 Adds dictionary dict2's key-values pairs to dict

dict.values()
5 Returns list of dictionary dict's values

Eval- In simple terms, the eval() method runs the python code (which is passed as an
argument) within the program.
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1

Data Type Conversion

When a description of an arithmetic operator below uses the phrase “the numeric
arguments are converted to a common type,” this means that the operator
implementation for built-in types works as follows:

 If either argument is a complex number, the other is converted to


complex;
 otherwise, if either argument is a floating point number, the other is
converted to floating point;
 otherwise, both must be integers and no conversion is necessary.

Some additional rules apply for certain operators (e.g., a string as a left argument to
the ‘%’ operator). Extensions must define their own conversion behavior.

Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type-names as a function.

There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.

S.No. Function & Description

int(x)
1
Converts x to an integer.

float(x)
2
Converts x to a floating-point number.

complex(real [,imag])
3
Creates a complex number.

22 | P a g e Python Programming (KNC-402)


str(x)
4
Converts object x to a string representation.

eval(str)
5
Evaluates a string and returns an object.

tuple(s)
6
Converts s to a tuple.

list(s)
7
Converts s to a list.

set(s)
8
Converts s to a set.

dict(d)
9
Creates a dictionary. d must be a sequence of (key,value) tuples.

chr(x)
10
Converts an integer to a character.

ord(x)
11
Converts a single character to its integer value.

hex(x)
12
Converts an integer to a hexadecimal string.

oct(x)
13
Converts an integer to an octal string.

Expressions
an expression in python is a block of code that produces a result or value upon
evaluation. A simple example of an expression is 6+3. An expression can be broken
doun into operators and operands. Operators are symbols which help the user or
command computer to perform mathematical or logical operations.

Operators
Operators are the constructs, which can manipulate the value of operands. Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called the operands and + is called the
operator.

Types of Operator
Python language supports the following types of operators −
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

23 | P a g e Python Programming (KNC-402)


Python Arithmetic Operators
Assume variable a holds the value 10 and variable b holds the value 21, then

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 31

Subtracts right hand operand from left


- Subtraction a – b = -11
hand operand.

Multiplies values on either side of the


* Multiplication a * b = 210
operator

Divides left hand operand by right hand


/ Division b / a = 2.1
operand

Divides left hand operand by right hand


% Modulus b%a=1
operand and returns remainder

Performs exponential (power) calculation on a**b =10 to the


** Exponent
operators power 20

Floor Division - The division of operands


where the result is the quotient in which 9//2 = 4 and
the digits after the decimal point are 9.0//2.0 = 4.0, -
//
removed. But if one of the operands is 11//3 = -4, -
negative, the result is floored, i.e., rounded 11.0//3 = -4.0
away from zero (towards negative infinity):

Python Comparison Operators


These operators compare the values on either side of them and decide the relation
among them. They are also called Relational operators.

Assume variable a holds the value 10 and variable b holds the value 20, then

Operator Description Example

If the values of two operands are equal, then the (a == b) is not


==
condition becomes true. true.

If values of two operands are not equal, then


!= (a!= b) is true.
condition becomes true.

If the value of left operand is greater than the


(a > b) is not
> value of right operand, then condition becomes
true.
true.

If the value of left operand is less than the value


< (a < b) is true.
of right operand, then condition becomes true.

24 | P a g e Python Programming (KNC-402)


If the value of left operand is greater than or
(a >= b) is not
>= equal to the value of right operand, then condition
true.
becomes true.

If the value of left operand is less than or equal to


(a <= b) is
<= the value of right operand, then condition
true.
becomes true.

Python Assignment Operators


Assume variable a holds the value 10 and variable b holds the value 20, then

Operator Description Example

Assigns values from right side c = a + b assigns value of


=
operands to left side operand a + b into c

It adds right operand to the


c += a is equivalent to c =
+= Add AND left operand and assign the
c+a
result to left operand

It subtracts right operand


from the left operand and c -= a is equivalent to c =
-= Subtract AND
assign the result to left c-a
operand

It multiplies right operand


with the left operand and c *= a is equivalent to c =
*= Multiply AND
assign the result to left c*a
operand

It divides left operand with the c /= a is equivalent to c =


/= Divide AND right operand and assign the c / ac /= a is equivalent to
result to left operand c=c/a

It takes modulus using two


c %= a is equivalent to c
%= Modulus AND operands and assign the result
=c%a
to left operand

Performs exponential (power)


calculation on operators and c **= a is equivalent to c
**= Exponent AND
assign value to the left = c ** a
operand

It performs floor division on


c //= a is equivalent to c =
//= Floor Division operators and assign value to
c // a
the left operand

25 | P a g e Python Programming (KNC-402)


Python Bitwise Operators

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60;
and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

Python's built-in function bin() can be used to obtain binary representation of an


integer number.
The following Bitwise operators are supported by Python language –

Operator Description Example

Operator copies a bit, to the


(a & b) (means 0000
& Binary AND result, if it exists in both
1100)
operands

It copies a bit, if it exists in (a | b) = 61 (means


| Binary OR
either operand. 0011 1101)

It copies the bit, if it is set in (a ^ b) = 49 (means


^ Binary XOR
one operand but not both. 0011 0001)

(~a ) = -61 (means


1100 0011 in 2's
~ Binary Ones It is unary and has the effect of
complement form
Complement 'flipping' bits.
due to a signed
binary number.

The left operand's value is


moved left by the number of a << = 240 (means
<< Binary Left Shift
bits specified by the right 1111 0000)
operand.

The left operand's value is


moved right by the number of a >> = 15 (means
>> Binary Right Shift
bits specified by the right 0000 1111)
operand.

Python Logical Operators

26 | P a g e Python Programming (KNC-402)


The following logical operators are supported by Python language. Assume
variable a holds True and variable b holds False then −

Operator Description Example

and Logical If both the operands are true then condition (a and b) is
AND becomes true. False.

If any of the two operands are non-zero then (a or b) is


or Logical OR
condition becomes true. True.

Used to reverse the logical state of its operand. not(a and b)


not Logical NOT
is True.

Python Membership Operators

Python’s membership operators test for membership in a sequence, such as strings,


lists, or tuples. There are two membership operators as explained below –

Operator Description Example

Evaluates to true if it finds a variable in x in y, here in results


the specified sequence and false in a 1 if x is a
In
otherwise. member of sequence
y.

Evaluates to true if it does not finds a x not in y, here not in


variable in the specified sequence and results in a 1 if x is
not in
false otherwise. not a member of
sequence y.

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two
Identity operators as explained below −

Operator Description Example

Evaluates to true if the variables on


x is y, here is results in 1
Is either side of the operator point to the
if id(x) equals id(y).
same object and false otherwise.

Evaluates to false if the variables on x is not y, here is not


is not either side of the operator point to the results in 1 if id(x) is not
same object and true otherwise. equal to id(y).

Python Operators Precedence

27 | P a g e Python Programming (KNC-402)


The following table lists all operators from highest precedence to the lowest.

S.No. Operator & Description

**
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

is is not
11
Identity operators

in not in
12
Membership operators

not or and
13
Logical operators

NOTE- Exponentiation and Assignment operations are right associative.

Use of some built-in functions-


28 | P a g e Python Programming (KNC-402)
1. help()
>>> help()
Welcome to Python 3.4's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.4/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name or
summary contain a given string such as "spam", type "modules spam".
help> quit

>>>

2. id()
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.). For
example—
------------------------------
>>> a=10
>>> id(a)
1684853344
>>> id(10)
1684853344
>>>
--------------------------------------
3. chr()
Return a Unicode string of one character with ordinal i. For example—
----------------------------
>>> chr(8976)
'⌐'
>>> chr(97)
'a'
----------------------------------
4. ord()
Return the integer ordinal of a one-character string.
Given a string representing one Unicode character, return an integer representing
the Unicode code point of that character. For example, ord('a') returns the
integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr(). For
example--
---------------------------------------
>>> ord('A')
65
>>> ord('@')
64
-----------------------------

5. type()

29 | P a g e Python Programming (KNC-402)


With one argument, return the type of an object.
---------------------
>>> a=10
>>> type(a)
<class 'int'>
>>> name="ABC"
>>> type(name)
<class 'str'>
----------------------
Size of a variable-
>>> from sys import getsizeof
>>> a=10
>>> getsizeof(a)
14 bytes
>>> a = 2**1000
>>> getsizeof(a)
146 bytes

Operator Precedence

Operator precedence determines which operator is performed first in an expression with


more than one operators with different precedence.
For example: Solve

10 + 20 * 30

Operators Associativity is used when two operators of same precedence appear in an


expression. Associativity can be either Left to Right or Right to Left.

For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right,
so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Associativity is only used when there are two or more operators of same precedence.
The point to note is associativity doesn’t define the order in which operands of a single
operator are evaluated. For example, consider the following program, associativity of
the + operator is left to right, but it doesn’t mean f1() is always called before f2(). The
output of the following program is in-fact compiler dependent.

Associativity of Python Operators

 We can see in the above table that more than one operator exists in the same
group. These operators have the same precedence.
 When two operators have the same precedence, associativity helps to determine
which the order of operations.
 Associativity is the order in which an expression is evaluated that has multiple
operator of the same precedence. Almost all the operators have left-to-right
associativity.
 Exponent operator ** has right-to-left associativity in Python.

30 | P a g e Python Programming (KNC-402)


How to create and save python program/files
Open IDLE(Python GUI)--shell will open.
File-- New File
Write code in file
File-- Save or Ctrl+S--------to save a file

File is saved in C:\python34\filename.py


How to run python program/files
In program file, go to Run- Check module(Will show error, if any)
Then Run- Run Module or press F5

How to run a saved python program/files


exec(open("C:\\python34\\aa.py").read())

31 | P a g e Python Programming (KNC-402)


NOTE-Make programs for Simple Interest calculation and area of a circle.

1.Program to calculate Simple Interest

1. P = float(input("Enter the principal amount : "))


2. N = float(input("Enter the number of years : "))
3. R = float(input("Enter the rate of interest : "))
4. SI = (P * N * R)/100
5. print("Simple interest : ,SI)

2.Program to calculate Area of circle

1. PI = 3.14
2. r = float(input('Enter the radius of the circle :'))
3. area = PI * r * r
4. print("Area of the circle is : ",area)

32 | P a g e Python Programming (KNC-402)

You might also like