Unit-2
Chapter -6: Getting Started With Python
Python: It is widely used general purpose, high level
programming language Developed by Guido van
Rossum in 1991.
It is used for:
• Software development,
• Web development (server side),
• System scripting,
• Mathematics.
Why Python?
• Pythonworks on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Pythonhas syntax that allows developers to write programs
with fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code
can be executed as soon as it is written. This means that
prototyping can be very quick.
• Python can be treated in a procedural way, an object-
oriented way or a functional way.
Features of Python
Easy to use as simple syntax rule
Interpreted language Code execution & interpretation
line by line
Cross platform language It can run on windows,
Linux, Macintosh etc. equally
Expressive language Less code to be written as it
itself express the purpose of the code.
Completeness Support wide range of library
Free& Open Source Can be downloaded freely and
source code can be modify for improvement.
Shortcomings of Python
1. Lesser libraries as compared to other
programming languages like c/ c++, java,. Net
2. Slow language as it is interpreted languages,
it executes the program slowly.
3. Weak on Type binding It not pin point on use
of a single variable for different data type.
Python Character Set
A set of valid characters recognized by python. Python uses the
traditional ASCII character set. The latest version recognizes the
Unicode character set.
The ASCII character set is a subset of the Unicode character set.
Letters: – A-Z, a-z
Digits: – 0-9
Special symbols: – Special symbol available over keyboard
(?,@,#,$,%,^,&,*,**.~)
White spaces: – blank space, tab, carriage return, new line, form
feed
Other characters: - Unicode
How to work in Python
After installation of python ,we can work on it in
following ways
(i) in Interactive mode
(ii) in Script mode
Token
Smallest individual unit in a program is known
as token.
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators/Delimiters
Keywords
Keywords, also known as reserved words, are a type of
predefined tokens in a programming language that have
special meanings and purposes. These words are reserved
by the language and cannot be used as variable names or
any other identifiers
i.e. and, exec, not, as, finally, or, assert, for, pass, break,
from, print, class, global, raise, continue, if, return, def,
import, try, del, in, while, elif, is, with, else, lambda, yield,
except etc.
Identifiers
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 more letters, underscores and digits (0 to 9).
Python does not allow special characters
Identifier must not be a keyword of Python.
Python is a case sensitive programming language.
Thus, Rollnumber and rollnumber are two different identifiers in
Python.
Some valid identifiers: Mybook, file123, z2td, date_2, _no
Some invalid identifier: 2rno, break, my.book, data-cs
Literals
Literals in Python can be defined as number, text, or other data that
represent values to be stored in variables.
Example of String Literals in Python name = ‘Johni’ , fname
=“johny”
Example of Integer Literals in Python(numeric literal) age = 22
Example of Float Literals in Python(numeric literal) height = 6.2
Example of Special Literals in Python Literals:
Escape sequence/Back slash character constants
Escape Sequence Description 1. \\- Backslash (\) 2.\’ :Single quote
(‘) 3.\" :Double quote (") 4. \a: ASCII Bell (BEL) 5. \b: ASCII
Backspace (BS) 6.\f: ASCII Formfeed (FF) 7. \n: ASCII Linefeed (LF) 8.
\r: ASCII Carriage Return (CR) 9.\t: ASCII Horizontal Tab (TAB) 10.\v:
ASCII Vertical Tab (VT) 11.\ooo: Character with octal value ooo 12. \
xhh: Character with hex value hh
Operators
Operators can be defined as symbols that are used to
perform operations on operands.
Types of Operators:
1. Arithmetic Operators (+, -, *, /, %, **,//)
2. Relational Operators (> ,<,>=, <=,==,!=)
3. Assignment Operators(=)
4. Logical Operators (and, or, not)
5. Bitwise Operators (&,|,!,~)
6. Membership Operators (in, not in)
7. Identity Operators (is , is not)
Python Datatype
A Python data type defines the type of data stored in
a variable.
Following are the standard or built-in data type of
Python:
1. Numeric
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
Data types are the classification or categorization of data items.
It represents the kind of value that tells what operations can be performed on a
particular data.
Numeric
i. Integers ii. Floating point iii. Complex Number
Integer: Integers or int are positive or negative numbers with no
decimal point. Integers in Python 3 are of unlimited size. e.g. a= 100
b= -100 c= 1*20
Floating point numbers: It is a positive or negative real number with a
decimal point. e.g. a = 101.2 b = -101.4 c = 111.23 d = 2.3*3
Complex numbers: Complex numbers are combination of a real and
imaginary part. Complex numbers are in the form of X+Yj, where X is a
real part and Y is imaginary part. e.g. a = complex(5)
# convert 5 to a real part val and zero imaginary part print(a)
b=complex(101,23)
Sequence Type
String: In Python A string is a sequence of
characters. In python we can create string using single
(' ') or double quotes (" "). Both are same in python.
e.g. str='computer science' print('str-', str) # print
string print('str[0]-', str[0]) #
List: In Python List are collections of items and each
item has its own index value.
Tuple: In Python List and tuple, objects mean you
cannot modify the contents of a tuple once it is assign
both are same except ,a list is mutable python objects
and tuple is immutable Python objects.
Boolean: It is used to store two possible values
either true or false e.g. str="comp sc"
b=str.isupper()
Set :In Python It is an unordered collection of
unique and immutable (which cannot be
modified)items. e.g. set1={11,22,33,22}
Dictionary: In Python It is an unordered collection
of items and each item consist of a key and a
value. e.g. dict = {'Subject': 'comp sc', 'class': '11'}
print(dict)
Input and Output
Understanding input and output operations is fundamental to Python
programming.
Python Support input value from user via keyboard using two type of
function are :
1. raw_input():
2. input():
1. raw_input(): Function In Python allows a user to give input to a
program from a keyboard but in the form of string.
e.g. age = int(raw_input(‘enter your age’))
percentage = float(raw_input(‘enter percentage’)
2. input() : Function In Python allows a user to
give input to a program from a keyboard but
returns the value accordingly. Input value need
to be convert into numerical form for calculation.
e.g.
age = int(input(‘enter your age’))
C = age+2 #will not produce any error
NOTE : input() function always enter string value
in python 3.so on needint(),float() function can
be used for data conversion.
Practice Questions
Q1. Write invalid identifiers from the following:
1_dt, true, sam, d-o-b, pass, goto#, a2z, to20,
False
Q2. Identify the error(s) in the following code and re-write correct code:
a=true # a=True
b=False
if (a=b): # if(a==b):
print(b, sep ‘@’) # sep=‘@’
Else # else:
Print(a, end “#”) # print(a,end=‘#’)
Q3. What will be the output of the following snippet?
x, y = 2, 6
x, y = y, x + 2
a=”x”
b=y+1
print(x, a)
print(y, b)
Observe the following code and write the missing statements:
m=___________ #Statement 1
km=_____________ #Statement 2
print(___________) #Statement 3
print(______________) #Statement 4
a) Write statement to accept an integer value – Statement 1
b) Write statement to convert miles to km – Statement 2
c) Write statement to print entered miles with appropriate text – Statement
3
d) Write statement to print kms with appropriate text – Statement 4
Find the error in the following code: c)
a) temp==90
y=x+5 print temp
z+10=z d)
print(z,”\n”, Y) a=10;
b=20
b) print( a And b)
a=10 e)
b=a-5*2 a, b, c=2, 8, 4
c=a/b print(a, b, c)
print(C=,c) c, b, a = a b c
print(a; b; c)
What keyword would you use to add an alternative condition to an if
statement?
a) else if b) elseif c) elif d) None of the above
What will be the data type of the var in the below code snippet?
var = 10
print(type(var))
var = "Hello"
print(type(var))
a) int and str
b) int and int
c) str and str
d) float and str
What will be the output of the following code snippet?
print(type(5 / 2))
print(type(5 // 2))
a) int and int
b) str and str
c) int and float
d) float and int
How will the following expression be evaluated in Python?
15.0 / 4 + (8 + 3.0)
Type conversion
The process of converting the value of one
data type (integer, string, float, etc.) to
another data type is called type conversion.
Python has two types of type conversion.
i. Implicit Type Conversion
ii. Explicit Type Conversion
1. Implicit type conversion: In Implicit type conversion, Python
automatically converts one data type to another data type. This
process doesn't need any user involvement.
e.g.
num_int = 12
num_flo = 10.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
OUTPUT
print("datatype of num_new:",type(num_new)) ('datatype of num_int:', )
('datatype of num_flo:’, )
('Value of num_new:',
22.23)
('datatype of num_new:', )
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.
e.g.
num_int = 12
num_str = "45"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
OUTPUT
num_sum = num_int + num_str
('Data type of num_int:', <type 'int'>)
('Data type of num_str before Type Casting:',
print("Sum of num_int and num_str:",num_sum)
<type 'str'>)
print("Data type of the sum:",type(num_sum))
('Data type of num_str after Type Casting:',
<type 'int'>)
('Sum of num_int and num_str:', 57)