python_unit_1 (1)
python_unit_1 (1)
IMScIT SEM 5
221601501 INTRODUCTION TO PYTHON
UNIT– I
Introduction to Python
It provides rich data types and easier to read syntax than any other
programming languages
It is a platform independent scripted language with full access to operating
system.
Compared to other programming languages, it allows more run-time flexibility
Libraries in Pythons are cross-platform compatible with Linux, MacIntosh,
and Windows
For building large applications, Python can be compiled to byte-code.
Python supports functional and structured programming as well as OOP
It supports interactive mode that allows interacting Testing and debugging of
snippets of code
In Python, since there is no compilation step, editing, debugging and testing is
fast.
It supports automatic garbage collection.
Web Frameworks for Python
A Web framework is a collection of packages or modules which allow
developers to write Web applications or services without having to handle such
low-level details as protocols, sockets or process/thread management.
Django is the most popular Python framework around, and it’s easy to
understand. Thousands of websites are currently using Django, from daily
newspapers to social media and sharing sites to major foundations and
nonprofits.
Django is known for being fast to build and friendly to beginning programmers.
Web2py easy to learn as Django, but also more flexible and extremely portable.
The same code can run with a SQL database or MongoDB.
The Web2py framework comes with a code editor, debugger, and deployment
tool with which you can develop and debug code, as well as test and maintain
applications.
Web Frameworks for Python
Pyramid as the “Goldilocks” framework, feature-rich without enforcing one
way of doing things, lightweight without leaving you on your own as your app
grows. It’s a favorite framework among many experienced Python developers
and transparency, and has been used by small teams as well as tech giants like
Dropbox, Yelp, SurveyMonkey, and Mozilla.
Other frameworks like Flask, Bottle, Tornado, etc...
Basics of Python
The Python language has many similarities to Perl, C, and Java.
Python files have extension .py.
Assuming that you have Python interpreter set in PATH variable.
This is especially helpful when someone else has written a code and you are analysing it
for bug fixing or making a change in logic, by reading a comment you can understand the
purpose of code much faster then by just going through the actual code.
Ex:- ‘#’ This is just a comment. Anything written here is ignored by Python
Multi-line comment:
To have a multi-line comment in Python, we use triple single quotes at the beginning and
at the end of the comment, as shown below.
Ex:-
'''
This is a
multi-line
comment
'''
Python Keywords and Identifiers
Python Keywords
In Python, keywords are case sensitive. There are 33 keywords in Python 3.12
All the keywords except True, False and None are in lowercase and they must be
written as it is. The list of all the keywords is given below.
Basics of Python
Reserve Keywords
Python Identifiers
Variable name is known as identifier. There are few rules that you have to follow
while naming the variables in Python.
1. The name of the variable must always start with either a letter or an underscore
(_).
For example: _str, str, num, _num are all valid name for the variables.
2. The name of the variable cannot start with a number.
For example: 9num is not a valid variable name.
3. The name of the variable cannot have special characters such as %, $, # etc,
they can only have alphanumeric characters and underscore (A to Z, a to z, 0-9 or
_ ).
4. Variable name is case sensitive in Python which means num and NUM are two
different variables in python.
Python Variables
Equalto sign
Python variables do not need explicit declaration to reserve memory space.
The equal to sign creates new variables and gives them values.
<variable> = <expr>.
It read right to left only.
Multiple assignment:
a=b=c=1
a,b,c = 1,2,"john"
Data Types
Standard Data Types: Data type defines the type of the variable, whether it is an
integer variable, string variable, tuple, dictionary, list etc.
Python data types are divided in two categories, mutable Objects and immutable
Objects.
We can use the type() function to know which class a variable or a value belongs
to.
Complex numbers are written in the form, x + yj, where x is the real part and y is
the imaginary part. Here are some examples.
int (signed integers)
long (long integers, they can also be represented in octal and
hexadecimal)
float (floating point real values)
complex (complex numbers)
Python displays long integers with an uppercase L.
Boolean (bool)
It represents the truth values False and True.
String
String is sequence of Unicode characters.
Follows (left-to- right order) of characters
We can use single quotes or double quotes to represent strings.
Multi-line strings can be denoted using triple quotes, '''.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the string.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
Data Type
List
List is an ordered sequence of items. It is one of the most used datatype in
Python and is very flexible. All the items in a list do not need to be of the same
type.
It is similar to array in C only difference is that elements it contains have
different data type.
We can use the slicing operator [ ] to extract an item from a list. Index starts
form 0 in Python.
Tuple
A tuple is another sequence data type that is similar to the list.
The main differences between lists and tuples are: Lists are enclosed in brackets
( [ ] ) and their elements and size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated.
Tuples are read-only lists.
Tuples are used to write-protect data so it is faster than list as it cannot change
dynamically.
Data Type
Dictionary
Dictionary is an unordered collection of key-value pairs.
They work like associative arrays or hashes found in Perl and consist of key-
value pairs.
A dictionary key can be almost any Python type, but are usually numbers or
strings.
Key and value can be of any type.
It is generally used when we have a huge amount of data.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).
Processing Input and Output
Input/Output
Functions like input() and print() are widely used for standard input and
output operations respectively.
print() function
It is used to output data to the standard output device (screen).
You can write print(argument) and this will print the argument in the next
line when you press the ENTER key
To format our output str.format() method is used.
Syntax of print():
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Processing Input and Output
print() Parameters
objects - object to the printed. * indicates that there may be more than one
object
sep - objects are separated by sep. Default value: ' '
end - end is printed at last
file - must be an object with write(string) method. If omitted it, sys.stdout will
be used which prints objects on the screen.
flush - If True, the stream is forcibly flushed. Default value: False
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4, sep ='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
Processing Input and Output
Enter a number: 10
'10'
Working with Python Files
Import
When program size increases it is divided into different modules.
A module is a file containing Python definitions and statements.
Definitions inside a module can be imported to another module, import
keyword to do this.
Syntax
import module_name
We can also import some specific attributes and functions only, using the
from keyword.
Operators
Operators
Operators are special symbols which represent symbols and perform arithmetic
and logical computations.
The values the operator uses are called operands.
Python supports following types of Operators:
Arithmetic Operators
Comparison/Relational Operators
Assignment Operators
Logical Operators
Membership Operators
Identity Operators
Bitwise Operators
Operators
Arithmetic Operators:
Comparison operators are used to compare values. It either returns True or False
according to the condition.
Operators
Bitwise Operators:
Logical Operators:
Operators
Identity Operators:
is and is not are the identity operators in Python. They are used to check if two
values (or variables) are located on the same part of the memory. Two variables
that are equal does not imply that they are identical.
Operators
Membership Operators:
Creating String
A string is a sequence of characters.
Strings can be created by enclosing characters inside a single quote or double
quotes. Even triple quotes can be used in Python but generally used to
represent multiline strings and docstrings.
var1 = 'Hello World!'
var2 = "Python Programming"
In Python, Strings are stored as individual characters in a contiguous memory
location.
The benefit of using String is that it can be accessed from both the directions in
forward and backward.
Both forward as well as backward indexing are provided using Strings in
Python.
Forward indexing starts with 0,1,2,3,....
Backward indexing starts with -1,-2,-3,-4,....
String
str[0] = 'P' = str[-6]
str[1] = 'Y' = str[-5]
str[2] = 'T' = str[-4]
str[3] = 'H' = str[-3]
str[4] = 'O' = str[-2]
str[5] = 'N' = str[-1].
String
String Functions String Functions
Capitalize
Startwith
Count
Swapcase
Endswith
Lstrip
Find
Rstrip
Index
Isalnum
Isalpha
Isdigit
Islower
Isupper
Isspace
len
Lower
Upper
String Functions
Capitalize():
It capitalizes the first character of the String.
Syntax:
str.capitalize()
Example:
str = "this is string example";
print "str.capitalize() : "
Output:
This is string example
String
count(string,begin,end):
Counts number of times substring occurs in a String between begin and end
index.
Syntax:
str.count(sub, start= 0,end=len(string))
Parameters
sub − This is the substring to be searched.
start − Search starts from this index. First character starts from 0 index.
By default search starts from 0 index.
end − Search ends from this index. First character starts from 0 index.
By default search ends at the last index.
endswith(suffix ,begin=0,end=n):
Returns a Boolean value if the string terminates with given suffix between begin
and end.
Syntax
str.endswith(suffix[, start[, end]])
Parameters
suffix − This could be a string or could also be a tuple of suffixes to look for.
start − The slice begins from here.
end − The slice ends here
isalnum():
It returns True if characters in the string are alphanumeric i.e., alphabets or
numbers and there is at least 1 character. Otherwise it returns False.
Syntax:
str.isalnum()
Isalpha():
It returns True when all the characters are alphabets and there is at least one
character, otherwise False.
Syntax
str.isalpha()
Isdigit():
It returns True if all the characters are digit and there is at least one character,
otherwise False.
Syntax
str.isdigit()
islower():
It returns True if the characters of a string are in lower case, otherwise False.
Syntax
str.islower()
isupper():
It returns False if characters of a string are in Upper case, otherwise False.
Syntax
str.isupper()
isspace():
It returns True if the characters of a string are whitespace, otherwise false.
Syntax
str.isspace()
len(string):
len() returns the length of a string.
Syntax
len( str )
Lower():
Converts all the characters of a string to Lower case.
Syntax
str.lower()
Upper():
Converts all the characters of a string to Upper Case.
Syntax
str.upper()
startswith(str ,begin=0,end=n):
Returns a Boolean value if the string starts with given str between begin and end.
Syntax
str.startswith(str, beg=0,end=len(string));
Parameters
str − This is the string to be checked.
beg − This is the optional parameter to set start index of the matching
boundary.
end − This is the optional parameter to end start index of the matching
boundary.
Swapcase():
Inverts case of all characters in a string.
Syntax
str.swapcase();
lstrip():
Remove all leading whitespace of a string. It can also be used to remove
particular character from leading.
Syntax
str.lstrip([chars])
Parameters
chars − You can supply what chars have to be trimmed.
Output
this is string example..
this is string example..8888888
String
rstrip():
Remove all trailing whitespace of a string. It can also be used to remove
particular character from trailing.
Syntax
str.rstrip([chars])
Parameters
chars − You can supply what chars have to be trimmed.
output
this is string example..
88888888this is string example..
Math and Comparison
Math Module consists of mathematical functions and
constants.
The Python math module provides various values of
various constants like pi, and tau.
Constants
Synatx Description Output
math.pi depicted as either 22/7 or 3.14. math.pi 3.141592653589793
provides a more precise value for the pi
Function Description
Name
ceil(x) Returns Smallest integer not less than x
floor(x) Returns the greatest integral value smaller than the number
pow(x,y) Compute value of x raised to the power y (x**y)
sqrt(x) Returns the square root of the number
factorial(x) Returns the factorial of the number
fabs() Returns the absolute value of the number.
min() Find the minimum value from tuple or list
max() Find the maximum value from tuple or list
String Formating
Formatting Strings
Python uses C-style string formatting to create new, formatted strings. The "%"
operator is used to format a set of variables enclosed in a "tuple" (a fixed size
list), together with a format string, which contains normal text together with
"argument specifiers", special symbols like "%s" and "%d".
The string format() method formats the given string in Python.
String Formating
Formatting Strings:
format() method takes any number of parameters. But, is divided into two types
of parameters:
Positional parameters - list of parameters that can be accessed with index of
parameter inside curly braces {index}
Keyword parameters - list of parameters of type key=value, that can be
accessed with key of parameter inside curly braces {key}
String Formating
Formatting Strings:
Positional Argument
Keyword Argument
String Formating
Formatting Strings:
# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam",
blc=230.2346))
# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))
Output:
Hello Adam, your balance is 230.2346.
Formatting with alignment
Type Meaning
< Left aligned to the remaining space
^ Center aligned to the remaining space
> Right aligned to the remaining space
= Forces the signed (+) (-) to the leftmost position
String formatting with format()
Conversion Functions
int(): string, floating point → integer
float(): string, integer → floating point number
str(): integer, float, list, tuple, dictionary → string
list(): string, tuple, dictionary → list
tuple(): string, list → tuple
Range Function
The built-in range function is very useful to generate sequences of numbers in
the form of a list.
The range() constructor returns an immutable sequence object of integers
between the given start integer to the stop integer.
range() constructor has two forms of definition:
range(stop)
range(start, stop[, step])
range() takes mainly three arguments having the same use in both
definitions
start - integer starting from which the sequence of integers is to be returned
stop - integer before which the sequence of integers is to be returned. The
range of integers end at stop - 1.
step (Optional) - integer value which determines the increment between each
integer in the sequence.
Range Function
x = range(3, 6)
for n in x:
print(n) # 3 4 5
x = range(3, 20, 2)
for n in x:
print(n) # 3 5 7 9 11 13 15 17 19