0% found this document useful (0 votes)
35 views49 pages

UNIT1

The document outlines the features, history, applications, and limitations of Python, highlighting its simplicity, versatility, and extensive libraries. It discusses Python's evolution from its inception by Guido van Rossum to its current versions, emphasizing its growing popularity in various fields including web development, scientific applications, and game development. Additionally, it compares Python with C, providing insights into their differences, and includes installation instructions for PyCharm and Python on Windows.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views49 pages

UNIT1

The document outlines the features, history, applications, and limitations of Python, highlighting its simplicity, versatility, and extensive libraries. It discusses Python's evolution from its inception by Guido van Rossum to its current versions, emphasizing its growing popularity in various fields including web development, scientific applications, and game development. Additionally, it compares Python with C, providing insights into their differences, and includes installation instructions for PyCharm and Python on Windows.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

UNIT-1

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:

• Python 1.0 was introduced in Jan 1994


• Python 2.0 was introduced in oct 2000.
• Python 3.0 was introduced in Dec 2008
• Python 3.6.3 ---2016
Applications of Python
• Embedded scripting language: Python is used as an embedded scripting language for
various testing/ building/ deployment/ monitoring frameworks, scientific apps, and quick
scripts.
• 3D Software: 3D software like Maya uses Python for automating small user tasks, or for
doing more complex integration such as talking to databases and asset management systems.
• Web development: Python is an easily extensible language that provides good integration
with database and other web standards.
GUI-based desktop applications: Simple syntax, modular architecture, rich text processing
tools and the ability to work on multiple operating systems makes Python a preferred choice
for developing desktop-based applications.
• Image processing and graphic design applications: Python is used to make 2D imaging
software such as Inkscape, GIMP, Paint Shop Pro and Scribus. It is also used to make 3D
animation packages, like Blender, 3ds Max, Cinema 4D, Houdini, Lightwave and Maya.
Scientific and computational applications: Features like high speed, productivity and
availability of tools, such as Scientific Python and Numeric Python, have made Python a
preferred language to perform computation and processing of scientific data. 3D modeling
software, such as FreeCAD, and finite element method software, like Abaqus, are coded in
Python.
Games: Python has various modules, libraries, and platforms that support development of
games. Games like Civilization-IV, Disney's Toontown Online, Vega Strike, etc. are coded
using Python.
• Enterprise and business applications: Simple and reliable syntax, modules and libraries,
extensibility, scalability together make Python a suitable coding language for customizing
larger applications. For example, Reddit which was originally written in Common Lips, was
rewritten in Python in 2005. A large part of Youtube code is also written in Python.
• Operating Systems: Python forms an integral part of Linux distributions.
The Future of Python:
• Python has a huge user base that is constantly growing. It is a stable language that is
going to stay for a long time.
• The strength of Python can be understood from the fact that this programming
language is the most preferred language of companies, such as Nokia, Google, and
YouTube, as well as NASA for its easy syntax.
• Python has become an ideal choice for programmers. Based on the data from Google
Trends and other relevant websites, Python is amongst the top five most preferred
languages in academics as well as in industry.
• Python is a high-speed dynamic language. It works well in applications like photo
development and has been embedded in programs such as GIMP and Paint Shop Pro.
• The best part is that more and more companies have started using Python for a
broader range of applications ranging from social networks, through automation to
science calculations.

• Difference between C and Python


Metrics Python C
C is a general-purpose,
Python is an interpreted, procedural computer
Introduction high-level, general-purpose programming language.
programming language.

Compiled programs
Interpreted programs execute
execute faster as
Speed slower as compared to
compared to interpreted
compiled programs.
programs.

It is easier to write a code in


Program syntax is harder
Usage Python as the number of lines
than Python.
is less comparatively.

There is no need to declare


the type of In C, the type of
variable. Variables are a variable must be
Declaration of untyped in Python. A given declared when it is
variables variable can be stuck on created, and only values
values of different types at of that type must be
different times during the assigned to it.
program execution
Error Debugging In C, error debugging is
difficult as it is a
Error debugging is simple. compiler dependent
This means it takes only one language. This means
in instruction at a time and that it takes the entire
compiles and executes source code, compiles it
simultaneously. Errors are and then shows all the
shown instantly and the
execution is stopped, at that errors.
instruction.

C does not support


Supports function renaming function renaming
Function renaming mechanism i.e, the same mechanism. This means
mechanism function can be used by two the same function cannot
different names. be used by two different
names.

Complexity The syntax of a C


Syntax of Python programs is
program is harder than
easy to learn, write and read.
Python.

Python uses an automatic

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.

Built-in functions Python has a large library of C has a limited number


built-in functions. of built-in functions.

Implementing Data Implementing data


Gives ease of implementing
Structures structures requires its
data structures with built-in
functions to be explicitly
insert, append functions.
implemented
No pointers functionality Pointers are available in
Pointers
available in Python. C.

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 - 2. Select a location to save the project.


We can save the newly created project at desired memory location or can keep
file location as it is but atleast change the project default
name untitled to "FirstProject" or something meaningful.
Pycharm automatically found the installed Python interpreter.
After change the name click on the "Create" Button.

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.

Step - 6. The output will appear at the bottom of the screen.


How to install Python in Windows?
Python is the most popular and versatile language in the current scenario.
Python doesn't come with prepackage in Windows, but it doesn't mean
that Window user cannot be flexible with Python.

Step - 1: Visit Official Site to Download Python Installer

o All Python-related information is available on its official website.


First, open the browser and visit the official site (www.python.org) to
install Python installer. Here, we can see the many Python installer
versions, but we will download the latest version of Python.

o It will take us on the above page. We can download the latest


Python installer by clicking on the Download button. We can also
download the older version. Let's see the following example.
Step -2 Install Python

o Once the download is completed, then run the installer by double-


clicking on the download file. It will ask for Add Python 3.8 to
PATH. Click on the checkbox and click on Install Now navigator.
o Once the download is completed, then run the installer by double-
clicking on the download file. It will ask for Add Python 3.8 to
PATH. Click on the checkbox and click on Install Now navigator.

Now Python is successfully installed in Windows, and you are ready to


work with Python.
Writing and Executing First Python Program:
Download Python from www.Python.org.

Once installed, the Python console can be accessed in several ways.


First, using the command line and running the Python interpreter directly.
Second, using a GUI software that comes installed with Python called Python’s Integrated
Development and Learning Environment (IDLE).
Writing Python Programs & Executing it
Step 1: Open an editor.
Step 2: Write the instructions.
Step 3: Save it as a file with the filename having the extension .py.
Step 4: Run the interpreter with the command python program_name.py or use IDLE to run
the programs.
To execute the program at the command prompt, simply change your working directory to C:\
Python34 (or move to the directory where you have saved Python) then type python
program_name.py.
If you want to execute the program in Python shell, then just press F5 key or click on Run
Menu and then select Run Module.
Internal working of Python:
Step1: The python code reads a python source code or instruction and verifies its syntax.in
case of error, the translation of instructions is immediately halted, and error message is
displayed.
Step2; In case of error is encountered, the python code is compiled into an intermediate
language called “Byte code.”
Step3: Byte code is submitted to the Python Virtual Machine (PVM). PVM is the python
interpreter. It converts the Python byte code into machine executable code.
Literal Constants: The value of a literal constant can be used directly in programs. For example, 7,
3.9, 'A', and "Hello" are literal constants.

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:

Quotient and reminder:

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(""")

s1='''CVR College of Engineering’''

s1=""" CVR College of Engineering"""

We can also use triple quotes to use single quote or double quote in our String.

''' This is " character'''


' This i " Character '
We can embed one string in another string
'''This "Python class very helpful" for DS students'''

String literal concatenation:


>>>print(‘Beautiful Weather’ ‘……’’seems it would rain’)
Beautiful Weather……’’seems it would rain’

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]

Specifying stride while slicing strings:


The Stride specifies the number of characters to move forward after the first character is
retrieved from the string.
By default, the value of the stride is 1, which means that every character between two index
numbers is retrieved.
If the stride is 2, then every second character is accessed,if the stride is 3 then every third
Character is accessed.
Examples:
>>> s="CVR"

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

Data Type Boolean


Boolean is another data type in Python. A variable of Boolean type can have one of the two
values- True or False. Similar to other variables, the Boolean variables are also created while
we assign a value to them or when we use a relational operator on them.
Example:
Input Operation
To take input from the users, Python makes use of the input() function. The input() function
prompts the user to provide some information on which the program can work and give the
result. However, we must always remember that the input function takes user’s input as a
string.
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:

Syntax: x = firstValue if condition else secondValue

If condition is True then firstValue will be considered

else secondValue will be considered.

Eg 1: a,b=10,20

x=30 if a<b else 40

print(x) #30

Read two numbers from the keyboard and print minimum value

a=int(input("Enter First Number:"))


b=int(input("Enter Second Number:"))
min=a if a<b else b
print(“minimum value”,min)

output:
Enter First Number:10
Enter Second Number:20
minimum value 10
Program for minimum of 3 numbers

a=int(input("Enter First Number:"))


b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
min=a if a<b and a<c else b if b<c else c
print("Minimum Value:",min)

Maximum of three numbers program


a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
max=a if a>b and a>c else b if b>c else c
print("Maximum Value:",max)
Unary Operators
Unary operators act on single operands. Python supports unary minus operator. Unary minus
operator is strikingly different from the arithmetic operator that operates on two operands and
subtracts the second operand from the first operand. When an operand is preceded by a minus
sign, the unary operator negates its value.
For example, if a number is positive, it becomes negative when preceded with a unary minus
operator. Similarly, if the number is negative, it becomes positive after applying the unary
minus operator. Consider the given example.
b = 10 a = -(b)
The result of this expression is a = -10, because variable b has a positive value. After
applying unary minus operator (-) on the operand b, the value becomes -10, which indicates it
as a negative value.
Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level. These operators
include bitwise AND, bitwise OR, bitwise XOR, and shift operators. Bitwise operators expect
their operands to be of integers and treat them as a sequence of bits.
The truth tables of these bitwise operators are given below.

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

x="hello learning Python is very easy!!!"


print('h' in x)
print('d' in x)
print('d' not in x)
print('Python' in x)

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.

Decision Control Statements


Control Statements
A control statement is a statement that determines the control flow of a set of instructions,
i.e., it decides the sequence in which the instructions in a program are to be executed.
Types of Control Statements —
• Sequential Control: A Python program is executed sequentially from the first line of
the program to its last line.
• Selection Control: To execute only a selected set of statements.
• Iterative Control: To execute a set of statements repeatedly.
If Statement

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

output: enter any number from 0-30:20


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:

For Loop and Range() Function


The range() function is a built-in function in Python that is used to iterate over a sequence of
numbers. The syntax of range() is range(beg, end, [step])
The range() produces a sequence of numbers starting with beg (inclusive) and ending with
one less than the number end. The step argument is option (that is why it is placed in
brackets). By default, every number in the range is incremented by 1 but we can specify a
different increment using step. It can be both negative and positive, but not zero.
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:

Condition-controlled and Counter-controlled Loops

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:

The Break Statement


The break statement is used to terminate the execution of the nearest enclosing loop in
which it appears. The break statement is widely used with for loop and while loop.
When compiler encounters a break statement, the control passes to the statement that
follows the loop in which the break statement appears.
The Continue Statement
Like the break statement, the continue statement can only appear in the body of a loop. When
the compiler encounters a continue statement then the rest of the statements in the loop are
skipped and the control is unconditionally transferred to the loop-continuation portion of the
nearest enclosing loop.

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:

You might also like