Python Notes - Unit1
Python Notes - Unit1
1. Web development – Web framework like Django and Flask are based on Python.
They help you write server side code which helps you manage database, write backend
programming logic, mapping urls etc.
2. Machine learning – There are many machine learning applications written in Python.
Machine learning is a way to write a logic so that a machine can learn and solve a
particular problem on its own. For example, products recommendation in websites like
Amazon, Flipkart, eBay etc. is a machine learning algorithm that recognises user’s
interest. Face recognition and Voice recognition in your phone is another example of
machine learning.
3. Data Analysis – Data analysis and data visualisation in form of charts can also be
developed using Python.
7. Desktop applications – You can develop desktop application in Python using library
like TKinter or QT.
8. Scientific and Numeric Applications : Python has become a crucial tool in scientific
and numeric computing. In fact, Python provides the skeleton for applications that deal
with computation and scientific data processing. Apps like FreeCAD (3D modeling
software) and Abaqus (finite element method software) are coded in Python.
Features of Python programming language
2. Easy to Learn: Learning python is easy as this is a expressive and high level
programming language, which means it is easy to understand the language and thus
easy to learn.
3. Cross platform: Python is available and can run on various operating systems such
as Mac, Windows, Linux, Unix etc. This makes it a cross platform and portable
language.
5. Large standard library: Python comes with a large standard library that has some
handy codes and functions which we can use while writing code in Python.
6. Free: Python is free to download and use. This means you can download it for free
and use it in your application.. Python is an example of a FLOSS (Free/Libre Open
Source Software), which means you can freely distribute copies of this software, read its
source code and modify it.
Python Versions :
Best approach is to type the program into an editor, save the code you type to a file,
and then execute the program. Most of the time we use an editor to enter and run our
Python programs. The interactive interpreter is most useful for experimenting with
small snippets of Python code. There are two ways to write python program.
(ii) enter the program into IDLE’s editor, save it, and run it.
Python Identifiers :
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another. Rules for naming identifiers :
Numeric : In Python, numeric data type represent the data which has numeric value.
Numeric value can be integer, floating number or even complex numbers. These
values are defined as int, float and complex class in Python.
• Float – This value is represented by float class. It is a real number with floating
point representation. It is specified by a decimal point. Optionally, the character e or
E followed by a positive or negative integer may be appended to specify scientific
notation.
type() function is used to determine the type of data type. For example
>>> type('abc')
<class 'str'>
>>> type(3)
<class 'int'>
>>> type(3.2)
<class 'float'>
>>> type(3+4j)
<class 'complex'>
>>>
Built-in Functions
A numeric object of one type can be converted in another type using
the following functions:
int Returns the integer object from a float or a string containing digits.
abs Returns the absolute value of a number without considering its sign.
• String
• List
• Tuple
Example :
str="HELLO"
print(str)
print(type(str))
#print first character of string
print(str[0])
#print last character of string
print(str[-1])
#print second last character of string
print(str[-2])
Output :
HELLO
<class 'str'>
H
O
L
String Operators
Obviously, arithmetic operators don't operate on strings. However,
there are special operators for string processing.
str.capitalize() Returns the copy of the string with its first character capitalized and the rest of the
letters are in lowercased.
string.casefold() Returns a lowered case string. It is similar to the lower() method, but the casefold()
method converts more characters into lower case.
string.center() Returns a new centered string of the specified length, which is padded with the
specified character. The deafult character is space.
string.count() Searches (case-sensitive) the specified substring in the given string and returns an
integer indicating occurrences of the substring.
string.endswith() Returns True if a string ends with the specified suffix (case-sensitive), otherwise returns
False.
string.expandtabs() Returns a string with all tab characters \t replaced with one or more space, depending
on the number of characters before \t and the specified tab size.
string.find() Returns the index of the first occurence of a substring in the given string (case-
sensitive). If the substring is not found it returns -1.
string.index() Returns the index of the first occurence of a substring in the given string.
string.isalnum() Returns True if all characters in the string are alphanumeric (either alphabets or
numbers). If not, it returns False.
string.isalpha() Returns True if all characters in a string are alphabetic (both lowercase and uppercase)
and returns False if at least one character is not an alphabet.
string.isascii() Returns True if the string is empty or all characters in the string are ASCII.
string.isdecimal() Returns True if all characters in a string are decimal characters. If not, it returns False.
string.isdigit() Returns True if all characters in a string are digits or Unicode char of a digit. If not, it
returns False.
string.isidentifier() Checks whether a string is valid identifier string or not. It returns True if the string is a
valid identifier otherwise returns False.
string.islower() Checks whether all the characters of a given string are lowercased or not. It returns True
if all characters are lowercased and False even if one character is uppercase.
string.isnumeric() Checks whether all the characters of the string are numeric characters or not. It will
return True if all characters are numeric and will return False even if one character is
Method Description
non-numeric.
string.isprintable() Returns True if all the characters of the given string are Printable. It returns False even if
one character is Non-Printable.
string.isspace() Returns True if all the characters of the given string are whitespaces. It returns False
even if one character is not whitespace.
string.istitle() Checks whether each word's first character is upper case and the rest are in lower case
or not. It returns True if a string is titlecased; otherwise, it returns False. The symbols
and numbers are ignored.
string.isupper() Returns True if all characters are uppercase and False even if one character is not in
uppercase.
string.join() Returns a string, which is the concatenation of the string (on which it is called) with the
string elements of the specified iterable as an argument.
string.ljust() Returns the left justified string with the specified width. If the specified width is more
than the string length, then the string's remaining part is filled with the specified fillchar.
string.lower() Returns the copy of the original string wherein all the characters are converted to
lowercase.
string.lstrip() Returns a copy of the string by removing leading characters specified as an argument.
string.maketrans() Returns a mapping table that maps each character in the given string to the character in
the second string at the same position. This mapping table is used with the translate()
method, which will replace characters as per the mapping table.
string.partition() Splits the string at the first occurrence of the specified string separator sep argument
and returns a tuple containing three elements, the part before the separator, the
separator itself, and the part after the separator.
string.replace() Returns a copy of the string where all occurrences of a substring are replaced with
another substring.
string.rfind() Returns the highest index of the specified substring (the last occurrence of the
substring) in the given string.
string.rindex() Returns the index of the last occurence of a substring in the given string.
string.rjust() Returns the right justified string with the specified width. If the specified width is more
than the string length, then the string's remaining part is filled with the specified fill
char.
Method Description
string.rpartition() Splits the string at the last occurrence of the specified string separator sep argument
and returns a tuple containing three elements, the part before the separator, the
separator itself, and the part after the separator.
string.rsplit() Splits a string from the specified separator and returns a list object with string elements.
string.rstrip() Returns a copy of the string by removing the trailing characters specified as argument.
string.split() Splits the string from the specified separator and returns a list object with string
elements.
string.splitlines() Splits the string at line boundaries and returns a list of lines in the string.
string.startswith() Returns True if a string starts with the specified prefix. If not, it returns False.
string.strip() Returns a copy of the string by removing both the leading and the trailing characters.
string.swapcase() Returns a copy of the string with uppercase characters converted to lowercase and vice
versa. Symbols and letters are ignored.
string.title() Returns a string where each word starts with an uppercase character, and the remaining
characters are lowercase.
string.translate() Returns a string where each character is mapped to its corresponding character in the
translation table.
string.upper() Returns a string in the upper case. Symbols and numbers remain unaffected.
string.zfill() Returns a copy of the string with '0' characters padded to the left. It adds zeros (0) at
the beginning of the string until the length of a string equals the specified width
parameter.
>>> print('Welcome')
Welcome
>>> a=5
>>> print(a)
5
>>> print(type(a))
<class 'int'>
>>> a="hello"
>>> print(a)
hello
>>> print(type(a))
<class 'str'>
>>> a=5
>>> b=4
>>> print(a,b)
54
>>> print(a,b,sep="#")
5#4
>>> print(a,b,sep="#",end="&")
5#4&
>>> c=6
>>> print(a,b,c,sep=",")
5,4,6
>>> print("Value of a : ",a)
Value of a : 5
>>> print("Value of a and b : ",a,b)
Value of a and b : 5 4
>>> a=1
>>> b=2
>>> print("A={} and B={}".format(a,b))
A=1 and B=2
>>> print("B={1} and A={0}".format(a,b))
B=2 and A=1
>>> print("A={} and B={} and A={}".format(a,b))
IndexError: tuple index out of range
>>> print("A={0} and B={1} and A={0}".format(a,b))
A=1 and B=2 and A=1
>>>
user.
Syntax : input([prompt])
Note : By default input method read string and store in variable. To perform calculations we need to
convert them in numeric value by using int() and float() methods.
>>> a=input('Input a Value : ')
Input a Value : 23
>>> print(a)
23
>>> print(type(a))
<class 'str'>
Eval Function : if we wish x to be of type integer if the user enters 2 and x to be floating point if the user enters
2.0? Python provides the eval function that attempts to evaluate a string
Exercise
x1 = eval(input('Entry x1? '))
print('x1 =', x1, ' type:', type(x1))
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
// Floor Division - The division of operands where the 9//2 = 4 and 9.0//2.0 =
result is the quotient in which the digits after the 4.0, -11//3 = -4, -
decimal point are removed. But if one of the 11.0//3 = -4.0
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity) −
BITWISE OPERATORS
>> Signed Shift right by pushing copies of the leftmost bit in from
right shift the left, and let the rightmost bits fall off
For Example :
x = 20 #When we assign the value to the x. the integer object 20 is created in the
Heap memory and its reference is assigned to x.
y = x
It means the y object will refer to the same object because Python allocated the same
object reference to new variable if the object is already exists with the same value.
if id(x) == id(y):
print("x and y refer to the same object")
x += 1
In this case two objects will be there x will be pointing to 21 Object and y will be
pointing to 20 object.
If id(x) == id(y):
print("x and y do not refer to the same object")
>>> a=1
>>> id(a)
1797707952
>>> b=a
>>> id(a)
1797707952
>>> a=a+1
>>> id(a)
1797707968
>>> id(b)
1797707952
>>>del a # to delete a object reference
Dynamic Memory Allocation : Dynamic memory allocates the memory at the runtime
to the program. Memory is allocated to the objects at the run time. We use
the Heap for implement dynamic memory management. everything in Python is an
object means dynamic memory allocation inspires the Python memory management.
Python memory manager automatically vanishes when the object is no longer in use.