You are on page 1of 16

PRAGATI ENGINEERING COLLEGE, SURAMPALEM

(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

UNIT – I

1.1. Introduction to Python


Python is a simple and powerful language. It provides the solution to the given problem
without worrying on the technical details of the programming language viz., structure and
syntax. It supports high level programming language with both procedure and object oriented
properies. It is more suitable for scripting and various applications development. The python
programming language is introduced by Guido van Rossum. Various popular programming
languages viz., C, C++ and Java can be coupled with Python. It contains built in libraries for data
structures and GUI (graphical user interface). In Python, a control routine program is an
additional feature. This program feature makes the Python to connect different programs. With
the built in garbage collector feature, the memory management is handled efficiently in Python.
In Python, including various libraries is not required and also usage of code blocks is made easy
with the indentation (white space).
In Python, declaration of a variable not requires the specification of the data type. So, it is
called as the dynamic typed language. It is applicable for derived types also. The Python is a
platform independent programming language. It contains an interpreter which will read the
source program line by line and converts into machine code. Similar to Java programming
language, the Python also supports platform independent feature with the help of Bytecode. The
interpreter of Python will generates the Bytecode as the output. This btecode file can be used by
any platform and within each platform, the Bytecode should be executed. The Python uses the
interpreter than the compiler so, it takes more time. The advantage of using interpreter is that the
syntax errors can be identified immediately after reading that line. The Python programming
language is more popular for the program prototyping. With this, the programs can be developed
with in less amount of time and it can support further modifications in quicker with the support
of graphical user interfaces (GUIs).
The Python supports both procedural oriented and object oriented programming language. In
a single Python program, both these programming language features can be used. So, Python
programming supports usage of top down approach which allows the usage of functions. It also
supports bottom up approach which allows the usage of class and objects.

1
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

1.2. Installing Python


Windows Operating System
Step1: Download the Python software from the following URL
https://www.python.org/downloads/windows/

Step2: Install the downloaded Python software

2
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

3
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

4
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

Step3: Add Python to the System Variable

 Click on Start->My Computer->Properties->Advanced System Settings->Environment


Variables-> System Variables-> Path->Edit.
 In the Text box, at the end paste the path of the Python “D:\Python\Python36-32;”
 Click OK.

1.3. Basic syntax

1.4. Interactive shell


Invoking the interpreter without passing a script file as a parameter brings up the
following prompt −

>>> print("Hello, Python!")

5
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

Script 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. Python files have extension .py

1.5. Editing, saving, and running a script (Script mode)


Step 1: Open notepad and type the following line

Step 2: Save the file as Hello.py


Step 3: Click Start->run->cmd->PythonProgramdirectory->python Hello.py

1.6. The concept of data types variables


In Python programming language, the data can be maintained by variables. The type of
the variable represents the value stored within the variable. Type inferencing is allowed in
Python. So, the general keywords like “int”, “float” etc. are not required for the variable.

6
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

D:\Python>python
Python 3.6.0 (v3.6.0:41df79263a11,
Dec 23 2016, 07:18:10) [MSC v.1900
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or
"license" for more information.
>>> 10
10
>>> 35.76
35.76
>>> 'abcd'
'abcd'
>>> 1,00,000
In Python, “type” keyword is used to get the data type assigned to the input data.
(1, 0, 0)
>>> type(100)
<class 'int'>
>>> type(15.27)
<class 'float'>
>>> type('abcd')
<class 'str'>

The “bool” data type contains two possible values viz., “True” and “False”.

>>> bool

<class 'bool'>

The “False” value can be considered in any one of the following cases.
 If the value is “None”
 If the value is “0” or “0.0”
 If the input value is empty list, tuple or string.

7
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

>>> bool('a')

True

>>> bool('')

False

In Python, variables can be initialized without declaration. Based on the value of the input data,
the type of the variable will be automatically considered. A variable name should start with a
letter followed by sequence of letters, numbers or underscore (_) special character.
Integer data, floating point data and string data will be considered as primitive data type.
Character data will be considered as string data with length 1.

>>> a=65
>>> b=78.24
>>>c='hai'
>>>a
65
>>>b
78.24
>>>c
‘hai’

In Python, the string data will be considered as an array. The array index will start from 0.

>>> a='chapter-2'
>>> a
'chapter-2'
>>> a[1]
'h'
>>> a[0]
'c'
>>> a[5]
'e'

8
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

For string data, ‘+’ represents the concatenation operation and ‘*’ represents the repetition
operation.
>>> a=('ha'+'i')
>>> a
'hai'
>>> a=('ha'*2)
>>> a
'haha'

Other than the primitive variables, Python also supports the following variables.

1.7. Assignments immutable variables


Tuples:
It is a list with a fixed number of elements. It uses parentheses for specification of data.

>>> x=(4,5,6)
>>> x[0]
4
>>> x[1]
5
>>> x[-1]
6
>>> x[2]
6

The index ‘-1’ represents the last element in the tuple. In case of tuple variable, the change of the
values is not permitted.

>>> x[2]=10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
9
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

Lists:
It is different than tuple. A list without a fixed number of elements. It uses square brackets for
specification of data. The change of values of a list variable is allowed.
>>> x=[4,5,6]
>>> x[0]
4
>>> x[1]
5
>>> x[-1]
6
>>> x[2]
6
>>> x[0]=10
>>> x
[10, 5, 6]

Dictionaries:
It is a variable used to maintain multiple typed elements. It uses curly braces for specification of
data. It maintains the data by using {key:value,…} format. Multiple entries will be separated by
the comma operator. The change of values is allowed.

>>> x={1:'a',2:2,3:5.8}
>>> x
{1: 'a', 2: 2, 3: 5.8}
>>> x[1]
'a'
>>> x[2]
2
>>> x[3]
5.8
>>> x[1]='b'
>>> x 10

{1: 'b', 2: 2, 3: 5.8}


PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

1.8. Numerical types


In Python programming, when the numerical values are assigned to the variable, then the
numeric objects will be automatically created. The ‘del’ keyword is used to delete the reference
to the numeric objects. The syntax of ‘del’ keyword is
del numericalobject-1[,……,numericalobject-n]
 If the ‘del’ keyword is applied on the numeric object where it is not initialized then a
runtime error will be generated.

b=20
print("Value of B=",b)
del(a)
print("Value of A=",a)

Output:
D:\PythonPrograms>python del.py
Value of B= 20
Traceback (most recent call last):
File "del.py", line 3, in <module>
del(a)
NameError: name 'a' is not defined

In Python programming language, there are three types of numerical objects. They are
i. integers
ii. floating point numbers
iii. complex numbers

2.10. Integers
The integers represent the fixed point numerical data. So, it maintains integer numbers
with no decimal point. In early versions, there are integers and long integers. But in version3,

11
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

only int with unlimited size is allowed. With this both the positive and negative numbers can be
represented. A subset of integers is allowed to represent the Boolean values. An integer value
can be represented in binary, decimal, hexa-decimal or octal form.

>>> a=10 #decimal integer value


>>> a
10
>>> a=0b100 #binary integer value
>>> a
4
>>> a=0x16 #hexa-decimal integer value
>>> a
22
2.11. Floating Point Numbers
>>> a=0o24 #octal integer value
The floating point
>>> a numbers are used to represent the floating point numerical data. So, it
20 with decimal point separating the integer and fractional parts. Scientific
maintains real numbers
notation may also be used to represent the data. The exponential power is represented with ‘E’ or
‘e’ in decimal system.

2.12. Complex Numbers


The complex numbers are used to represent the numerical data in terms of x+iy, where x
represents the real part and y represents the imaginary part. Both x and y values are floating point
numbers.

2.13. Functions Applicable to All Types of Numbers


In Python programming, one type of numerical data can be converted to another type of
data by using number type conversion functions. Various number type conversion functions are
listed below.
 int() function will convert and returns the input data to a integer number. It requires one
argument.
 long() function will convert and return the input data to a long integer number. It requires
one argument.

12
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

 float() function will convert and returns the input data to a real number. It requires one
argument.
 complex() will convert and returns the input data to a complex number. It can take one or
two arguments. If one argument is provided then it will be placed in real value with zero
imaginary value. If two are provided then they will be considered for both the real and
imaginary values.

Various mathematical functions are defined in math module and are listed below.
 The ‘ceil(arg1)’ function will return the ceiling value of the argument (arg1)
 The ‘fabs(arg1)’ function will return the absolute value of the input float arg1.
 The ‘abs(arg1)’ function will return the absolute value of the input integer arg1.
 The ‘floor(arg1)’ function will return the floor value of the arg1.
 The ‘copysign(arg1,arg2)’ function will copy the sign of y into x.
 The ‘isinf(arg1)’ function will return the TRUE if arg1 is infinity otherwise returns
FLASE.
 The ‘isnan(arg1)’ function will return the TRUE if arg1 is a NaN otherwise returns
FLASE.
 The ‘exp(arg1)’ function returns the exponential value of arg1.
 The ‘log2(arg1)’ function returns the log2 value of arg1.
 The ‘pow(arg1,arg2)’ function returns the arg1arg2 value.
 The ‘acos(arg1)’ function returns the arc cosine value of arg1.
 The ‘sin(arg1)’ function returns the sine value of arg1.
 The ‘atan(arg1)’ function returns the arc tangent value of arg1.
 The ‘radians(arg1)’ function returns the radian value of arg1(degrees)
 The ‘pi’ is a mathematical constant used to represent the π value
 The ‘e’ is a mathematical constant used to represent the constant value of ‘e’

13
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

1.9. Arithmetic operators and expressions


The arithmetic operators are used to perform the arithmetic operations between any two
operands. Various arithmetic operators are
 The ‘+’ operator is used to perform the addition operation between the two input data
values.
 The ‘-’ operator is used to perform the subtraction operation between the two input data
values.
 The ‘*’ operator is used to perform the multiplication operation between the two input
data values.
 The ‘/’ operator is used to perform the division operation between the two input data
values.
 The ‘%’ operator is used to return the remainder of the division operation performed
between the two input data values.
 The ‘**’ operator is used to compute the exponential calculation.
 The ‘//’ operator is used to perform the floor division operation between the two input
data values. It returns the quotient of the division operation. The decimal points in the
quotient result will be removed. If any one of the input is negative then the quotient result
is rounded towards negative infinity.
For example the two numbers considered are 20 and 10 then the result of
a+b = 30
a-b = 10
a*b = 200
a/b = 2
a%b = 0 (remainder is 0)
a**2 = 400 (202)
-a//b = -2 (a is negative, so the quotient will be rounded to towards negative infinity)
Expressions and order of evaluations
Atom is a basic element of Python expression. An atom can be an identifier or literal. An
Atom also consists of various forms enclosed in brackets, parentheses or braces. Name is an
atom representing an identifier. Both the Byte and String literals are allowed in Python. Multiple
14
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

expressions are separated by comma operator in a parenthesized form. The expressions re


evaluated based on the following Table-1.1.
Table-1.1: Operator Precedence in Python.
S.No. Operator & Description
1 **
2 ~+-
3 * / % //
4 +-
5 >> <<
6 &
7 ^|
8 <= < > >=
9 <> == !=
10 = %= /= //= -= += *= **=
11 Identity operators
12 Membership operators
13 Logical operators

1.10. Comments in the program


In Python, the comments can be specified in any one of the following two ways. They are
 “#” is used to represent the single line comment.
 Multiple line comment statements are started and ended with the “”” delimeter.

1.11. Understanding error messages.


 ParseError
 TypeError
 NameError
 ValueError
 URIError

15
PRAGATI ENGINEERING COLLEGE, SURAMPALEM
(Autonomous)
COMPUTER SCIENCE AND ENGINEERING
B.TECH II YEAR I SEMESTER

 TokenError
 SyntaxError
 TimeLimitError
 IndentationError
 AttributeError
 ImportError
 IndexError
ParseError
Parse errors happen when you make an error in the syntax of your program. Syntax errors
are like making grammatical errors in writing. If you don’t use periods and commas in your
writing then you are making it hard for other readers to figure out what you are trying to say.
Similarly Python has certain grammatical rules that must be followed or else Python can’t figure
out what you are trying to say. Usually ParseErrors can be traced back to missing punctuation
characters, such as parentheses, quotation marks, or commas. Remember that in Python commas
are used to separate parameters to functions. Paretheses must be balanced, or else Python thinks
that you are trying to include everything that follows as a parameter to some function.
TypeError
TypeErrors occur when you try to combine two objects that are not compatible. For
example you try to add together an integer and a string. Usually type errors can be isolated to
lines that are using mathematical operators, and usually the line number given by the error
message is an accurate indication of the line.
NameError
Name errors almost always mean that you have used a variable before it has a value.
Often NameErrors are simply caused by typos in your code. They can be hard to spot if you
don’t have a good eye for catching spelling mistakes. Other times you may simply mis-
remember the name of a variable or even a function you want to call.
ValueError
Value errors occur when you pass a parameter to a function and the function is expecting
a certain limitations on the values, and the value passed is not compatible.

16

You might also like