We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
® Python
Python Character Set
Python uses the character set to declare identifier as given
below:
* Letters A-Z, a-z
* Digits 0-9
* Special Symbols Space +-*/*\()(]{}
1&?_H#<2>=@
White Spaces Blank spaces, horizontal tab, carriage return
Sc>) ose is
® Python
Tokens in Python
The smallest individual unit of the program is known as Token.
There are five types of Tokens in Python:
* Keywords
* Identifiers
* Literals
* Delimiters
* Operators® Python
Keywords
They are the words used by Python interpreter to recognize the
structure of program. As these words have specific meaning for
interpreter, they cannot be used for any other purpose.
A partial list of keywords in Python 2.7 is
and del from not
while as elif global
or with assert else
if pass yield break
except import print class
exec in raise continue
finally is return def
for lambda ty
® Python
Identifiers/Variable names
Identifiers are the name given by the programmer to
objects/parts of a program.
1. Can be of any size
2. It should have allowed characters, which are a-z, A-Z, 0-9 and
underscore (_)
3. It must begin with an alphabet or underscore
4, It should not be a keyword
Itis a good practice to follow these identifier naming
conventions:
1. Variable name should be meaningful and short
2. Generally, they are written in lower case letters® Python
More on variable names
+ Names starting with one underscore (_V) are not
imported from the module import * statement
+ Names starting and ending with 2 underscores are
special, system-defined names (e.g.,__V__)
- Names beginning with 2 underscores (but without
trailing underscores) are local to a class (__V)
- Asingle underscore (_) by itself denotes the result of
the last expression
® Python
Mutable and Immutable Variables
A mutable variable is one whose value may change in place,
whereas in an immutable variable change of value will not
happen in place. Modifying an immutable variable will rebuild
the same variable.
Class Description Immutable? |
bool value ¥ |
int arbitrary magnitude) ¥
float v
list mutable sequence of objects |
tuple immutable sequence of objects v |
str character string ¥ |
set od set of distinct objects |
frozenset | i form of set class ¥ |
dict mapping (aka dictionary) |; ; ® Python
Identifiers / Variable
Identifiers are the name given by the programmer to objects/ parts
of a program.
“variables” in python are really object references.
Every object has:
A. Identity, - can be known using id (object)
Identity of the object: It is the object's address in memory and does not change
once it has been created.
B. type — can be checked using type (object) and
Itis a set of values, and the allowable operations on those values.
c. value
- to bind value to a variable, we use assignment operator (=). This is also known
as building of a variable. Example
>>> pi = 31415
® Python
Operators
Operators are special symbols which represents computation.
They are applied on operand(s), which can be values or variables.
Same operator can behave differently on different data types.
Operators when applied on operands form an expression.
Operators are categorized as
* Arithmetic
* Relational
* Logical
* Assignment
Value and variables when used with operator are known as
operands.® Python
Arithmetic Operators
. Example operators.py | + + addition
print( 2*2) + - subtraction
print( 2**3) / division
ea a) ** exponentiation
Se % modulus (remainder after
pont(it/2) division)
Output: Comparison operators
4
8
1
05
0
+ Note the difference between floating point division and
integer division in the last two lines
@ Python
= Sa Se =o
: magica [sseerae ee Ones Nenara’
100 GoodMorning
Multiplication
7 Division
% Remainder/
Medule 2
Exponentiation
256
tf Integer >=7.0//2 aea3/ /2
Division 3.0 elaRelational Operators.
® Python
| Symbol | Description Example 1 Example?
« Less than >e70 >>>'Hello'< ‘Goodbye’
oon False
Dees
>>>\Goodbye'< ‘Hello’
Fale
True
poe 7>> 7e10 and 1<15
True
> Greater than peeps >>>‘Hello'> ‘Goodbye’
True —
>er10<10
Talce >>>\Goodbye> ‘Hello
False
< lees than equal to >>>‘Hello'<= ‘Goodbye!
Relational Operators
®@ Python
> greater than equal | >>>10>=10 >>>'Hello'>="Goodbye’
to Tme
True
>>> 10>=12
>>>'Goodbye! >= ‘Hello!
False
False
t=, | not equal to >>>l0l=11 >>>’ Hello’ |= HELLO
True
>>>10!=10
False
se equal to >>>10==10 >>>‘Hello’ == ‘Hello’
True ae
>>>: ” . " ’
>>>'Hello’ == ‘Good Bye’
False False® Python
Logical Operators
Description
or If any one of the operand is true, then the condition becomes true.
and If both the operands are true, then the condition becomes true.
not Reverses the state of operand/ condition.
a
@ Python
Assignment Operators
Assignment Operator combines the effect of arithmetic and assignment operator
Symbol Description Example Explanation
Assigned values from right side | >>>x=12"
operands to left variable >>>y="greetings’® Python
added and assign back the result
to left operand
subtracted and assign back the
result to left operand
popat=2
The operand/
expression/
constant written on
RES of operator is
will change the
value of x to 14
multiplied and assign back the
result to left operand
divided and assign back the
result to left operand x/n2
taken modulus using two
operands and asrign the result | 2-2
to left operand
performed exponential (power)
calculation on operators and en
assign value to the left operand
performed. floor division on|x//=2
operators and assign value to
the left operand BSE CS Andrpid Ae
® Python
Precedence of operator - Listed from high precedence to low precedence.
Operator
Description
Exponentiation (raise to the power)
unary plus and minus
Multiply, divide, modulo and floor division
Addition and subtraction
Comparison operators
Equality operators
=,-| Assignment operators
not and or Logical operators® Python
Associative
An operator may be Left-associative or Right
—associative.
+ Inleft associative, the operator falling on left
side will be evaluated first.
Examples: +,-,*,/ are left associate
* In right associative operator falling on right will
be evaluated first. Example "=" and "**" are
Right Associative.
® Python
Literals
* The values which are assigned to variable or are use in
expression or in print statement in a program are
called Literals. Literals can be defined as a data that is
given in a variable or constant.
Python support the following literals:
|. String literals
I.Numeric literals
Ill. Boolean literals
IV. Special literals
V.Literal CollectionsDelimiters
Delimiters are symbols that perform three special roles
in python like grouping, punctuation and assignment/
binging of objects to names. Grouping and punctuation
delimiters are all written as one character symbols.
OO Grouping
eae Punctuation
Searels Arithmetic assignments
= |= A= c= dds Bitwise assignment binding
7
® Python
DATA Types
Data Types
bumbers None Sequences Sets Mappings
Integer Floating Complex Stings Tuple ist
[Paine
Boolean
+ Example Output:
pi= 3.1415926 ,
message = "Hello, world ae
ioe
print( type(pi) )
print( type(message) )
print( type(i) )& Python
Numerical data type
Number data type stores Numerical Values. This data type is
immutable i.e. value of its object cannot be changed (we will talk
about this aspect later). These are of three different types:
a) Integer & Long
b) Float/floating point
c) Complex
®& Python
Integer & Long
* Range of an integer in Python can be from -2147483648 to
2147483647, and long integer has unlimited range subject to
available memory.
* Integers are the whole numbers consisting of + or — sign with
decimal digits like 100000, -99, 0, 17. While writing a large
integer value, don’t use commas to separate digits. Also
integers should not have leading zeros.
* When we want a value to be treated as very long integer value
append L to the value.
>>> b= 5192L #example of a very long value to a variable
>e> c= 4298114
>>>type(c) # type () is used to check data type of value
>>> type(c)
® Python
Boolean
Integers contain Boolean Type which is a unique data type,
consisting of two constants, True & False, A Boolean True value is
Non-Zero, Non-Null and Non-empty.
Example
>>> flag = True
>>> type(flag)
® Python
Float/floating point
Numbers with fractions or decimal point are called floating point
numbers.
A floating point number will consist of sign (+,-) sequence of
decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963.
These numbers can also be used to represent a number in
engineering/ scientific notation.
-2.0X 105 will be represented as -2.0e5
2.0X10-5 will be 2.0E-5
Example
y= 12.36Types and Operators: Types of Numbers (2)
Other numeric types:
Octal constants
Examples: 0177, -01234
-Must start with a leading 0
Hex constants
Examples: 0x9ff, OX7AE
Must start with a leading Ox or 0X
Complex numbers
Examples: 3443, 3.0+4.04, 27
‘Must end in 5 or J
@ Python
-Typing in the imaginary part first will return the complex number in the
order Re+ImJ
Complex
@ Python
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.00.0
Example >>> y =9-5j
>>> print( y.real, y.imag )
9.0-5.0® Python
Sequence
A sequence is an ordered collection of items, indexed by
positive integers. It is combination of mutable and non
mutable data types. Three types of sequence data type
available in Python are Strings, Lists & Tuples.
None
This is special data type with single value. It is used to signify the
absence of value/false in a situation. It is represented by None.
® Python
String:
String is an ordered sequence of letters/characters. They
are enclosed in single quotes (‘‘) or double quotes (“ “).
The quotes are not part of string. They only tell the
computer where the string constant begins and ends.
They can have any character or sign, including space in
them. These are immutable data types. We will learn
about immutable data types while dealing with third
aspect of object i.e. value of object
Example
>>>a='Ram'@ Python
Lists:
List is also a sequence of values of any type. Values in the
list are called elements / items. These are mutable and
indexed/ordered. List is enclosed in square brackets.
Example
| =["spam", 20.5,5]
————————EpEEw Ess
@ Python
Tuples:
Tuples are a sequence of values of any type, and are
indexed by integers. They are immutable. Tuples are
enclosed in (). We have already seen a tuple,
in Example 2 (4, 2).
Sets Set is an unordered collection of values, of any
type, with no duplicate entry. Sets are immutable.
Example
s = set ((1,2,34])® Python
Mapping This data type is unordered and mutable.
Dictionaries fall under Mappings.
Dictionaries: can store any number of python
objects. What they store is a key — value pairs, which are
accessed using key. Dictionary is enclosed in curly
brackets.
Example
d={1:'a',2:'
pou
® Python
While writing Python statements, keep the following points in
mind:
1, Write one python statement per line (Physical Line). Although it is possible to
write two statements ina line separated by semicolon
2. Comment starts with "W" outside a quoted string and ends at the end of a
line. Comments are not part of statement. They may occur on the line by
themselves or at the end of the statement. They are not executed by
interpreter.
3. For a long statement, spanning multiple physical lines, we can use "/" at the
end of physical line to logically join it with next physical line. Use of the "/" for
joining lines is not required with expression consists of (), [], {}
4. When entering statement(s) in interactive mode, an extra blank line is treated
as the end of the indented block.
5. Indentation is used to represent the embedded statement(s) ina compound/
Grouped statement. All statement(s) of a compound statement must be
indented by a consistent no. of spaces (usually 4)
6. White space in the beginning of line is part of indentation, elsewhere it is not
significant.