sem 3 com python ch 1
sem 3 com python ch 1
Unit
1 FUNDAMENTALS OF PYTHON
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.
lo start, go to python.org/downloads and then click on the button to download the latest version
of Python:
Ppython
Downloads Documentation Community
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
9 Install Now
CUsersluoniAppDetailecer Prograrn: Pythun Python39
’ Customize installation
Choose lotstion and features
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 "
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
a = 'Your age?
print (a)
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"
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
# 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)
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
print (b)
print (c)
Output
1
20.2
India
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
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"
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.
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
>>> 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.
print ("x is of t
ype:.type (x))
y = 10.6
print ("y is of
type:.type (y))
XX y
print (x)
<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
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)
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
item = "banana"
Output:
The banana COsts 24 cents
The banana costs 24.00 cents
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
>>> pEini
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
-= 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
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)
() 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