UNIT1
UNIT1
Features of Python
• Simple and Easy to Learn
• Versatile
• Free and Open Source
• High-level Language
• Interactive
• Portable
• Object Oriented
• Interpreted
• Dynamic
• Extensible
• Embeddable
• Extensive
• Easy maintenance
• Secure
• Robust
• Multi-threaded
• Garbage Collection
Simple Easy to Learn: Python is a simple and small programming language. When we read
Python program, we can feel like reading English statements. A python program is clearly
defined and easily readable. The syntaxes are very simple and only 30+ keywords are
available. When compared with other languages, we can write programs with very a smaller
number of lines. Hence more readability and simplicity.
Versatile: Python supports development of a wide range of applications ranging from simple
text processing to WWW browsers to games.
Free and Open Source: We can use Python software without any licence, and it is
freeware. Its source code is open, so that we can customize based on our requirement.
High-level Language: Python is high level programming language and hence it is a
programmer friendly language. Being a programmer, we are not required to concentrate low
level activities like memory management and security etc. They just need to concentrate on
writing solutions of the current problem at hand.
Interactive: Programs in python work in interactive mode which allows interactive testing
and debugging of pieces of code. Programmers can easily interact with the interpreter directly
at the Python Prompt to write their programs.
Portable: Python programs are portable. i.e. we can migrate from one platform to another
platform very easily. Python programs will provide same results on any platform. The
programs work on any of the operating systems like
linux,unix,Macintosh,Solaris,OS/2,PalmOS etc. With out requiring any changes.
Both Procedure Oriented and Object Oriented: Python language supports both
Procedure oriented (like C, pascal etc) and object oriented (like C++, Java) features. While
object-oriented technique encapsulates data and functionalities within objects, procedure-
oriented technique on the other hand, builds the program around procedures or functions
which are reusable pieces of program. Hence, we can get benefits of both like security and
reusability etc.
Interpreted: We are not required to compile Python programs explicitly. Internally Python
interpreter will take care that compilation. If compilation fails interpreter raised syntax errors.
Once compilation success then PVM (Python Virtual Machine) is responsible to execute.
Dynamic: In Python we are not required to declare type for variables. Whenever we are
assigning the value, based on value, type will be allocated automatically. Hence Python is
considered as dynamically typed language. But Java, C etc are Statically Typed Languages
because we have to provide type at the beginning only. This dynamic typing nature will
provide more flexibility to the programmer.
Extensible: Since python is an open-source software anyone can add low level modules to
the Python Interpreter. These modules enable programmer to add to or customize their tools
to work more efficiently. Moreover, if you want a piece of code not to be accessible for
everyone, then you can even code that part of your program in C or C++ and then use them
from your Python program.
Embedded: We can use Python programs in any other language programs.
i.e. we can embedded Python programs anywhere.
Extensive Library: Python has a rich inbuilt library. Being a programmer, we can use this
library directly and we are not responsible to implement the functionality.
Easy maintenance: code written in python is easy to maintain.
Secure: The python Programming is secure from tampering. Modules can be distributed to
prevent altering the source code.
Robust: Python programmers cannot manipulate memory directly.Moreover,errors are raised
as exceptions that can be catch and handled by the program code. For every syntactical
mistake an easy and simple interpret message is displayed.
Multi-threaded: Python supports multi-threading, that is executing more than one process of
a program simultaneously.
Garbage Collection: the Python run-time environment handles garbage collection of all
python objects. For this reference counter is maintained to assure that no object that is
currently in use is deleted. An object that is no longer used or has gone out of scope are
eligible for garbage collection. This frees programmers from the worry of memory leak and
dangling reference problems.
Limitations of Python:
Parallel processing can be done in Python but not as elegantly as done in some other
languages (like JavaScript and Go Lang).
Being an interpreted language, Python is slow as compared to C/C++. Python is not a
very good choice for those developing a high-graphic 3d game that takes up a lot of
CPU.
As compared to other languages, Python is evolving continuously and there is little
substantial documentation available for the language.
As of now, there are few users of Python as compared to those using C, C++ or Java.
It lacks true multiprocessor support.
It has very limited commercial support points.
Python is slower than C or C++ when it comes to computation heavy tasks and
desktop applications.
It is difficult to pack up a big Python application into a single executable file. This
makes it difficult to distribute Python to non-technical.
History of Python
• Python was developed by Guido van Rossum in the late 1980’s and early 1990’s at
the National Research Institute for Mathematics and Computer Science in the
Netherlands.
• It has been derived from many languages like ABC, Modula-3, C, C++, Algol-68,
Smalltalk, UNIX Shell and other scripting languages.
• Its version 1.0 was released in 1991, which introduced several new functional
programming tools. While version 2.0 included list comprehensions and was released
in 2000 by the Be Open Python Labs team.
• Python 2.7 is supported till 2020 and concentrates further development of Python 3.
Currently 3.9.4 is readily available. The newer versions have better features like
flexible string representations, etc.
• Although Python is copyrighted, its source code is available under the GNU General
Public License (GPL). Python is currently maintained by a core development team at
the institute which is directed by Guido van Rossum. These days, from data to web
development, Python has emerged as a very powerful and popular language.
Python versions:
Compiled programs
Interpreted programs execute
execute faster as
Speed slower as compared to
compared to interpreted
compiled programs.
programs.
In C, the Programmer
Memory- garbage collector for memory has to do memory
management management. management on their
own.
Python is a General-Purpose
Applications C is generally used for
programming language. hardware related
applications.
PyCharm installation
PyCharm is a cross-platform IDE, and hence it can be installed on a variety of
the operating systems.
Windows
Installing PyCharm on Windows is very simple. To install PyCharm on
Windows operating system, visit the
link https://www.jetbrains.com/pycharm/download/download-thanks.html?
platform=windows to download the executable installer.
Double click the installer (.exe) file and install PyCharm by clicking next at
each step.
To create a first program to Pycharm follows the following step.
Step - 1. Open Pycharm editor. Click on "Create New Project" option to create
new project.
Step - 3. Click on "File" menu and select "New". By clicking "New" option it
will show various file formats. Select the "Python File".
Step - 4. Now type the name of the Python file and click on "OK". We have
written the "FirstProgram".
Step - 5. Now type the first program - print("Hello World") then click on the
"Run" menu to run program.
Numbers refers to a numeric value. You can use four types of numbers in Python program-
integers, long integers, floating point and complex numbers.
• Numbers like 5 or other whole numbers are referred to as integers. Bigger whole numbers
are called long integers. For example, 535633629843L is a long integer.
• Numbers like are 3.23 and 91.5E-2 are termed as floating point numbers.
• Numbers of a + bi form (like -3 + 7i) are complex numbers.
Types of Integer Literals:
There are three types of integer literals -decimal,octal and hexa decimal integer literals
Decimal Integer Literal:
Any integer literal that does not start with a zero is a decimal integer literal.
Example:+17,-26,1234,-89072
Octal Integer Literal:
Any integer literal that starts with digit zero followed by letter o is treated as an octal integer
literal in python
Example:0o12,-0o12,0o7654,0o1789
Hexadecimal Integer Literal:
Any integer literal that starts with digit zero followed by letter x is treated as an octal integer
literal in python.
Example:0x1234,0xA7B6F.
Built-in Format Function()
Any Floating -point value may contain an orbitary number of decimal places,so it is always
recommended to use the built-in-format() function to produce a string vrsion of a number
with a specific number of decimal places.
Examples:
#without using format
>>> float(16/(float(3))) #using format
5.3333333333 >>> float(16/(float(3)))
‘5.33’
>>> format(3**50,’.5e’)
‘7.17898e+23’
>>>format(123456,’ ,‘)
‘123,456’
Simple operations on Numbers:
Exponentiation:
Types of Literals
Strings:
A string is a group of characters.
• Using Single Quotes ('): For example, a string can be written as 'HELLO'.
• Using Double Quotes ("): Strings in double quotes are exactly same as those in single
quotes. Therefore, 'HELLO' is same as "HELLO".
• Using Triple Quotes (''' '''): You can specify multi-line strings using triple quotes. You can
use as many single quotes and double quotes as
Examples:
s1='CVR '
s1="CVR”
By using single quotes or double quotes we cannot represent multi line string literals.
s1="CVR
college of Engineering”
For this requirement we should go for triple single quotes(''') or triple double quotes(""")
We can also use triple quotes to use single quote or double quote in our String.
Escape Sequences
Some characters (like ", \) cannot be directly included in a string. Such characters must
be escaped by placing a backslash before them.
>>> print(“Today is 15th August. \n India became independent on this day.”)
Today is 15th August.
India became independent on this day.
>>>print(“Hello All \t Welcome to the world of python”)
Hello All.
Welcome to the world of python.
Raw Strings
If you want to specify a string that should not handle any escape sequences and want to
display exactly as specified, then you need to specify that string as a raw string. A raw string
is specified by prefixing r or R to the string.
Example:
String Formatting:
format(value,format_specifier)
examples:
>>> format(‘Hello’,’<30’)
‘ Hello’
>>>format(‘Hello’,’>30’)
‘ Hello’
>>>format(‘Hello’,’^30’)
‘Hello ‘
Slice a String:
You can extract subsets of strings by using the slice operator.
You need to specify index or the range of characters to be extracted.
The index of the first character is 0 and the index of the last character is n-1.
slice means a piece [ ] operator is called slice operator, which can be used to retrieve parts of
String.
In Python Strings follows zero based index.
The index can be either +ve or -ve.
+ve index means forward direction from Left to Right
-ve index means backward direction from Right to Left
P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
The syntax of slice operator is[start:end:stride]
>>> s[0]
'C'
>>> s[1]
'V'
>>> s[-1]
'R’
>>> s[1:40]
'VR'
>>> s[1:]
'VR'
>>> s[:4]
'CVR'
>>> s[:]
'CVR'
>>> s*3
'CVRCVRCVR’
>>>len(s)
2
Example2:
str=’Python is Easy!!!’
Print(str)
Print(str[0])
Print(str[3:9])
Print(str[4:])
Print(str[-1])
Print(str[:5])
Print(str*2)
Print(str+”ISN’T IT?”);
Output:
Python is Easy !!!
P
hon is
on is Easy!!!
!
Pytho
Python is Easy !!!Python is Easy !!!
Python is Easy !!!ISN’T IT?
Variables and Identifiers
Variable means its value can vary. You can store any piece of information in a variable.
Variables are nothing but just parts of your computer’s memory where information is stored.
To be identified easily, each variable is given an appropriate name.
Identifiers are names given to identify something. This something can be a variable, function,
class, module or other object. For naming any identifier, there are some basic rules like:
• The first character of an identifier must be an underscore ('_') or a letter (upper or
lowercase).
• The rest of the identifier name can be underscores ('_'), letters (upper or lowercase), or
digits (0-9).
• Identifier names are case-sensitive. For example, myvar and myVar are not the same.
• Punctuation characters such as @, $, and % are not allowed within identifiers.
Examples of valid identifier names are sum, __my_var, num1, r, var_20, First, etc.
Examples of invalid identifier names are 1num, my-var, %check, Basic Sal, H#R&A, etc.
Variables and Identifiers
Variable means its value can vary. You can store any piece of information in a variable.
Variables are nothing but just parts of your computer’s memory where information is stored.
To be identified easily, each variable is given an appropriate name.
Identifiers are names given to identify something. This something can be a variable, function,
class, module or other object. For naming any identifier, there are some basic rules like:
• The first character of an identifier must be an underscore ('_') or a letter (upper or
lowercase).
• The rest of the identifier name can be underscores ('_'), letters (upper or lowercase), or
digits (0-9).
• Identifier names are case-sensitive. For example, myvar and myVar are not the same.
• Punctuation characters such as @, $, and % are not allowed within identifiers.
Examples of valid identifier names are sum, __my_var, num1, r, var_20, First, etc.
Examples of invalid identifier names are 1num, my-var, %check, Basic Sal, H#R&A, etc.
Assigning or Initializing Values to Variables
In Python, programmers need not explicitly declare variables to reserve memory space. The
declaration is done automatically when a value is assigned to the variable using the equal sign
(=). The operand on the left side of equal sign is the name of the variable and the operand on
its right side is the value to be stored in that variable
Example:
Comments
Comments are the non-executable statements in a program. They are just added to describe
the statements in the program code. Comments make the program easily readable and
understandable by the programmer as well as other users who are seeing the code. The
interpreter simply ignores the comments.
In Python, a hash sign (#) that is not inside a string literal begins a comment. All characters
following the # and up to the end of the line are part of the comment
Example:
Indentation
Whitespace at the beginning of the line is called indentation. These whitespaces or the
indentation are very important in Python. In a Python program, the leading whitespace
including spaces and tabs at the beginning of the logical line determines the indentation level
of that logical line.
Example;
Arithmetic Operators
Example:
a=10
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a%b=',a%b)
print('a**b=',a**b)
output:
a+b= 12
a-b= 8
a*b= 20
a/b= 5.0
a//b= 5
a%b= 0
a**b= 10
Comparison Operators
Example:
a=10
b=20
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
print("a <= b is ",a<=b)
output:
a > b is False
a >= b is False
a < b is True
a <= b is True
Example2:
print(True > True)
print(True >= True)
print(10 > True)
print(False > True)
print(10 > 'cvr')
Output:
False
True
True
False
Traceback (most recent call last):
File "C:/Users/ACER/Desktop/python program/relation2.py", line 5, in <module>
print(10 > 'cvr')
TypeError: '>' not supported between instances of 'int' and 'str'
Ternary Operator:
Eg 1: a,b=10,20
print(x) #30
Read two numbers from the keyboard and print minimum value
output:
Enter First Number:10
Enter Second Number:20
minimum value 10
Program for minimum of 3 numbers
These operators are applicable only for int and boolean types. By mistake if we are trying to
apply for any other type then we will get Error.
Examples:
>>> print(4&5)
4
>>> print(10.5&5.6)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
print(10.5&5.6)
TypeError: unsupported operand type(s) for &: 'float' and 'float'
>>> print(True&True)
True
& ==> If both bits are 1 then only result is 1 otherwise result is 0
| ==> If atleast one bit is 1 then result is 1 otherwise result is 0
^ ==>If bits are different then only result is 1 otherwise result is 0
~ ==>bitwise complement operator 1==>0 & 0==>1
<< ==>Bitwise Left shift
>> ==>Bitwise Right Shift
Examples:
>>> print(True&True)
True
>>> print(4|5)
5
>>> print(4^ 5)
1
>>> print(~5)
-6
Shift Operators:
Python supports two bitwise shift operators. They are shift left (<<) and shift right (>>).
These operations are used to shift bits to the left or to the right. The syntax for a shift
operation can be given as follows:
Examples:
<< Left shift operator After shifting the empty cells we have to fill with zero
>>> print(10<<2)
40
>>> print(10>>2)
2
>> Right Shift operator After shifting the empty cells we have to fill with sign bit.( 0 for +ve
and 1 for -ve)
>>> print(10>>2)
2
Logical Operators
Logical AND (&&) operator is used to simultaneously evaluate two conditions or expressions
with relational operators. If expressions on both the sides (left and right side) of the logical
operator are true, then the whole expression is true. For example, If we have an expression
(a>b) && (b>c), then the whole expression is true only if both expressions are true. That is, if
b is greater than a and c.
Logical OR (||) operator is used to simultaneously evaluate two conditions or expressions
with relational operators. If one or both the expressions of the logical operator is true, then
the whole expression is true. For example, If we have an expression (a>b) || (b>c), then the
whole expression is true if either b is greater than a or b is greater than c.
Logical not (!) operator takes a single expression and negates the value of the expression.
Logical NOT produces a zero if the expression evaluates to a non-zero value and produces a
1 if the expression produces a zero. In other words, it just reverses the value of the
expression. For example, a = 10, b b = !a; Now, the value of b = 0. The value of a is not zero,
therefore, !a = 0. The value of !a is assigned to b, hence, the result.
and, or ,not We can apply for all types.
For boolean types behaviour:
and ==>If both arguments are True then only result is True
or ====>If atleast one arugemnt is True then result is True
not ==>complement
True and False ==>False
True or False ===>True
not False ==>True
For non-boolean types behaviour:
0 means False
non-zero means True
empty string is always treated as False
x and y: ==>if x is evaluates to false return x otherwise return y
Examples:
>>> 10 and 20
20
>>> 0 and 20
0
>>> 10 or 20
10
>>> 0 or 20
20
>>> not 10
False
>>> not 0
True
>>> "prash" and "cvr”
'cvr'
>>> " " and "prash"
'prash'
>>> "" and "prash"
''
>>> "prash" or ""
'prash'
>>> not ""
True
>>> not "prash" o/p:False
Membership and Identity Operators
Python supports two types of membership operators–in and not in. These operators, test for
membership in a sequence such as strings, lists, or tuples.
in Operator: The operator returns true if a variable is found in the specified sequence and
false otherwise. For example, a in nums returns 1, if a is a member of nums.
not in Operator: The operator returns true if a variable is not found in the specified sequence
and false otherwise. For example, a not in nums returns 1, if a is not a member of nums.
Identity Operators
is Operator: Returns true if operands or values on both sides of the operator point to the same
object and false otherwise. For example, if a is b returns 1, if id(a) is same as id(b).
is not Operator: Returns true if operands or values on both sides of the operator does not
point to the same object and false otherwise. For example, if a is not b returns 1, if id(a) is not
same as id(b).
Example1:
a=10
b=10
print(a is b)
x=True
y=True
print( x is y)
Example2:
list1=["one","two","three"]
list2=["one","two","three"]
print(id(list1))
print(id(list2))
print(list1 is list2)
print(list1 is not list2) print(list1 == list2)
Example3: Identity Operator
Expressions
An expression is any legal combination of symbols (like variables, constants and operators)
that represents a value. In Python, an expression must have at least one operand (variable or
constant) and can have one or more operators. On evaluating an expression, we get a value.
Operand is the value on which operator is applied.
Constant Expressions: One that involves only constants. Example: 8 + 9 – 2
Integral Expressions: One that produces an integer result after evaluating the expression.
Example:
a = 10
• Floating Point Expressions: One that produces floating point results. Example: a * b / 2
• Relational Expressions: One that returns either true or false value. Example: c = a>b
• Logical Expressions: One that combines two or more relational expressions and returns a
value as True or False. Example: a>b && y! = 0
• Bitwise Expressions: One that manipulates data at bit level. Example: x = y&z
• Assignment Expressions: One that assigns a value to a variable. Example: c = a + b or c =
10
Lists
Lists are the most versatile data type of Python language. A list consists of items separated
by commas and enclosed within square brackets. The values stored in a list are accessed
using indexes. The index of the first element being 0 and n-1 as that of the last element,
where n is the total number of elements in the list. Like strings, you can also use the slice,
concatenation, and repetition operations on lists.
Example:
Tuples
A tuple is similar to the list as it also consists of a number of values separated by commas and
enclosed within parentheses. The main difference between lists and tuples is that you can
change the values in a list but not in a tuple. This means that while tuple is a read only data
type, the list is not.
Example:
Dictionary
Python’s dictionaries stores data in key-value pairs. The key values are usually strings and
value can be of any data type. The key value pairs are enclosed with curly braces ({ }). Each
key value pair separated from the other using a colon (:). To access any value in the
dictionary, you just need to specify its key in square braces ([]).Basically dictionaries are
used for fast retrieval of data
Example:
Type Conversion
In Python, it is just not possible to complete certain operations that involves different types of
data. For example, it is not possible to perform "2" + 4 since one operand is an integer and
the other is of string type
Example:
Type Casting vs Type Coercion
In the last slide, we have done explicit conversion of a value from one data type to another.
This is known as type casting.
However, in most of the programming languages including Python, there is an implicit
conversion of data types either during compilation or during run-time. This is also known
type coercion. For example, in an expression that has integer and floating point numbers (like
21 + 2.1 gives 23.1), the compiler will automatically convert the integer into floating point
number so that fractional part is not lost.
Example:
If-Else Statement
Example:
Nested if Statements :
A statement that contains other statements is called a compound statement. To perform more
complex checks, if statements can be nested, that is, can be placed one inside the other. In
such a case, the inner if statement is the statement part of the outer one. Nested if statements
are used to check if more than one conditions are satisfied.
Example:
num=int(input("enter any number from 0-30:"))
if(num>=0 and num<10):
print("it is in the range 0-10")
if(num>=10 and num<20):
print("it is in the range 10-20")
if(num>=20 and num<30):
print("it is the range 20-30")
If-elif-else Statement
Python supports if-elif-else statements to test additional conditions apart from the initial
test expression. The if-elif-else construct works in the same way as a usual if-else
statement. If-elif-else construct is also known as nested-if construct.
Example:
While Loop
Example:
For Loop
For loop provides a mechanism to repeat a task until a particular condition is True. It is
usually known as a determinate or definite loop because the programmer knows exactly how
many times the loop will repeat.
The for...in statement is a looping statement used in Python to iterate over a sequence of
objects.
Example:
Range() Function
If range() function is given a single argument, it produces an object with values from 0 to
argument-1. For example: range(10) is equal to writing range(0, 10).
• If range() is called with two arguments, it produces values from the first to the second. For
example, range(0,10).
• If range() has three arguments then the third argument specifies the interval of the sequence
produced. In this case, the third argument must be an integer. For example, range(1,20,3).
Example:
Nested Loops
Python allows its users to have nested loops, that is, loops that can be placed inside other
loops. Although this feature will work with any loop like while loop as well as for loop.
A for loop can be used to control the number of times a particular set of statements will be
executed. Another outer loop could be used to control the number of times that a whole loop
is repeated.
Loops should be properly indented to identify which statements are contained within each for
statement.
Example:
Example:
The Pass Statement
Pass statement is used when a statement is required syntactically but no command or code
has to be executed. It specified a null operation or simply No Operation (NOP) statement.
Nothing happens when the pass statement is executed.
Difference between comment and pass statements In Python programming, pass is a null
statement. The difference between a comment and pass statement is that while the interpreter
ignores a comment entirely, pass is not ignored. Comment is not executed but pass statement
is executed but nothing happens.
Example:
The Else Statement Used With Loops
Unlike C and C++, in Python you can have the else statement associated with a loop
statements. If the else statement is used with a for loop, the else statement is executed when
the loop has completed iterating. But when used with the while loop, the else statement is
executed when the condition becomes false.
Example: