Python Notes (KNC-402) UNIT-1
Python Notes (KNC-402) 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.
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:
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.
>>>
>>>
>>> 4+5
----------------------------
-------------------------------
>>>print(“Hello, Students”)
--------------------------------------------------
>>> name
'Sachin Tendulkar'
>>> print(name)
Sachin Tendulkar
---------------------------------------------
>>> c=a+b
----------------------------------
>>> c=a+b
>>> c
'1020'
>>> print(c)
1020
----------------------------------------
>>> area=3.14*radius*radius
----------------------------------------------------------------------------------
>>> SI=(p*r*t)/100
----------------------------------------------------------------
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.
as finally or
continue if return
del in while
elif is with
except
if True:
print ("True")
else:
print ("False")
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")
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 −
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'
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
For multiple-line commenting feature. You have to comment each line individually as
follows −
# This is a comment.
“””This is a comment.
‘’’This is a comment.
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.
-----------------------------------
>>> a=10
>>> a
10
>>> b=20.58
>>> b
20.58
>>> c='PYTHON'
>>> c
' PYTHON '
---------------------------------
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.
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
Examples
Here are some examples of numbers −
10 0.05 3.14j
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 −
---------------------------------------------------
------------------------------------------------------------------------------
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 −
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.
cmp(list1, list2)
1
No longer available in Python 3.
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.
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
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.
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 −
The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists −
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 = {}
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.
(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 −
(b) Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.
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.
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
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
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:
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.
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.
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
Assume variable a holds the value 10 and variable b holds the value 20, then
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
and Logical If both the operands are true then condition (a and b) is
AND becomes true. False.
Identity operators compare the memory locations of two objects. There are two
Identity operators as explained below −
**
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'
<> == !=
9
Equality operators
= %= /= //= -= += *= **=
10
Assignment operators
is is not
11
Identity operators
in not in
12
Membership operators
not or and
13
Logical operators
>>>
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()
Operator Precedence
10 + 20 * 30
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.
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.
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)