2020 Chapter 3 FEATURES OF PYTHON
2020 Chapter 3 FEATURES OF PYTHON
FUNDAMENTALS
Python
Character Set
Is a set of valid characters that python can
recognize. A character represent letters, digits
or any symbol. Python support UNICODE
encoding standard. Following are the Python
character
Lett set : A-Z,
ers a-z
Special symbols :space +-*/()~`!@#$
Digi : 0-9
%^
ts & [{
]};:‟”,<.>/?
White spaces : Blank space,
Enter, Tab
Other character : python can
process all ASCII and UNICODE as a part
of data or literal
TOKE
NS
In a passage of text, individual words and
punctuation marks are called tokens or
lexical units or lexical elements. The
smallest individual unit in a program is
known as Tokens. Python has following
tokens:
Keywords
Identifiers(Name)
Literals
Operators
Punctuators
KEYWOR
DS
Keywords are the reserved words and have
special meaning for python interpreter.
Every keyword is assigned specific work
and it can be used only for that purpose.
A partial list of keywords in Python is
Boolean Literals
Literal Collections
String
Literals
It is a collection of character(s) enclosed in
a double or single quotes
Examples of String literals
“Python”
“Mogambo”
□ „123456‟
„Hello How are your‟
□ „$‟, „4‟,”@@”
In Python both single character or multiple
characters enclosed in quotes such as
“kv”, „kv‟,‟*‟,”+” are treated as same
Non-Graphic (Escape)
characters
They are the special characters which
cannot be type directly from keyboard
like backspace, tabs, enter etc. When
the characters are typed they perform
some action. These are represented by
escape characters. Escape characters
are always begins from backslash(\)
character.
List of Escape
characters
Escape What it does Escape What it does
Sequence Sequence
\\ Backslash \r Carriage return
‟\ Single quotes \t Horizontal tab
\” Double quotes \uxxxx Hexadeci
mal
value(16
bit)
\a ASCII bell \Uxxxx Hexadeci
mal
value(32
bit)
\b Back Space \v vertical tab
\n New line \ooo Octal value
String type in
Python
Python allows you to have two string
types:
Single Line Strings
The string we create using single or double
quotes are normally single-line string i.e. they
must terminate in one line.
For e.g if you type as
Name="KV and press enter
Python we show you an error “EOL while scanning
string literal”
The reason is quite clear, Python by default
creates single-line string with both single
quotes and it must terminate in the same line
String type in
Python
Multiline String
Some times we need to store some text
across multiple lines. For that Python offers
multiline string.
To store multiline string Python provides two
ways:
(a)By adding a backslash at the end of
normal Single / Double
quoted string. For e.g.
>>> Name="1/6 Mall
Road \ Kanpur"
>>> Name
'1/6 Mall
String type in
Python
Multiline String
(b) By typing text in triple
quotation marks
for e.g.
>>> Address="""1/7
Preet Vihar New
Delhi
India"""
>>>
print(Address)
1/7 Preet Vihar
New Delhi
India
>>> Address
'1/7 Preet Vihar\
Size of
String
Python determines the size of string as the count of
characters in the string. For example size of string “xyz”
is 3 and of “welcome” is 7. But if your string literal has
an escape sequence contained in it then make sure to count
the escape sequence as one character. For e.g.
String Size
„\\‟ 1
„abc‟ 3
„\ab‟ 2
“Meera\‟s Toy” 11
“Vicky‟s” 7
You can check these size using len() function of
Python. For example
>>>len(„abc‟) and press enter, it will show the
size as 3
Size of
String
For multiline strings created with triple quotes : while
calculating size the EOL character as the end of
line is also counted in the size. For example, if you
have created String Address as:
>>>
Address="""Civil lines
Kanpur"""
>>> len(Address)
18
For multiline string created with single/double
quotes the EOL is not counted.
>>>
data="ab\
bc\
cd"
>>>
Numeric
Literals
The numeric literals in Python can
belong to any of the following
numerical types:
1)Integer Literals: it contain at least one
digit and must not contain decimal point. It
may contain (+) or (-) sign.
Types of Integer Literals:
>>> isMarried=True
>>> type(isMarried)
<class 'bool'>
Special Literals
None
Python has one special literal, which is None. It
indicate absence of value. In other languages it is
knows as NULL. It is also used to indicate the end
of lists in Python.
>>> salary=None
>>> type(salary)
<class 'NoneType'>
Complex
Numbers
Complex: Complex number in python is made up of two
floating point values, one each for real and imaginary part.
For accessing different parts of variable (object) x; we will
use x.real and x.image. Imaginary part of the number is
represented by “j” instead of “I”, so 1+0j denotes zero
imaginary.
part.
Example
>>> x = 1+0j
>>> print
x.real,x.imag 1.0
0.0
Example
>>> y = 9-5j
>>> print y.real,
Conversion from one type to
another
Python allows converting value of one data type to
another data type. If it is done by the programmer
then it will be known as type conversion or type
casting and if it is done by compiler automatically
then it will be known as implicit type conversion.
Example of Implicit type conversion
>>> x = 100
>>> type(x)
<type 'int'>
>>> y = 12.5
>>> type(y)
<type 'float'>
>>> x=y
>>> type(x)
<type 'float'> # Here x is automatically converted to
float
Conversion from one type to
another
Explicit type conversion
To perform explicit type conversion Python provide
functions like int(), float(), str(), bool()
>>> a=50.25
>>> b=int(a)
>>>
print b
50
Here
50.25 is
convert
ed to int
value 50
>>>a=2
Simple Input and
Output
In python we can take input from user using the
built-in function input().
Syntax
variable = input(<message to display>)
Note: value taken by input() function will always be of
String type, so by
default you will not be able to perform any arithmetic
operation on variable.
>>> marks=input("Enter
your marks ") Enter your
marks 100
>>> type(marks)
<class 'str'>
Here you can see even we are entering value 100
Simple Input and
Output
>>> salary=input("Enter
your salary ") Enter your
salary 5000
>>> bonus =
salary*20/100
Traceback (most
recent call last):
File "<stdin>", line
1, in <module>
TypeError:
unsupported operand
type(s) for /: 'str' and
Reading / Input of
Numbers
Now we are aware that input() function
value will always be of string type, but
what to do if we want number to be
entered. The solution to this problem
is to convert values of input() to
numeric type using int() or float()
function.
Possible chances of error
while taking input as
numbers
1.Entering float value while converting to
int
>>> num1=int(input("Enter marks
")) Enter marks 100.5
Traceback (most recent call last): File
"<stdin>", line 1, in <module>
ValueError: invalid literal for int() with
base 10: '100.5‘
Example 2
>>> percentage=float(input("Enter
percentage ")) Enter percentage 100
percent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
„100 percent'
Program
1
Open a new script file and type the
following code:
num1=int(input("Enter
Number 1 "))
num2=int(input("Enter
Number 2 ")) num3 =
num1 + num2
print("Result =",num3)
Let us write few
programs
1. WAP to enter length and breadth and
calculate area of rectangle
2. WAP to enter radius of circle and
calculate area of circle
3. WAP to enter Name, marks of 5 subject
and calculate total & percentage of
student
4WAP to enter distance in feet and
convert it into inches
5WAP to enter value of temperature in
Fahrenheit and convert it into Celsius.
6WAP to enter radius and height of
cylinder and calculate volume of
cylinder.
Operato
rs
are symbol that perform specific
operation when applied on variables.
Take a look at the expression: (Operator)
10 + 25 (Operands)
Above statement is an expression
(combination of operator and
operands)
i.e. operator operates on operand. some
operator requires two operand and some
requires only one operand to operate
Types of
Operators
Unary operators: are those operators
that require one operand to operate
upon. Following are some unary
operators:
Operator Purpose
+ Unary plus
- Unary minus
~ Bitwise
complement
Not Logical negation
Types of
Operators
Binary Operators: are those that
operand to
operators require two upon.
operate Following are some Binary
operators:
1. Arithmetic
Operator Action
Operators + Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Exponent
// Floor division
Examp
le
>>> num1=20
>>> num2=7
>>> val = num1 %
num2
>>>
print(val) 6
>>> val =
2**4
>>>
print(val)
16
>>> val =
num1 /
num2
>>> print(val)
2.857142857142
857
Bitwise
operator
Operat Purpose Action
or Bitwise operator
works on the
& Bitwise Return 1 if both binary value of
AND inputs are 1 number not on the
^ Bitwise Return 1, if actual value. For
XOR the example if 5 is
number of passed to these
1 in input operator it will work
on 101 not on 5.
is in odd
Binary of
| Bitwise OR Return 1 if 5 is 101, and return
any input the result in
is 1 decimal not in
binary.
Examp
le Binary of 12 is 1100 and 7 is 0111, so
applying &
1100
0111
Guess the output
-------
with
0100 Which is equal to decimal value 4
| and ^ ?
Let us see one practical example, To check whether entered number is
divisible of 2 (or in
a power of 2 or not) like 2, 4, 8, 16, 32 and so on
To check this, no need of loop, simply find the bitwise & of n
and n-1, if the result is 0 it means it is in power of 2
otherwise not
Identity
Operators
Operators Purpose
is Is the Identity same?
is not Is the identity not same?
Relational
Operators
Operators Purpose
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal
to
== Equal to
!= Not equal to
Logical
Operators
Operators Purpose
and Logical AND
or Logical OR
not Logical NOT
Assignment
Operators
Operators Purpose
= Assignment
/= Assign quotient
+= Assign sum
-= Assign difference
*= Assign product
**= Assign Exponent
//= Assign Floor division
Membership
Operators
Operators Purpose
in Whether
variable in
sequence
not in Whether variable
not in sequence
Punctuat
ors
Punctuators are symbols that are used in
programming languages to organize
sentence structure, and indicate the
rhythm and emphasis of expressions,
statements, and program structure.
Common punctuators are: „ “ # $ @ []
{}=:;(),.
Barebones of Python
It means basic structure of a
Program
Python program
Take a look of following code:
#This program shows a program‟s
component # Definition of function
SeeYou() follows Comme
def SeeYou(): nts
print(“This is my Functi
function”) on
#Main program
A=10
C=A+B Expressi
Stateme
B=A+20 Inline
if(C>=100) ons #checking
Comment
condition
print(“Value is equals or more
nts
than 100”)
else: print(“Value is less Blo
Indentat
print(“Welcome to python”)
The above statement call print function
When an expression is evaluated a
statement is executed
i.e. some action takes place.
a=100
b = b + 20
Comme
nts
Comments addition information
are al
is not executed
written by in a
program interpreter
ignored by Interpreter. i.e.
Comment
which
contains information regarding statements
used, program flow, etc.
Comments in Python begins from #
comments:
1. Full line comment
2. Inline comment
3. Multiline comment
Comme
nts
Full line comment
Example:
#This is program of
volume of cylinder
Inline comment
Example
area = # calculating area of
length*breadth rectangle
Multiline
#comment
Program name:
Example 1
area of circle # Date:
(using #)
20/07/18
#Language : Python
Comme
nts
Multiline comment (using “ “ “)
triple quotes
Example
“““
Program :name
Dat : swapping of
20/07/18
two
e number
: by using third
”” Log variable
” ic
Functi
ons
Function is a block of code that has name
and can be reused by specifying its name in
the program where needed. It is created
with def keyword.
Example
def drawline():
print(“=================
=====“)
print(“Welcome to
Python”)
drawline()
print(“Designed by
Block and
Indentation
Group of statement is known as block
like function, conditions or loop etc.
For e.g.
def area():
a = 10
b=5
c=a*b
Indentation means extra space before writing
any statement. Generally four space
together marks the next indent level.
Variabl
es
Variables are named temporary location
used to store values which can be further
used in calculations, printing result etc.
Every variable must have its own Identity,
type and value. Variable in python is created
by simply assigning value of desired type to
them.
For e.g
Num = 100
Name=“James”
Variabl
es
Note: Python variables are not storage
containers like other programming
language. Let us analyze by example.
In C++, if we declare a variable radius:
radius = 100
[suppose memory
address is 41260] Now we
again assign new value to
radius
radius = 500
Variabl
es
Now let us take example of
Python:
radius = 100 [memory address 3568]
Examples:
Multiple
Assignments
x,y,z = 10,20,30 #Statement 1
z,y,x = x+1,z+10,y-10 #Statement 2
print(x,y,z)
Output will be
10 40 11
Now guess the output of following
code fragment x,y = 7,9
y,z = x-2,
x+10
print(x,y,z)
Multiple
Assignments
Let us take another example
y, y = 10, 20
x=100 x int:
x=“KVi 100
ans” int:1
00
x
string:KVi
ans
Caution with Dynamic
Typing
Always ensure correct operation during
dynamic typing. If types are not used
correctly Python may raise an error.
Take an
example x =
100
y=0
y=x/2
print(y)
x='Exa
Determining type of
variable
Python provides type() function to
check the datatype of variables.
>>> salary=100
>>> type(salary)
<class 'int'>
>>> salary=2000.50
>>> type(salary)
<class 'float'>
>>> name="raka"
>>> type(name)
<class 'str'>
Output through
print()
Python allows to display output using
print().
Syntax:
print(message_to_print[,sep=“string”,
end=“string”])
Example 1
print(“Welco
me”)
Example 2
Age=20
print(“Your
Output through
print()
Example 3
r = int(input("Enter
Radius ")) print("Area of
circle is ",3.14*r*r)
string
„\a‟ , “\a” , “Reena\‟s”, „\”‟, “It‟s”, “XY\
,““
“XY
YZ” YZ”””
How many types of String in python?
Just a
minute…
What are the different ways to declare
multiline String?
Identify the type of following literal:
Statement
What is the error inn following python
program:
print(“Name is “, name)
Just a
minute…
Which of the following string will be the
syntactically correct? State reason.
1. “Welcome to India”
2. „He announced “Start the match” very
loudly‟
3. “Sayonara‟
4. „Revise Python Chapter 1‟
5. “Bonjour
6. “Honesty is the „best‟ policy”
Just a
minute…
The following code is not giving desired
output. We want to enter value as 100
and obtain output as 200.
Identify error and correct the program
num = input("enter
any number")
double_num = num * 2
Print("Double
of",num,"is",double_nu
m)
Just a
minute…
Why the following code is
giving error?
Name="James"
Salary=200
00
Dept="IT"
print("Name is
",Name,end='@') print(Dept)
print("Salary is ",Salary)
Just a
minute…
WAP to obtain temperature in Celsius and
convert it into
Fahrenheit.
What will be the output of following code:
x, y = 6,8
x,y = y, x+2
print(x,y)
What will be the output of following code:
x,y = 7,2
x,y,x = x+4, y+6, x+100
print(x,y)