Python Note Book
Python Note Book
Python Note Book
V SHANMUGANEETHI
ASSOCIATE PROFESSOR, DCSE, NITTTR CHENNAI
WHAT IS PYTHON
Python is an interpreted,
object-oriented,
high-level programming language with dynamic semantics.
Python is Interactive
Sit at a Python prompt and interact with the interpreter directly to write your programs.
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows
the learner to pick up the language quickly.
Easy-to-read: Python code is more clearly defined
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX,Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
FEATURES
Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial databases.
GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
Scalable: Python provides a better structure and support for large programs than shell scripting.
PYTHON IDENTIFIERS
Python has many useful built-in data types. Python variables can store
different types of data based on a variable's data type. A variable's data
type is created dynamically, without the need to explicitly define a data
type when the variable is created.
STANDARD DATA TYPES – BUILT-IN DATATYPES
Numbers
Integer
Floating point number
Complex number
String
List
Tuple
Dictionary
NUMBER
Number data types store numeric values. They are immutable data types, means that
changing the value of a number data type results in a newly allocated object.
var1 = 1
var2 = 10
seed([x]) Sets the integer starting value used in generating random numbers. Call this
function before calling any other random module function. Returns None.
The boolean data type is either True or False. In Python, boolean variables are defined by the True and
False keywords.
a = True
type(a)
<class 'bool'>
Integers and floating point numbers can be converted to the boolean data type using Python's bool()
function.
An int, float or complex number set to zero returns False. An integer, float or complex number set to
any other number, positive or negative, returns True.
BOOL FUNCTION
zero_int = 0
bool(zero_int)
False
pos_int = 1
bool(pos_int)
True
TYPES OF OPERATOR
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
Divides left hand operand by right hand operand and returns b%a=0
% Modulus
remainder
a**b =10 to the power 20
** Exponent Performs exponential (power) calculation on operators
Floor Division - The division of operands where the result is the 9//2 = 4 and 9.0//2.0 = 4.0
//
quotient in which the digits after the decimal point are removed.
COMPARISON OPERATORS
Operator Description Example
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!= If values of two operands are not equal, then condition becomes true.
<> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar
to != operator.
> If the value of left operand is greater than the value of right operand, then (a > b) is not true.
condition becomes true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is true.
operand, then condition becomes true.
ASSIGNMENT OPERATORS
Operator Description Example
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
It adds right operand to the left operand and assign the result to left
+= Add AND c += a is equivalent to c = c + a
operand
It subtracts right operand from the left operand and assign the result to
-= Subtract AND c -= a is equivalent to c = c - a
left operand
It multiplies right operand with the left operand and assign the result to
*= Multiply AND c *= a is equivalent to c = c * a
left operand
It divides left operand with the right operand and assign the result to c /= a is equivalent to c = c / ac /= a is
/= Divide AND
left operand equivalent to c = c / a
It takes modulus using two operands and assign the result to left
%= Modulus AND c %= a is equivalent to c = c % a
operand
**= Exponent Performs exponential (power) calculation on operators and assign value
c **= a is equivalent to c = c ** a
AND to the left operand
It performs floor division on operators and assign value to the left
//= Floor Division c //= a is equivalent to c = c // a
operand
STRINGS
It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d
%
or %f to map their values in python.
INDEXING
Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is indexed as
given in the below figure.
s h a n n e e t h i
0 1 2 3 4 5 6 7 8 9
str ='shannethi'
print('str[0] = ',str[0])
print('str[1] = ',str[1])
str[0] = s
str[1] = h
STRING OPERATIONS - SLICING
del str
print(str)
STRING METHODS
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]).
To some extent, lists are similar to arrays in C. One difference between them is that
all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator.
LIST
A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas. Unlike lists,
however, tuples are enclosed within parentheses.
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 can be
thought of as read-only lists.
TUPLES
Python's dictionaries are kind of hash table type. 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.
Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).
DICTIONARY
d={
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
DICTIONARY
dict = {}
dict['one'] = "name of the user"
dict[2] = "gender"
dict[3] = "dept"
dict[4] = "address"
tinydict = {'name': 'shanmuganeethi.v','mobile':6734, 'dept': 'Computer Centre'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (dict[4]) # Prints value for 4 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
IF STATEMENT
Statement Description
if statements An if statement consists of a boolean expression followed
by one or more statements.
if expression:
statement(s)
IF STATEMENT
print('shanmuganeethi.v')
inputval=int(input('Enter the Number'));
if(inputval == 25) :
print("Enter the value is correct")
print("if statement working , Good bye")
IF .. ELSE
if expression:
statement(s)
else:
statement(s)
IF .. ELSE
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else statement(s)
elif expression4:
statement(s)
else: statement(s)
NESTED IF STATEMENT
nestinput = int(input("Enter the Number"))
if nestinput < 1000:
print ("Expression value is less than 1000")
if nestinput == 500:
print ("Expected divided by 2")
elif nestinput == 100:
print ("The value is 1/10 of expected value")
elif nestinput == 50:
print ("The value is 1/20 of expected value")
elif nestinput < 50:
print ("Very Low value")
else:
print ("It more than the expected value")
print ("Nested statements are working")
LOOPING STATEMENTS
Executes a sequence of statements multiple times and abbreviates the code that
for loop
manages the loop variable.
nested loops You can use one or more loop inside any another while, for or do..while loop.
LOOP CONTROL STATEMENTS
Control
Description
Statement
Terminates the loop statement and transfers execution to the
break statement
statement immediately following the loop.
Causes the loop to skip the remainder of its body and immediately
continue statement
retest its condition prior to reiterating.
The pass statement in Python is used when a statement is required
pass statement syntactically but you do not want any command or code to
execute.
WHILE LOOP
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value.
The loop iterates while the condition is true.
WHILE LOOP
val=int(input("Enter the Number which is less than 15 and greated than 5:"))
while(val > 2):
print('value is=', val)
val=val-1
print('while loop is working')
USING ELSE STATEMENT WITH LOOPS
mylistvalues = ['chennai','bangalore','hyderabad','patna','trichy','madurai']
for i in mylistvalues:
print ("The city name :", i) The city name : chennai
The city name : bangalore
The city name : hyderabad
The city name : patna
print('Thank you') The city name : trichy
The city name : madurai
Thank you
FOR LOOP
while expression:
while expression:
statement(s)
statement(s)
i=2
while(i < 100):
j=2
while(j <= ( I / j) ):
if not( I %j ):
break
j=j+1
if (j > i/j) :
print (i, " is prime“)
i=i+1
BREAK AND CONTINUE
The most common use for break is when some external condition
is triggered requiring a hasty exit from a loop. The break statement
can be used in both while and for loops.
Strings are amongst the most popular types in Python. Strings can be
created simply by enclosing characters in quotes. Python treats single
quotes the same as double quotes. Creating strings is as simple as
assigning a value to a variable.
Python does not support a character type; these are treated as strings of
length one, thus also considered a substring.
STRING UPDATE
"update" an existing string by (re)assigning a variable to another string. The new value
can be related to its previous value or to a completely different string altogether.
* Repetition - Creates new strings, concatenating multiple copies of the same a*2 will give -HelloHello
string
[] Slice - Gives the character from the given index a[1] will give e
[ :] Range Slice - Gives the characters from the given range a[1:4] will give ell
in Membership - Returns true if a character exists in the given string H in a will give 1
not in Membership - Returns true if a character does not exist in the given string M not in a will give 1
r/R Raw String - Suppresses actual meaning of Escape characters. The syntax for raw print r'\n' prints \n and print
strings is exactly the same as for normal strings with the exception of the raw R'\n'prints \n
string operator, the letter "r," which precedes the quotation marks. The "r" can
be lowercase (r) or uppercase (R) and must be placed immediately preceding the
first quote mark.
upper()
Converts lowercase letters in string to uppercase.
zfill (width)
Returs original string leftpadded with zeros to a total of width characters;
intended for numbers, zfill() retains any sign given (less one zero).
isdecimal()
Returns true if a unicode string contains only decimal characters and false
otherwise.
THANK YOU