Module - 1 INTRODUCTION TO PYTHON
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.
Elements of python language
Source characters-Set of valid characters that a programming
language can recognize.
1.Alphabets uppercase(A-Z) and lowercase(a-z), underscore(_)
2.Special characters(+,-,*,/,^,~,%,!,&,|,(),{},[],?,’,;,\,blank(“ “) )
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
{, }, [, ], ;, :,
Python block structure
Python program is a set of statements called block, i.e group of
statements.
In python block it has statements, comments and while writing
statements it follows indentation.
Indentation:
It refers to white spaces(Tab and spaces)in a python program.It is not
programming style.
In C use curly braces to structure a block
Ex: total =0
for i=1 to 10
{
total =total + i;
}
In python there are no curly braces. Instead uses indentation
total= 0
for i=1 to 10
total = total + I
The amount of white spaces used is up to the user.to ensure uniformity
and readability four spaces or a tab is often used.mixing Tab and space
bar is not desirable as it may cause syntax error.
Comments in python
Comments are helpful to explain code and context. Python provides a
single option to give comments using the symbol(#). Python interpreter
ignores the comments.
Variables and Assignment statement
Variable:
A variable is a memory location where a programmer can store a value.
Example : roll_no, amount, name etc.
Value is either string, numeric etc. Example : "Sara", 120, 25.36
Variables are created when first assigned.
Variables must be assigned before being referenced.
The value stored in a variable can be accessed or updated later.
No declaration required
The type (string, int, float etc.) of the variable is determined by Python
The interpreter allocates memory on the basis of the data type of a
variable.
Python Variable Name Rules
•Must begin with a letter (a - z, A - B) or underscore (_)
•Other characters can be letters, numbers or _
•Case Sensitive
•Can be any (reasonable) length
There are some reserved words which you cannot use as a variable
name because Python uses them for other things
Assignment statement
The assignment statement creates new variables and gives them values
Syntax:
<variable> = <expression>
EX:
>>> Item_name = "Computer“ #A String
>>> Item_qty = 10 #An Integer
>>> Item_value = 1000.23 #A floating
>>> print(Item_name)
Computer
>>> print(Item_qty)
10
>>> print(Item_value)
1000.23
Syntax for multiple assignment:
<var1>, <var2>, ..., <var n> = <expr 1>, <expr 2>, ...,<expr n>
Example for multiple assignment
>>> x , y = 10 ,20
>>> x,y=y,x
>>>print(x,y)
(20,10)
Python swap values in a single line and this applies to all objects in
python.
Syntax:
var1, var2 = var2, var1
Dynamic type checking:
In python does not require one to declare variables before it is used.
Static typing:
Variable needs to be declared before it is used. Ex C language
Python data types
Data type indicates what values a variable can hold. Data types are the
classification or categorization of data items.It represents the kind of
value that is assigned to variables.
Example:
x=3
here ‘x’ is integer variable as 3 is a whole number and an integer
Python Data types
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’>
A is sequence ordered collection of values. Elements in sequence are
stored as series of memory locations i.e indexed from 0 to n-1
Three Types:
1.A string is a sequence of characters
2.A list is a sequence of values
3.A tuple is a sequence of values like lists but a tuple is immutable
Common operations on the sequence are
1.Membership operation i.e element is present or not
2.Concatenation i.e combined the sequence seq1 + seq2
3.Slicing like [start index:end index]
4.Built-in-operations like len(),max(),min(),sorted(),reversed()
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
// - returns integer quotient of an integer division
% - return remainder of integer division
** - used for exponentiation
Types of arithmetic expressions are
Constant expressions i.e ex: 7+3
Integer and floating-point expressions involving variables i.e ex: a*b/2
Examples of arithmetic operators
>>> 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 precedence and associativity
Operator precedence: It is the way operations are carried out.
This is summarized by rule PEMDAS.
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.
Comparison or Relational Operators
Comparison operators are used to compare two values and
returns Boolean value ( True or False).Condition for a decision can be
created using a relational operator.All relational operators are having
the same precedence as relational operators are not associative
Example:
>>>7<9
True
>>>7==9
False
Boolean or logical Operators
Python BIT-WISE Operators
Bit-wise operators are used to compare binary bit numbers. It operates
bit by bit.
Examples:
>>>bin(10)
‘ob1010’
>>>bin(9)
‘ob1001’
>>>10&9
8
Python Identity Operators
Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory
location
Operators Meaning
is Check whether two objects are the same or not. Returns True if objects same
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
Python Membership Operators
Membership operators test whether the given object is in the
collection or not.
Operator meaning
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
# Program to check input type in Python
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)
# Printing type of input value
print ("type of number", type(num))
print ("type of name", type(name1))
Output:
Enter number :1234
1234
Enter name : python
python
type of number <class 'str'>
type of name <class 'str'>
Python | Output using print() function
Python print() function prints the message to the screen or any
other standard output device.
Syntax : print(argument)
Argument can be integer, float, string or any other data type
Ex:
print(‘hello’) ,print(“this is correct”) -->double and single do for printing
more than one argument
print( x)---> variable can print directly
print(100)---> numbers can print directly
Ex: # printing multiple line
a = 10
b = “this is a string”
print(a,b)
10 this is a string
Extension of print statement
Two important flags:
Sep : separator use +,:,, and by default space
End: end and by default \n
Example for “sep”
print(“I am” , “from”, “India” , sep=“,”)
Example for “end”
a= 100
b= 200
print(a,b) #100 200
print(a,end=‘,’)
print(b) #100,200
Formatting print statement
Some application require fancy printing as per requirements called
formatting.All variables and constants need to be converted to string
type for printing purpose.There are several ways to format output using
String Method in Python.
1.Formatting output using String modulo operator(%)
2.Formatting output using format method
3.Formatting output using String Literals(F- string or f- string)
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
%i and %d Signed decimal integer
%u Unsigned decimal integer
%o Octal integer
%x and %X Hexadecimal integer
%e and %E Exponential notation
%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
Example for string
>>>country =“Independent India”
>>>age = 75
>>> print(“%s is %d years old” % (country, age))
2.string formatting using format() method
Syntax: format(value, specifications)
Here it use {} a named replacements or placeholders
The print() searches for the place holders and if it is not available,
it print as it is without formatting
1.Examples:
Value = 17.3733333
print(‘value= ‘,format(value,’0.3f’))---#17.373
print(‘value= ‘,format(value,’3.2e’))---#1.74e+01
print(‘value= ‘,format(value,’3.2E’))---#1.74E+01
2.Examples:
student= “raghu”
RollNo = 200010
print(“{},Reg number {}”.format(student,RollNo))
O/P:raghu, 200010
3.Example :
‘{0} {1}’.format(‘Name’,’is’)
‘name is’
‘{1}{0}’.format(‘Name’,’is’)
‘is Name’
3.Formatting output using String Literals(F- string or f- string)
Start with f or F at the beginning of the string.{} are placeholders
that hold the expressions that are replaced by the values. It simplifies
string interpolation.¡It make string formatting faster, more readable,
more concise and less error
>>>country = “Independent India”
>>>age = 75
>>>print(‘f{country} is {age} years old’)
# Independent India is 75 years old