Module 1
Module 1
What is Python?
Python is an open source, object-oriented, high-level powerful
programming language.
Developed by Guido van Rossum in the early 1990s. Named after
“Monty Python Flying Circus” series.
Python runs on many Unix variants, on the Mac, and on Windows
2000 and later.
Python Program:
Python programs are composed of modules.Modules contain
statements.Statements contain expressions.Expressions create and
process objects.
Tokens:
•It is smallest lexical unit in a program.
•It is separated by a space, tab or carriage return collectively called
white spaces.
•Types of tokens are:
1. Identifiers
2. Keywords
3. Literals
4. Punctuation
Identifiers:
•The names that represent programmable entity in Python
•In python , all variables, objects & functions are given a name. that
name is identifiers.
•Ex: i=0, where ‘i ’ is variable assign by value 0
•The programmers choose self explanatory meaningful names
•Certain rules govern how a name can be given are
1. Every identifier must start with a letter or underscore(_)
2. The letter or underscore can be followed by any sequence of letters,
digits or underscore
3. Identifiers cannot have space
4. Identifiers are case sensitive. Ex, Celsius, CELSIUS, Celsius are different
Keywords :
Keywords in Python are reserved words that can not be used as a
variable name, function name, or any other identifier.
import keyword
print(keyword.kwlist)
Literals:
•Constant or constant values, are other name for literals.
•Literals in Python are numbers, text or other data type depict values
stored in variables.
•Python manipulate constants by assigning them to variables and then
manipulate
Types of literals:
•String literals: text and constant strings
•Composed using ‘ ‘, “ “, and “’ “’
•Spaces, special characters, keywords placed inside the quotes are
treated as literals
Numerical literals : Three types
1.Integer: whole numbers 25,36,1487
2.Floating-point numbers: fractional numbers with decimal points
12.3,3.14
3.complex numbers:4+32j and 7+2j
Boolean literals: Boolean literals are False (0) and True(1)
Punctuates or delimiters
•These symbols can serve as a separators of values
•Used to enclose a set of values
{, }, [, ], ;, :,
1.Numbers
Integers: Int or integers are primary data types.
+ive or –ive number( Ex: 233, -754)
Decimal integers whose base 10( Ex:45,-96, 128)
Octal integers whose base 8(0O or 0o)
Hexadecimal numbers whose base 16((0X or 0x)
Float number:Decimal point numbers +ive or–ive numbers
( -14.36,3.14)
Complex numbers: Extensions of floating –pint numbers with real
and imaginary parts. Ex: >>>complex(3,4)
3+4j
2.Boolean types
Refers to True and False. Represented by integers as 0 and 1. Boolean
variable hold boolean values
Example
>>>time_up=True
>>>time_up
True
Function called bool() that covert values to boolean.
Ex: bool(1)
>>> True
3.None type
Indicates no value.Null in C, in python it is None
Example:
>>>type(None)
<Class ‘NoneType’>
1.Strings :
Collection of characters.Delimited by single, double and triple quotes.
Include letters, numbers, punctuation and many special/unprintable
characters.
Example: “lion” , ‘14.0’
2. Lists:
Set of items or elements. Similar to array but have non-
homogeneous content.It is mutable as items can be changed.
To create a list, one can just enclose the sequence of objects in
square brackets.List can be a collection of integers, strings and floating
values.Lists are indexed and contents are accessed.
Ex:lst1=[‘hello’,”morning”,13,67.9]
0 1 2 3
>>>lst1[2]
13
>>>lst1[1:3]
[‘hell0’,13]
Some of the list operations are adding,insertion,deletion of items
and lists.
3.Tuples:
Collection of items or elements.Tuple is sort of list but tuple is
immutable i.e cannot change the elements or size in a tuple.
To generate tuples, just enclose the sequence of objects in round
brackets () and separated by comma.It support indexing/slicing and one
cannot change the elements. Supports operations like
indexing,slicing,combining tuples,deletion,insertion and deletion of
elements in the tuple.
Example: >>>tup1=(‘a’,’b’,’c’,’d’,’k’,’m’)
>>>print(tup1)
(‘a’,’b’,’c’,’d’,’k’,’m’)
4.Bytes and byte arrays
Immutable object that stores a long sequence of values from 0 to
255.
Useful for encoding ASCII,Unicode 0 UTF-8,UTF-16,images such as
JPEG,PNG and audio files like MP3
Ex: >>>x=b’Hello’
>>>x
b’Hello’
5.Sets/frozen sets
It is an unordered collection of zero or more elements with no
duplicates with curly braces { }.The set is immutable and unique.
Ex: >>>lst = {“red”,”red”,”green”}
>>>lst1=set(1st)
>>>print(1st1)
{red’,’green’}
6.Dictionary
It is an unordered collection of items in the form of keys and
values called mapping type. Created by sequence of key-value pairs with
curly brackets {} and colon.(,) to separate key-value pairs. Colon (:) is
used to separate key and value.
Ex:
>>>pwd = {‘abc’:’123’,’def’:’456’}
>>>pwd
{‘abc’:’123’,’def’:’456’}
Operations are creation of a dictionary, adding elements to the
dictionary, removing the elements of the dictionary, and deletion of
dictionary
Python operators
Operators are special symbols which represent computations,
conditional matching etc on variables and values.The values the
operator uses are called operands.Operation is depends on datatype.
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform
common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x–y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
>>> 3+4
7
>>>3/2
1.5
>>>4*6
24
>>>14//3
4
>>>17.3//3
5.0
>>>13%3
1
>>>13.2%4
1.1999999999993
>>>2**4
16
Operator Associativity:
If an expression contains two or more precedence, then
associativity have to use.
Two types:
1.Left-to-right associativity
2.Right-to-left associativity
Ex:20 + (3+12)+2**4
= 20 + 15 +2**4
= 20 + 15 + 16
= 51
Compound Assignment Operators
Assignment operators are used to assign values to variables.
Examples:
>>>bin(10)
‘ob1010’
>>>bin(9)
‘ob1001’
>>>10&9
8
is not Check whether two objects are and Returns True if objects are not same
Examples:
1.>>>t1 = 7
>>>t2 = 8
>>>t1 is t2
False
2.>>>t1 = 7
>>>t2 = 8
>>>t1 is not t2
True
in Checks whether object is present in the collection. Returns True if the object is present
not in Checks whether object is not present in the collection. Returns True if the object is not prese
Example:
1.>>>1=[‘red’,’white’,’hack’]
>>>print(‘red’ in 1)
True
2. >>>print(‘brown’ in 1)
False
Operator precedence
Simple input /output print statements
Two I/O statement functions are:
1.input()
2.print()
Reading numbers from keyboard
1.Using input() function one can read the input from the console.
Syntax: var=input()
Input() function produces only string. To avoid error have to use
typecasting.
1. Typecasting the input to Integer
num1 = int(input('enter a num'))
2. Typecasting the input to Float:
num1 = float(input('enter a num'))
eval() function:
We can also use eval(): Takes a string and treats it as a python
expression.
It accepts a number(int,float, string, or complex) and determines the
type of value entered by the user.
Example:
>>>x = eval(input(“enter the number”))
enter the number 10
>>>x=x+10
>>>print(x)
20
String interpolation
It is the way of combining a string with constants or variables at
specific locations to create a user-defined output. This replacements is
called placeholder(%).
1.Formatting output using String modulo operator(%)
¢Useful string format symbol with conversion
Symbol Conversion
%s string
%o Octal integer
%f Floating point
Example:
#integer and float value
print("integer : % 2d, float : % 5.2f" %(1, 05.333))
#integer value
print("Total Player : % 3d, Batsman : % 2d" %(24, 12))
#octal value
print("% 5.3o"% (50))
#exponential value
print("% 10.2E"% (456.1458))
O/P:
integer : 1, float : 5.33
Total Player : 24, Batsman : 12
062
4.56E+02