0% found this document useful (0 votes)
15 views24 pages

sem 3 com python ch 1

The document provides an introduction to Python, covering its history, features, applications, and installation process. It highlights Python's ease of use, readability, and versatility across various domains such as web development, data science, and artificial intelligence. Additionally, it discusses the basic structure of Python programs, keywords, identifiers, and variable management.

Uploaded by

sohanpatel0777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views24 pages

sem 3 com python ch 1

The document provides an introduction to Python, covering its history, features, applications, and installation process. It highlights Python's ease of use, readability, and versatility across various domains such as web development, data science, and artificial intelligence. Additionally, it discusses the basic structure of Python programs, keywords, identifiers, and variable management.

Uploaded by

sohanpatel0777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

Scripting Language Python

Unit

1 FUNDAMENTALS OF PYTHON

1.1. Introduction and History of Python


1.2. Python Features
13. Python Applications
1.4. Installing Python
1.5. Basic Structure of Python program
1.6. Keywords und Identifiers
1.7. Data types and Variables
1.8. Type Casting
1.9 Input-Output functions: input, print
1.10. Operators
MCQ
Solved Questions
Exercise

1.1. Introduction and History of Python


Python is an open-source (free) programming language\that is used in web programming. data
science, artificial intelligence, and many scientific applications. Learning Python allows the
programmer to focus on solving problems, rather than focusing on syntax.It was created by Guido
van Rossum in 1991 and further developed by the Python Software Foundation.
1.2. Python Features
1. Easy Language
Python is an easy language. It is easy to read, write, learn and understand.
Python has a smooth learning curve. It is easy to learn.
Python has a simple syntax and Python code is easy to understand.
Since it's easy to understand, you can easily read and understand someone else's code.
Python is also éasy to write because of its simple syntax.
2. Readable
(Che Python language is designed to make developers life easy) Reading a Python code is like
reading an English sentence. This is one of the key reasons that makes Python best for beginners.
Python uses indentation instead of curly braces, unlike other programming languages. This makes
the code look clean and easier to understand.
3. Interpreted Language
Python is an interpreted language) (It comes with theIDLE YInteractive Development
Environment). This is an interpreter and follows the REPL structure (Read-Evaluate-Print-Loop).
It executes and displays the output of one line at a time.
Seripting Language Python-2022 / I
2
Seripting Language Python
So it displays erors while vou'e unning a line and displays the entire stacK trace tor the eoe
4. Dynamically-Typed Language

You don't nced to declare data type while defining a variable. The interpreter detesmines this .
untime based on the types of the parts of the expression. This is easy tor
programmers but Can
create nuntime emors.
$. Object-Oriented
Python is object-oriented but supports both functional and object-orientcd programming. Everythino
in Python is an object.
6. Open-Source
Python is open-source and the community is always contributing to it to improve It is
free and
its source code is freely available to the public. You can download Python from the official Python
Website.
7. Large Standard Library
The standard library is lange and has many packages and modules with
common and
functionality. If you need something that is available in this standard library, you don'timportant
need to
write it from scratch. Because of this, you can focus on more important things.
8. Platform-Independent
Python is platform-independent. If you write a program, it will run on
like Windows, Mac and Linux. You don't need to write them different platlorms
separately for each platform.
9. Extensible and Embeddable
Python is extensible. You can use code from other languages like C++ in your Python
also embeddable. You can embed your Python code in other code.It is
languages like C++.
10. GUI Support
You can use Python to create GUI (Graphical User Interfaces).
1.3. Python Applications
Python can be used for various domains :
Domain Description
Desktop and Web A Desktop application is one that runs stand-alone in a desktop or laptop
Applications computer for example BiToment, Blender, Juice while a Web application requires
a Web browser to run, for example Mailman, Plone, MoinMoin.
Data Science It is a ficld that uses scientific methods such as data collection; algorithms and
machine leaning techniques to extract, analyze and process insights from raw data.
Machine Learning It is an application of artificial intelligence (AI) that gives systems the ability lo
automatically learn and improve from expericnce and data without being explicitly
programmed
Robotics It is a branch of engincering that deals with the conception, design, manufacture,
and operation of robots.
Artificial
I is a broad field that deals with enabling machines to demonstrate inelligence
Seripting Language Python
Domain Desoription
Intelligence Similar human's intelligence such as decision-making., facial recognition.

ctc.Artificial intelligence incorporates other fields like Machine L¢aming. Robotics.


Natural Language Processing(NLP), etc.
Internet of Things I is a ficld that describes the network of things that are embedded with software.
(loT) and other lechnologies for the purpose of connecting and exchanging data with
other devices over the internet.
Gaming I is the art of designing and programming games for entertainment, cducational.
or experimental purposes and that runs on computers and mobile devices.
Mobile Applications I is a computer program or app designed to run on a mobile device such as a
phone, table, or watch.
Natural Language It is a field that analyses speech in both audible speech, as well as text of a
processing language.
3D CAD Python can create a 3D CAD application by using the following functionalities.0
Fandango (Popular)
CAMVOX
HeeksCNC
AnyCAD
RCAM
Data visualization Data visualization is another popular and developing area of interest. Python
provides a variety of graphing libraries with all.,kinds of, features. You can find
a library to create simple graphical representation or even a_ more interactive
plot in python. Examples include Pandas.Visualization and Plotly.
Finance Python is increasingly being utilized in the world of finance, often in areas such
as quantitative and qualitative analysis. It can be a valuable tool in determining
asset price trends and prédictions
Image Processing Python contains many libraries that are used to work-with the image. Some
libraries of image processing are given below.
OpenCV
Pillow
SimplelTK

Some Dfawbacks of Python are :


Slow speed
Memory inefficient

Ineffective in mobile computing


Undeveloped database layers.
Run time error prompt due to its dynamism.
Seripting Language Python
1.4. Installing Pthon
betor we start Python pogramming, we need to have an interpreter to interpret and run our
programs. There are cetain online interpreters like https:/ide.geeksforgecks.org. htp://hdecne cony
r ntp://codepad.org/ that can be used to run Python programs without installing an interpreter.
Windows There are many interpreters available frecly to run Python scripts like IDLE (Integratcd
Development Environment) that comes bundled with the Python software downloaded from btt/
(python.org
Python 3 Installation on Windows
Step 1: Download Pvthon 3.9

lo start, go to python.org/downloads and then click on the button to download the latest version
of Python:

Python PSF Docs

Ppython
Downloads Documentation Community

Down d the latest version for Windows


Download Pythor 3.9.0

Looking for Python with a different 0S? Python for Windows,


Linux/UNIX, Mac OS X, Other

Step 2: Run the .exe file


Next. run the .exe file that you just downloaded:

python-3.9.0
Seripting Language Python
Step 3: Install Python 3.9
You can now start the installation of Python by clicking on Install Now:
Python 3.9.0 (64-bit) Setup

Install Python 3.9.0 (64-bit)


Select Install Now to install Python with default settings, or choose
Customize to enable or disable features.

9 Install Now
CUsersluoniAppDetailecer Prograrn: Pythun Python39

Include: IDLE pir and docurntntation


Creates shortcut and file associatiuns

’ Customize installation
Choose lotstion and features

python M Install launcher for all users (recommended)


for
Cancel
DAdd Python 3.9 to PATH
windows
also check the box to add Python to the Path.
Note that depending on your needs, you may
Your installation should now begin:
Python 3.9.0 (64-bit) Setup

Setup Progress

Installing:

Initializing...

python fo
Cancel

windows
completed:
lime, your setup would be
of
After a short period
10 Seripting Language Pytho
1.5. Basic Structure of
Python program
and C.py. The file
The structure Pyihon
Program consists of three files such as :a.py.b.py modetsi
Py IS chosen for high level Gle it is known as a simple text file of statements. .. Files b.py
C.py ane modules

Top-level Modules

b.py

Standard
a.py library
modules

C.py

In General Python Program Consists of so many text files, which contains python statements.
Program is designed as single main, high file with one or more supplement files Python
Statements In general, the interpreter reads and executes the statements line by line i.e sequentially.
In python high level file has Important path of control of your Program where you can start your
application. The library tools are also known as Module files. These tools are implemented for
making collection of top-level files. High level files use tools which are defined in Module files.
Modules :
Modules are having top end of code.
Standard library files :
Python has large collection of modules known as standard library.it contains many modules for
GUI Design, Internet and network scripting, Text design malching. Operating system Interfaces.
First Python Progran1
Let us execute programs in different modes of programming.
Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the following prompt
Type the following text at the Python prompt and press the Enter -
>>> print "Hello, Python!"
Seripting Language Python 11

I1 you are running new version of Python, then you would need to use print statement with
parenthesis as in print ("Hello, Python!"):. this produces the following result
Hello. Python!
Seript Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and continues until
the script is finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the following
Source code in a test.py file "

print "Hello, Python!


We assume that you have Python interpreter set in PATH variable. Now, try to run this program
as follows

test.py C\Users\Gayatri\AppDatallocal Programs\Python\Python38-32\test.py (3.8.3)


Frle Edt Format Run Options Window Help
IEnt ("Hello, Eython!"):

This produces the following result"


Hello, Python!
Python Statements

Python programs are typically organized with one statement per line. In other words, each statement
occupies a single line. with the end of the statement delimited by the newline character that marks
the end of the line.

Example
print ( 'Welcome to python programing' )
Output :
Welcome to python programming
Multiple Statements per Line We can also write multiple statements per line, but it is not a good
practice as it reduces the readability of the code. For Example, consider the following code.
12 Seripting Language Pytho

Example
a 10: ba 20; c b a
print (a); print (b); print (c)
Output:
10

20

80
Comments in Python
Symbols used for writing comments include Hash (#) or Triple Quotation marks (""). Hash
Used in wnting single linc comments that do not span multiple lines. Triple Quotation Marks an
UScd to write multiple line comments. Three quotation marks to slart the comment and again threa
quotation marks to end the comment.
Example
###**** This example wil1 not print Hello World ##****# print( 'Hello
World) # This is a comment

Multiline Comments
This example will demonstrate
multiple comments

wThe following
a variable contains the

string Your age'

a = 'Your age?

The following statement prints


what's inside the variable a

print (a)

1.6. Keywords and ldentifiers


Keywords:
The following list shows the Python keywords. These are reserved words and you cannot use
them as constant or variable or any other identifier names. All the Python keywords contain
lowercase letters only.
Seripting Language Python

and exec not


àssert finally
break for pass
Class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Idéntifiers and variables
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 moe
letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @. S, and % within
a case sensitive programming language. Thus, name and Name are two identifiers. Python is
different identifiers in PythOn.
The value stored in a variable can be
changed during program execution.
A variable is only a name given to a memory location; áll the
effects that memory location. operations done on the variable
A variable can have a short name (like x and v) or a
more descriptive name (agc, carname,
total_volume).
Rales for Python variables :
A variable name must sturt with a letter or the underscore character
A variable name cannot start with number

A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and )

Variable names are case-sensitive (age, Age and AGE are three different ariables)
Valid Variable Invalid Variable

myCountry = "India" 2myCountry = "India

my_Country "India" my-Country "India"


my_Country = "India" my Country = "India"

myCountry "India"
MYCOUNTRY = "India"

myCountry2 = "India"
14 Seripting Language Pytho
Example variable ereation:
# An integer assiqnment
age= 41
# Afloating point
salary = 1234.5
# A string

name = "India"

print (age)
print (salary)
print (name)
Output :
41

1234.5
India

Declare the Variable


Let's see how to declare the variable and print the variable.
# declaring the var
Number = 100

# display
print( Number)
Output :
100

Variable re-declaration:
We can re-declare the python variable once we have declared the variable already.
# declaring the var
Number = 100

# display
print ("Before declare: ", Number)

# re-declare the var


Number = 120.3

print ("After re-declare: ", Number)


Scripting Language Python 15

Output :
Before declare: 100
After re-declare : 120.3
Assigning a single value to multiple variables :
Also, Python allows assigning a single value to several variables simultaneously with "" operators.
For example :
a = b = c = 10

print (a)
print (b)
print (c)
Output:
10
10

10

Assigning different values to multiple variables :


Python allows adding different values in a single line with " operators.
a, b, c = 1, 20.2,,"India"
print (a)

print (b)
print (c)

Output
1

20.2
India

1.7. Data types and Variables


Data types are the classification of data items In Python programming, data types are actually
classes and variables are instance (object) of these classes.
Following are the standard or built-in data type of Python :
Numbers
String
List
Tuple
Dictionary
16 Seripting Language Pythun

Python - Data Types

Sequence
Numeric Dictionary Boolean Set Type
1ue
False
Interger Float Strings Tuple
Complex (u ") List ()
Number

Numbers

Python supports four distinct numeric types: integers, long. float and complex numbers. In
addition, Boóleans are a subtype of plain integers. Integers int are positive or negative wholc
numbers with no decimal point. Long integers have unlimited precision and floats represcnt real
numbers and are written with a decimal point dividing the integer and ractional parts.Complex
numbers have a real and imaginary part, a + be, where a is the real part and b is the imaginary
part.

Exampl
#integer example
x=9999

print ("type of x is . type (x) )


#float example
y=3.141
print ( "The type of y is ". type (y))
#complex example
z=99+5j
print ("The type of z is ". type(z) )
Output
Type of x is < class 'int' >
The type of y is < class 'float
The type of z is < class 'complex' >

String
A String is an aray of characters. They are formed by a list of characters, which is really an
""array of characlers".
Seripting Language Python 17

In Python, string is a sequence of Unicode character. We can create them simply by enciosiny
characters in quoles. Python treats single quotes the same as double quotes.
str = "Hello World" |/double quotes
strl = Hello
World!'I/using single quotes
Python strings arc "immulable" which means they cannot be changed after they are crcated.
Characters in a string can be accessed using the standard | syntax and zero-based indexing.
Example :
str = Hello World"

print (str (0])

print (str [6:11] )


print (str + " !!")
print (len (str))
Output
H

World

Hello World !!

11

" List

Python List is one of the most frequently used and very versatile datatype. Lists work sinilarty
to strings: use the len() function and square brackets []to access data, with the first element at
index 0.

Example
weekdays = ( Monday', Tuesday', 'Wednesday', Thursday', Friday ]
print (weekdays [0] )
print (weekdays (4) )

Output
Monday
Friday
Tuple
A tuple is a tontainer which holds a series of comma-separated values between parentheses, A
tuple is similar to a list. Since, tuples are quite similar to lists, both of them are used in similar
situations as well. The only the difference is that list is enclosed between square bracket, tuple
between parenthesis and List have mutable objects whereas Tuple have immutable objects.

sripting Language Python-2022 / 3


18
Seripting Language
Example
my_Tuple_1 = (1,2, "Hello ,3.14,"world")
print (my_Tuple_l)
print (my_Tuple_1 (3))
my_Tuple_2 = (5, "six*)
print (my_Tuple_1 + my _Tuple_2+)
output
(1, 2, 'Hello'. 3.14, 'world')
3.14

(1, 2, Hello', 3.14, 'world', 5, 'six' )


Dictionary
Python Dictionaries allow you store and retrieve related information in a way that means somethin
both to humans and computers. Dictionaries are non-ordered and contain "keys" and "values", E
key is unique and the values can be just about anything, but usually they are string, int, or loa
or a list of these things. Dictionaries don't support the sequence operation of the sequence da.
types like strings, tuples and lists. Dictionaries belong to the built-in mapping type.
Example:
# Creating a
Dictionarywith Integer Keys
Dict = {1: I, 2: 'For', 3: India)
print ("\nDictionary with the use of Integer Keys: ")
print (Dict)

output
Dictionary with the use of Integer Keys:
(1: ' I , 2: 'For', 3: India')
To tell what the value type is, you can use the built-in type() function. In the following examples.
we use the type() function to display the value type:
>>> x = 42

>>> print (type (x) )


<class 'int'>
>>> x = 'hi'

>>> print (type (x) )


<class 'str'>
>>> x = 3.14

>>> print (type (x))


<class float'>
Seripting Language Python
,>>X False

>>> print (type (x) )


Kclass 'boo1'>

Checking for Type Equality


While the ty pe()function lets us check which type a variable contains. The 'is' operator used lor
identity checking. Numeric values may compare as equal to each other using the equality lest = yet
not match on their type. Consider this example:
>>> x = 1

>>> y = 1.0

>>> X == Y

True

>>> X is y

False
>>>

In the above example, x is assigned the integer value 1and yis assigned the float value 1.0. When
tested using the equality match ==, the result is True. Yet when tested using the object identity
operator is, the result is False since float and int are different types.

1.8. Type Casting :


Type Conversion
The process of convering the value of one data type (integer, string, float, etc.) to another data
type is called type conversion.
1 Type Conversion is the conversion of object from one data type to another data type.
Implicit Type Conversion is automatically performed by the Python interpreter.
Python avoids the loss of data in Implicit Type Conversion.
4 Explicit Type Conversion is also called Type Casting, the data types of objects are converted using
predefined functions by the user.
$. In Type Casting, loss of data may occur as we entorce the object to a specific data type.

Python has two types of type conversion:


Implicit Type Conversion
Explicit Type Conversion
Tmplicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another data tvpe
involvement.
This process doesn't need any user
20 Seripting Language Pytho
Example 1 :
Converting integer to loat
X= 10

print ("x is of t
ype:.type (x))
y = 10.6

print ("y is of
type:.type (y))
XX y
print (x)

print("x is of type:, type (x))


Output:
x 1s of type: <class int'>
Y is of type: <class
float'>
20.6
X 1s of type: <class float '>
AS we can see he type od 'x' got automatically changed to the "float" type from the "integer
type. this is a simple case of Implicit type conversion in python.
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type. We
use the predefined functions like int(), float(), str(), etc to perform explicit type conversion
This type of conversion is also called typecasting because the user casts (changes) the data lype
of the objects.
Syntax:

<required_datatype> (expression)
Typecasting can be done by assigning the required data type function to the expression.
In Explicit Type Conversion in Python, the data type is manually changed by the user as.pçr their
requirement. Various form of explicit type conversion are explained below:
int(a, base): This function converts any data type to integer. 'Base' specifies the base in which
string is if the data type is a string.
float(): This function is used to convert any data type to a floating-point number.
Example : Explicit type conversion
# Python code to demonstrate Type conversion
# using int (), float (), str()
Integers
X = int (1) # x will be 1

int (2. 8) # y will be 2


z = int ("3") # z will be 3
Seripting Language Python 21
Floats :

X = float (1) # x will be 1.0


y =float (2.8) y will1 be 2.8
z = float ("3") z wil1 be 3.0
o4 = float ( "4 .2") # w
will be 4.2
Strings :
K = Strsl") # x will be s1
y = str (2) #y will be2'
2 = str (3.0) # z will be 3.0
1.9. Input-Output functions: input, print
input ()

Pylhon provides us with a function that allows us to ask a user to enter some data and retuims
a reference to the data in the form of a string. The function is called input.
Python's input function takes a single parameter that is a string. For example, you might call
input as follows:
aName = input ('Please enter your name:)

Now whatever the user types after the prompt will be stored in the aName variable. Using the
input function, we can easily write instructions that will prompt the user to enter data. For example.
in the following two statements, the first asks the user for their name and the second prints the
result of some simple processing based on the string that is provided.
Example
aName = input( "Please enter your name ")
print ( Your name in all capitals is",aName.upper (), "and has length, len (aName)
Output :
Please enter Your name Jitendra
Your name in al1 capitals is JITENDRA and has length 8
It is important to note that the value returned from the input function will be a string representing
the exact characters that were entered after the prompt. If you want this string interpreted us
another type, you must provide the type conversion explicitly. In the statements below, the string
that is ente red by the user is converted to a float so that it can be used in further arithmetic
processing.
w)
radius = input"Please enter the radius of the circle
radius = float (sradius)
diameter = 2 radius

print (radius)
print (diameter)
22
Seripting Language Pyuio
Output
Flease enter the radius of the circle 2
2.0
4.0
print()

The print function provides a very simple way to output values from a Python program.
print take
zero or more parameters and displays them using a single blank as the
default separator, It i
possible to change the separator character by setting the sep
argument. addition, cach print ende
In
with a newline character by default. This behavior can be changed setting the end argument
These vanations are shown in the following session:
PIint("Hello)

Print ( "Hello, "World)


print("Hell0", "World", sep="*** )
print ("Hello", "World", end="*** ")
Output:
Hello

Hello World
Hello"* *World
Hello World* *
Python provides us with an alternative called formatted strings. A formatted string is a template
in which words or spaces that will remain constant are combined with placeholders for variables
that will be inserted into the string. For example, the statement
print (aName "is", age, "years old. ")

contains the words is and years old, but the name and the age will change depending on the variable
values at the time of execution. Using a formatted string., we write the previous statement as
print ("$s is %d years old, " (aName, age) )

This simple example ilustrates a new string expression. The %operator is a string operator called
the format operator. Note that the number of values in the collection on the right side correspons
with the number 'of %characters in the format string. Values are taken--in order, left to right
from the collection and inserted into the format string.

The format string may contain one or more conversion specifications. In the cxample above.
the %s specifies a string, while the %d specifies an integer. Following table summarizes all of the
various type specifications.
Scripting Language Python
Character Output Format
d, i Integer
Unsigned integer
Floating point as m.ddddd
Floating point as m.ddddde+/-xx
Floating point as m.dddddE+/-xx
Use %e for exponents less than "4"4 or greater than +S+5, otherwise use %f
Single character
String, or any Python data object that can be converted to a string by using
the str function.
Insert a literal % charaçter

Format modifiers may be used to lef-justify or right-justifiy the value with a specified field width.
Modifiers can also be used to specify the field width along with a number of digits after the
decimal point. Following table explains these format modifiers
Modifier Example
Description
number %20d Put the value in field width of 20

%-20d Put the value in a field 20 characters wide, left-justified


%+20d Put the value in a field 20 characters wide, right-justified
%020d Put the value in a field 20 characters wide, fill in with leading zeros.
%20.2f Put the value in a field 20 characters wide with 2 characters to the right
of the decimal point.
(name) %(name)d Get the value from the supplied dictionary using name as the key.
Example
price = 24

item = "banana"

print ( "The %s costs td cents"%(item, price) )


print("The %+10s costs 5.2f cents"%(item, price) )

print( "The %+10s costs 10.2f cents "%(item, price))


itemdict = ("item": "banana", "cost":24)
print ( "The %(item) s costs %(cost)7.1f cents%itemdict)

Output:
The banana COsts 24 cents
The banana costs 24.00 cents

The banana costs 24.00 cents


1ne banana Costs 24.0 cents
24 Scripting Language Pytho
In addition to format strings that use format characters and format modifiers, Python strings at
include a format method that can be used in conjunction with a new Formatter class lo implemen
complex string formatting. More about these features can be found in the Python library relercnce
manual.

1.10 Operators :
Operators are used for carrying out operations on values and variables.
Python has 7 types of Operators as stated below :
Arithmetic Operator
Comparison operatorsS
Logical operators
Bitwise operators
Assignment Operator
Identity operators
Membership operators
(|) Arithmetic Operators
Python programming language supports different kinds of arithmetic operators for both integer and
floating point like addition, subtraction, multiplication, division and so on.
Operator Type Definition
Addition (+) Addition operator
Subtraction (-) Subtraction operator
Multiplication () Multiplication operator
Division () Division operator
Modulus (%) Reminder operator
Floor division (/) Divides and returms the value of the remainder.
Exponentiation (**) Raises the left operand to the power of right.
Example
Pthon 61Shall X

Fie fdt Shet Debug Ogians Wind3 Help


Pvsuoa 3.6.1 (13.6.4:d45eLeb, Dec 19 2017., 06:D4:45) SC v.1900 32 biL (I
n vint7
TyEc "oopyright", crcdite" or "ll9zn8c ( tor nOrC intoraation.

>>> pEini

>>> print%- y =', I-)

y = 150
: / y -1.5

x $76¬50390425
Seripting Language Python 25

2) Comparison Operators
Comparson operators are used for comparino values. IL either returns True or Falsc according lo
the condition.
Operators
Definition
Greater than (>)
True if left operand is grealer than the right
Less than (<)
True if left operand is less than the right
Fqual to (==) True if both operands are cqual
Not cqual to (!=)
True if operands are not cqual
Greater than or cqual to ()
True if left operand is greater than or equal to the right
Less than or equal to (<=)
True if left operand is less than or cqual to the right
Exannple :
Python 3.64 Shell
X
File Edit Shel Debug Options Window Help
Python 3.6.4 (V3 .6.4:d48e ceb, Dec 19 2017. 06:04:45) MSC v.1900 32 bit (Intel}
on win32
Type copyright", "credits® or "license () for more informat 1on.
>>> x = 8

>3> y= 15
>>> print ('X > y is', xy)
x >Y is False
>>> print ('x < y is', x<y)
x<y 1s True
>>5 print('x y is', xy)
x v is False
>> print ('* != y is', x!y)
x ! y 1s True
>> print ('x S= y i ' , x>=y)
X =Y is False
>> print ('x (= y ig, K<=Y)
y is True

(3) Logieal Operators


Logical operators are used for performing AND, OR and N T operations. It either returns True or
False according to the condition.
Operators Definitions

and True if both the operands are true


True if either of the operands is true
not True if operand is false

Seriptiag Language Python-2022 4


26 Seripting Language Pyh
Example
thon 3,64 Shell
Frie Edt Shell Debug Options Window
Help
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) (MSC v.1900 32 bit (Inre
on win32
Type copyright ". "creditg" or "licenge () " for more informa tíon.
>>>a 1 r u e
>> b a l s e
is', à and b)
>>> pI int ('a and E
a and ba False
>>> print ( 'a or b is', a or b)
a or bis True
>>> int (not a 1s, no a)
not a is False

(4) Bitwise Operators

Bitwise operators operate on bits and perform bit by bit operation.


Operators Definitions
Bitwise AND
Bitwise OR
Bitwise N T
Bitwise XOR
Bitwise right shift
Bitwise left shift
(S) Assignment Operator
An assignment operator is used to assign a value to a variable.
Operators Definitions Output
x = 15 X = |S
X += 15 X= X + 15

-= X -= 15 X = x- 15

x *= 15 X= X * 15

X = X /15

o= x %= 15 x = x % 15
x Il= I5 X= x I 15

**= x **- 15 X= X * 15

&= x &= 15 x = x & 15


x = 15
X ^= 15 X = X ^ 15

X <<= 15 X = X <« 15
Scripting Language Python 27
(e) ldentity Operators
Python offers 2 types of identity operators ie is and is
not.
Both are used to compare if two values are located on he same par of the memory. Two variables
that are cqual does not imply that hey are
Operators
identical.
Definitions
True if the operands are identical
Irue if the operands are not identical
Ample :
Python 5.64 Shell X
le Edit Shell Debug Opions Window
Help
Ey:hon 3.6.4 (3.¬.4:d48eceb, Dec 19 2017. 06t04 :45) MSC v.1900 32 b1t (2ntez)

IYpe "copyright", "creditg" or 1icensel) for Bore Anfortion.


>>a 3

>>> a2- "Pythcn"


>>> b2 "Pythcn"
>>> a3 (4,5, 6)
>>> b3 (4,5,6])
>>> p:int (al 1s nct bl)
Falsc
>>> p:int (a2 is ba)
Irue
>>» pzint (a3 ia b3)
False

() Membership Operators
Python offers 2 types of membership operators i.e in and not in.
Both are used to test whether a value or variable is in a sequence.
Operators Definitions
True if value is found in the sequence
not in True if value is not found in the sequence
Example :
Phon 2.7.14Shell
Ale fde She Drhg Ontinns Windo Hp

Vytban 2.1.14 (2..14:0447A9Sted, Sep L6 Z0L, 2u: 19:30) MS .L5U0 z bat tin
Del) 1 on vin)2
Type eopyrigh=", "creditg" or license () £ar nOre infTatioa.

True
D2> luL "uy Luu" tiL iu a)
False
>2> print 1 1n b)
Truc
hy
>>> prinr ty* tn
Ealc
28 Seripting Language Pyuh
in b eturns False.
TIs key and '\ IN the value in dietinry b Hence, 'y'
" Operators Precedence
The folloW ing table lists all onetors fom highest preccdence to lowest.
Sr.No. Operator & Description
"Exponentiation (raise to the powcr)
the last two are +@ and -a
+ Complement. unary plus and minus (method names for
/ Multiply, divide. modulo and floor division
4 + -Addition and subtraction
>><<Right and left bitwise shift
6 &Bitwise 'AND'
7 A IBitwise exclusive OR' and regular 'OR'
8 <- <O>=Comparison operators
O == =Equality operators
10 = = (= l/= = += '= *=Assignment operators
is is notldentity operators
12 in not inMembership operatoTs
13 not or andLogical operators
MCQ
01 Which the following statements assigns the value 25 to the variable x in Python :

A X 25 X = 25
C X= 25 D int x = 25
E. X << 25 Answer : B

02 In Python, a variable may be assigned a value of one type, and then later assigned a value
of a different type :
B Irue Answer: B
A False
03, Which one of the following is the correct way of declaring and initializing a variable, Nwith
the value 7?
A int x. X=1 B int x=7
D declare x=7 Answer:C

04. What will be the output of statement 2**2**2**2


A 16 B 256
D 65536 Answer: D
C 32768
05. Which of the following statement is False ?
A Variable names can be arbitrarily long.
B. They can contain both letters and numbers.
C Variable name can begin with underscore.
D Variable name can begin with number. Answe

You might also like