Python Programming (7)
Python Programming (7)
Content
• What Is Python?
• Python Features
• Python Applications
• Downloading & Installing Python
• Running Python
What Is Python?
• Python is a general purpose, high-level, interpreted
programming language.
A=true # In valid
NameError: name 'true' is not defined
Statements and Expressions:
A statement is an instruction or statement is a unit of code that can be executed by
python interpreter.
Eg: z = 1 // this iExamples: Y=x + 17 >>> x=10 >>> z=x+20 >>> z 30 s an assignment
statement
Expression:
An expression is a combination of values, variables, and operators which are evaluated
to make a new value b.
>>> 20 # A single value
>>> z # A single variable
>>> z=10 # A statement
But expression is a combination of variable, operator and value which is evaluated by
using assignment operator in script mode.
Examples: Y=x + 17
>>> x=10 >>> z=x+20 >>> z o/p : 30
When the expression is used in interactive mode, is evaluated by the interpreter and
the result is displayed instantly.
Eg:
>>> 8+2
10
Variables:
Variables are nothing but reserved memory locations to store
values. That means when you create a variable some space is
reserved in memory.
• One of the most powerful features of a programming language
is the ability to manipulate variables.
• A variable is a name that refers to a value. An assignment
statement creates new variables and gives them values:
• Data types specify the type of data like numbers and characters to be stored
and manipulated with in a program. Basic data type of python are
• Numbers
• Boolean
• Strings
• None
Numbers:
• Integers, floating point numbers and complex numbers fall under python
numbers category. They are defined as int, float and complex class in
python.
1. integer:
• Int, or integer, is a whole number, positive or negative, without decimals,
of unlimited length, it is only limited by the memory available.
Example:
a=10
b=-12
c=123456789
2. float:
• Float or "floating point number" is a number, positive or negative, containing
one or more decimals.
Example:
• X=1.0
• Y=12.3
• Z= -13.4
3. complex:
• Complex numbers are written in the form , “x+yj" where x is the real part and
y is the imaginary part.
Example:
A=2+5j
B=-3+4j
C=-6j
Boolean:
Booleans are essential when you start using conditional statements.
Python Boolean type is one of the built-in data types provided by Python,
which represents one of the two values i.e. True or False. The boolean
values, True and False treated as reserved words.
String:
• The string can be defined as the sequence of characters
represented in the quotation marks. In python, we can use single,
double, or triple quotes to define a string.
• In the case of string handling, the operator + is used to concatenate
two strings as the operation "hello"+" python" returns "hello
python".
Example:
EX : S1=‘Welcome’ #using single quotes
S1 Output: ‘Welcome’
print(S1) Output: Welcome
Ex: S2=“To” #using double quotes
S2 Output: 'to'
print(S2) Output: to
Ex: S3=‘’’Python’’’ #using triple quotes
S3 Output: "'python'"
print(S3) Output: 'python‘
Ex: Name1= ‘Hello’
Name2=‘python’
Name1 + Name2 Output: ‘Hellopython’
print(Name1 + Name2) Output: Hellopython
Example:
a=10
b=“Python"
c = 10.5
d=2.14j
e=True
print("Data type of Variable a :",type(a))
print("Data type of Variable b :",type(b))
print("Data type of Variable c :",type(c))
print("Data type of Variable d :",type(d))
print(“Data type of Variable e :”,type(e))
Output:
• Data type of Variable a : <class 'int'>
• Data type of Variable b : <class 'str'>
• Data type of Variable c : <class 'float'>
• Data type of Variable d : <class 'complex'>
• Data type of Variable e : <class 'bool'>
Indentation:
• In Python it is a requirement and not a matter of style to indent the
program. This makes the code cleaner and easier to understand and
read.
• If a code block has to be deeply nested, then the nested statements
need to be indented further to the right.
• Block 2 and Block 3 are nested under Block 1. 4 white spaces are
used for indentation and are preferred over tabs.
• Incorrect indentation will result in IndentationError.
Block 1
Block 2
Block 3
Block 2, Continuation
Block 1, Continuation
• Reading Input :
• Input() function is used to gather data from the user.
• Syntax : variable_name = input([prompt])
• Where prompt is a string written inside parenthesis.
• The prompt gives an indication to the user of the value that needs
to be entered through the keyboard.
• When user presses Enter key, the program resumes and input
function returns what the user typed as a string.
• Even if the user inputs a number, it is treated as a string and the
variable_name is assigned the value of string.
1. >>> person = input(“what is your name?”)
2. What is your name? John
3. >>>person
4. ‘John’
Print Output
• Print() function allows a program to display text onto the console.
• Print function prints everything as strings.
>>>print(“Hello World”)
Hello World
There are two major string formats which are used inside the print() function to display
the contents on to the console.
1. [Link]()
2. f-strings
[Link]() method:
• The format() method returns a new string with inserted values.
• syntax: [Link](p0,p1,p2…..k0=v0, k1=v1,…)
• Where p0,p1 are called as positional arguments and k0,k1 are keyword arguments
with their assigned values of v0,v1..
• Positional arguments are a list of arguments that can be accessed with an index of
argument inside curly braces like {index}. Index value starts from zero.
• Keyword arguments are a list of arguments of type keyword = value, that can be
accessed with the name of the argument inside curly braces like {keyword}.
Eg: country = input(“which country do you live in”)
print(“I live in {0}”.format(country))
• Print Output
Eg:
a = 10
b = 20
Print(“the values of a is {0} and b is {1}”.format(a,b))
Print(“the values of b is {1} and a is {0}”.format(a,b))
f-strings:
A f-string is a string literal that is prefixed with “f”. These strings
may contain replacement fields ,and are enclosed within
curly braces { }.
Eg: country = input(“which country do you live in”)
Print(f”I live in {country}”)
Type Conversion in Python:
• Python provides Explicit type conversion functions to directly convert
one data type to another. It is also called as Type Casting in Python
• Python supports following functions
1. int () : This function convert a float number or a string to an integer.
• Eg: float_to_int = int(3.5)
string_to_int = int(“1”) // number is treated as string
print(float_to_int) o/p: 3
print(string_to_int) o/p: 1 will be displayed.
2. float( ) :
• This function convert integer or a string to floating point number using the
float() function.
• Eg: int_to_float = float(8)
string_to_float = float(“1”) // number is treated as string
print(int_to_float)
print(string_to_float)
8.0
1.0 get displayed
• The str() Function : The str() function returns a string which is fairly human
readable.
Eg: int_to_string =str(8)
float_to_string = str(3.5)
Print(int_to_string) prints ‘8’
Print(float_to_string) prints ‘3.5’
Remember:
input () function is used to get input from user.
Example:
a=input (“Enter a value”)
Conditional Statements in Python Cont..
If-else statement:
• The if-else statement provides an else block combined with the if
statement which is executed in the false case of the condition.
Syntax:
Output:
if condition:
python [Link]
#block of statements
Enter your age: 19
else:
You are eligible to vote!!
#another block of statements (else-block)
Example: [Link]
age = int(input("Enter your age : "))
if age>=18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!"))
Conditional Statements in Python Cont..
If-elif-else statement:
• The elif statement enables us to check multiple conditions and
execute the specific block of statements depending upon the true
condition among them.
Syntax:
if condition1:
# block of statements
elif condition2:
# block of statements
elif condition3:
# block of statements
else:
# block of statements
Conditional Statements in Python Cont..
Example: [Link]
a=int(input("Enter a value : "))
b=int(input("Enter b value : "))
c=int(input("Enter c value : "))
if (a>b) and (a>c):
print("Maximum value is :",a)
elif (b>a) and (b>c):
print("Maximum value is :",b)
else:
print("Maximum value is :",c)
Output:
python [Link]
Enter a value: 10
Enter b value: 14
Enter c value: 9
Maximum value is: 14
Loop Statements in Python
Loop Statements in Python
• Sometimes we may need to alter the flow of the program. If the
execution of a specific code may need to be repeated several
numbers of times then we can go for loop statements.
• In python, the following are loop statements
o while loop
o for loop
while loop:
• With the while loop we can execute a set of statements as long
as a condition is true. The while loop is mostly used in the case
where the number of iterations is not known in advance.
Syntax:
while expression:
Statement(s)
Loop Statements in Python Cont..
for loop:
• The for loop in Python is used to iterate the statements or a
part of the program several times. It is frequently used to
traverse the data structures like list, tuple, or dictionary.
Syntax:
for iterating_var in sequence:
statement(s)
Output:
python [Link]
1234
for loop completely exhausted
Jump Statements in Python
Jump Statements in Python
• Jump statements in python are used to alter the flow of a loop
like you want to skip a part of a loop or terminate a loop.
• In python, the following are jump statements
o break
o continue
break:
• The break is a keyword in python which is used to bring the
program control out of the loop.
• The break statement breaks the loops one by one, i.e., in the
case of nested loops, it breaks the inner loop first and then
proceeds to outer loops.
• The break is commonly used in the cases where we need to
break the loop for a given condition.
Syntax: break
Jump Statements in Python Cont..
Example: [Link]
i = 1 Output:
while i < 6: python [Link]
print(i)
1
if i == 3:
break 2
i += 1 3
continue:
• The continue statement in python is used to bring the program
control to the beginning of the loop.
• The continue statement skips the remaining lines of code inside
the loop and start with the next iteration.
• It is mainly used for a particular condition inside the loop so
that we can skip some specific code for a particular condition.
Syntax: continue
Jump Statements in Python Cont..
Example: [Link]
str =input("Enter any String : ")
for i in str:
if i == 'h':
continue;
print(i,end=" ");
Output:
python [Link]
Enter any String : python
pyton
Functions
• Function:
• Block of statements are grouped together and is given a name which can be used to invoke (call) it
from other parts of the program.
• Functions can be either Built-in functions or User-defined functions
• Built-In Functions:
Function name Syntax Explanation
abs() abs(x), where x is an integer or abs() function returns the
floating point number absolute value of a number
min() Min(arg_1,arg_2….arg_n) Returns the smallest of 2 or
Where arg_1, arg_2…arg_n are more arguments
arguments
max() Max(arg_1,arg_2….arg_n) Where Returns the maximum of 2 or
arg_1, arg_2…arg_n are arguments more arguments
• 3rd party modules or libraries can be installed and managed using python’s package manager pip.
Arrow is a popular library used to create, manipulate format and convert date, time and timestamp.
• def function_definition_with_no_argument():
• print(“This is a function definition with no arguments”)
• def function_definition_with_one_argument(message):
• print(“This is a function definition with {message}”)
• def main():
• function_definition_with_no_argument()
• function_definition_with_one_argument(“one argument”)
• If_name_==“_main_”:
• main()
• OUTPUT:
• This is a function definition with no arguments
• This is a function definition with one argument
Output:
• The return Statement and void Function
• This is used to return value to the calling function so that it is
stored in a variable.
• Syntax: return[expression_list]
• In Python, we can define functions without a return
statement. Such functions are called void functions.
• A function call return only a single value but that value can
be a list or tuple.
• Eg:
• #Program to return multiple values from return statement separated by
comma
Example 1
def world_war():
alliance_world_war = input("which alliance won world war 2?")
world_war_end_year = input("when did world war 2 end?")
return alliance_world_war, world_war_end_year
def main():
alliance, war_end_year = world_war()
print(f"The war was won by {alliance} and the war ended in {war_end_year}")
if __name__=="__main__":
main()
Example 2
Output:
Sum = 10
Diff = 2
• Scope and Lifetime of Variables
def inner_func():
test_var = 100
print("local var inner func is ", test_var)
inner_func()
print("local var outer func is", test_var)
outer_func()
print("global var value is", test_var)
• Output:
• local var inner func is 100
• local var outer func is 60
• global var value is 10
Nested Function:
A nested function (inner function) can inherit the arguments and variables of
its outer function. The inner function can use the arguments and variables
of the outer function while the outer function cannot use the arguments
and variables of the inner function.
The inner function definition is invoked by calling it from within the outer
function definition.
Example:
Without return function
Output:
power= 8
multiplication= 20
With return function
def multiplication(a,b):
c=a*b
def power(d,e):
f=d**e
return f
result=power(2,3)
return c,result
def main():
mul,pow =multiplication(4,5)
print("mul=",mul)
print("pow=",pow)
if __name__=="__main__":
main()
Output:
mul= 20
pow= 8
Default Parameters:
Any calling function must provide arguments for all required parameters in the
function definition but can omit the arguments for default parameters. If no
argument is sent for that parameter, the default values is used.
Def main():
work_area(“ Sam works here in ”)
work_area(“Alice has interest in”, “Internet of Things”)
If__name__==“__main__”:
main()
Output:
Sam works here in Data Analytics
Alice has interest in Internet of Things
Example : 2
def message(msg1,msg2="Good Morning"):
print(msg1,msg2)
def main():
message("hello")
message("hello","world")
if __name__=="__main__":
main()
Output:
hello Good Morning
hello world
Keyword Arguments:
Whenever you call a function with some values as its arguments, these values get
assigned to the parameters in the function definition according to their position.
In calling function, you can specify the argument name and their value in the form of
Kwarg = value. In calling function, keyword arguments must follow positional arguments.
No parameter in the function definition may receive a value more than once.
OR
Keyword arguments mean whenever we pass the arguments(or value) by their
parameter names at the time of calling the function in Python in which if you
change the position of arguments then there will be no change in the
output.
On using keyword arguments you will get the correct output because
the order of argument doesn’t matter provided the logic of your code is
correct. But in the case of positional arguments, you will get more than one
output on changing the order of the arguments.
Example 1: Keyword Argument
def nameAge(name, age):
print("Hi, I am", name)
print("My Age is", age)
Output:
Hi, I am SriRam
My Age is 20
Hi, I am SriRam
My Age is 20
Positional arguments
Positional arguments are arguments that need to be included in the proper position or
order. The first positional argument always needs to be listed first when the function is
called. The second positional argument needs to be listed second and the third
positional argument listed third, etc.
Example 1:
def nameAge(name, age):
print("Hi I‘ am", name)
print("My age is", age)
#you will get correct output because argument is given in order
nameAge("SriRam", 20)
#you will get Incorrect output because argument is not in order
nameAge(20, "SriRam")
Output:
Hi I‘ am SriRam
My age is 20
Hi I 'am 20
My age is SriRam
*args and **kwargs
They are used as parameters in function definitions.
*args and **kwargs allows you to pass a variable number of arguments to
the calling function.
User might not know the number of arguments in advance that will be
passed to the calling function.
*args : Allows you to pass a non-key worded variable length argument list
to the calling function.
**kwargs as parameter in function allows you to pass key worded variable
length dictionary argument list to the calling function.
*args should come after all the positional paramters and **kwargs must
come right at the end.
*args and **kwargs
• In Python, we can pass a variable number of arguments to a function using
special symbols. There are two special symbols:
• *args (Non Keyword Arguments)
• **kwargs (Keyword Arguments)
We use *args and **kwargs as an argument when we are unsure about
the number of arguments to pass in the functions.
Python *args
Python has *args which allow us to pass the variable number of non keyword
arguments to function.
In the function, we should use an asterisk * before the parameter name to
pass variable length arguments. The arguments are passed as a tuple and these
passed arguments make tuple inside the function with same name as the
parameter excluding asterisk *
Example 1 : *args
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:" ,sum)
adder(3,5)
adder(4,5,6,7)
adder(1,2,3,4,5,6)
Output:
Sum: 8
Sum: 22
Sum: 21
Python **kwargs
Python passes variable length non keyword argument to function
using *args but we cannot use this to pass keyword argument. For this
problem Python has got a solution called **kwargs
it allows us to pass the variable length of keyword arguments to the
function.
In the function, we use the double asterisk ** before the parameter
name to denote this type of argument. The arguments are passed as a
dictionary and these arguments make a dictionary inside function with
name same as the parameter excluding double asterisk **
You need to import sys module to access command line arguments. All the command line
arguments can be printed as a list of string by executing [Link].
Example:
import sys
def main():
print(f"[Link] prints all the arguments at the command line including file name {[Link]}")
print(f"len([Link]) prints the total number of command line arguments including file name
{len([Link])}")
print("you can use for loop to traverse through [Link]")
for arg in [Link]:
print(arg)
if __name__=="__main__":
main()
Output
• C:\Users\Admin>python
C:/Users/Admin/AppData/Local/Programs/Python/Python311/[Link] lion tiger mouse
• len([Link]) prints the total number of command line arguments including file name 4
• C:/Users/Admin/AppData/Local/Programs/Python/Python311/[Link]
• lion
• tiger
• mouse
How to Execute command line argument program
1. Write the program
2. Save the program with .py extension
3. Open command prompt
4. Change the path to where program is being saved
5. Py followed by [Link] ([Link]) and followed by
number of Arguments (arg1 arg2 arg3…..)
Example 1
import sys
print([Link])
print(len([Link]))
for i in range (0,len([Link])):
print("Argument -:",i,":",[Link][i])
#Sum of all the elements from the command line
import sys
sum=0
for i in range (1,len([Link])):
sum+=int([Link][i])
print("result=",sum)
Strings
Creating and Sorting Strings:
>>>string_1 =“face”
>>>string_2 =“book”
>>>string_1+string_2
‘facebook’
When two strings are concatenated, there is no white space between them. If you need a white space
between the 2 strings, include a space after the first string or before the second string within the
quotes.
>>>singer = 50+”cent” gives an error as 50 is of integer type and cent is of string type.
>>>singer =str(50) + “cent”
>>>singer
‘50cent’
>>>repeated_str =“wow” * 5
>>>repeated_str
‘wowwowwowwowwow’
You can check the presence of a string in another string using in and not in membership operators
>>>fruit_str=“apple is a fruit”
>>>fruit_sub_str=‘apple’
>>>fruit_sub_str in fruit_string
True
>>> another_fruit_str=“orange”
>>>another_fruit_str not in fruit_str
True
3. String Comparison:
>, <, <=,>=,==, != can be used to compare two strings resulting in True or False. Python compares
the strings using ASCII value of the characters.
>>>”january” == “jane”
False
>>>”january” != “jane”
True
>>>”january” > “jane” # the ASCII value of u is more than e
True
>>>”january” < “jane”
False
>>>”january” >= “jane”
True
>>>”january” <= “jane”
False Built in functions Descriptions
>>>”filled”>”” Len() This function calculates the number
True of characters in a string
4. Built In Functions
using Strings Max() This function returns a character
There are built in functions for having highest ASCII value
which a string can be passed
Min() This function returns a character
as an argument.
having lowest ASCII value
Eg:
>>>max(“axel”)
‘x’
>>>min(“brad”)
‘a’
5. Accessing Characters in String by Index Number:
Each character in the string occupies a position in the string. Each of the string’s character
corresponds to an index number. First character is at index 0.
Syntax: string_name[index]
b e y o u r s e l f
index 0 1 2 3 4 5 6 7 8 9 10
>>>word_phrase=“be yourself”
>>>word_phrase[0]
‘b’
>>>word_phase[1]
e
>>>word_phase[2]
‘’
>>>word_phase[3]
y
The individual characters in a string can be accessed using negative indexing. If there is a long string
and you want to access end characters in a string, then you can count backwards from the end of
the string starting from the index of -1
>>>word_phrase[-1]
‘f’
>>>word_phrase[-2] b e y o u r s e l f
‘l’
index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
6. String Slicing and Joining
>>>drink[-3:-1] g r e e n t e a
‘te’
-9 -8 -7 -6 -5 -4 -3 -2 -1
>>>drink[6:-1]
‘te’ We can combine the positive and negative indexing numbers
• lower() • find()
• upper() •index()
• replace() • isalnum()
• join() • isdigit()
• split() • isnumeric()
• islower()
• isupper()
String Methods in Python Cont..
☞ lower ():
• In python, lower() method returns all characters of given string in
lowercase.
Syntax:
[Link]()
Example: [Link] Output:
str1="PyTHOn" python [Link]
print([Link]()) python
☞ upper ():
• In python, upper() method returns all characters of given string in uppercase.
Syntax:
[Link]()
Example: [Link] Output:
str="PyTHOn" python [Link]
print([Link]()) PYTHON
String Methods in Python Cont..
☞ replace()
• In python, replace() method replaces the old sequence of
characters with the new sequence.
Syntax: [Link](old, new[, count])
Example: [Link]
str = "Java is Object-Oriented and Java"
str2 = [Link]("Java","Python")
print("Old String: \n",str)
print("New String: \n",str2)
str3 = [Link]("Java","Python",1)
print("\n Old String: \n",str)
print("New String: \n",str3)
Output: python [Link]
Old String: Java is Object-Oriented and Java
New String: Python is Object-Oriented and Python
Old String: Java is Object-Oriented and Java
New String: Python is Object-Oriented and Java
String Methods in Python Cont..
☞ split():
• In python, split() method splits the string into a comma separated list.
The string splits according to the space if the delimiter is not provided.
Syntax: [Link]([sep="delimiter"])
Example: [Link]
str1 = “Java is a programming language"
str2 = [Link]()
print(str1);print(str2)
str1 = “Java,is,a,programming,language"
str2 = [Link](sep=',')
print(str1);print(str2)
Output:
python [Link]
7 -1 12 7
String Methods in Python Cont..
☞ index():
• In python, index() method is same as the find() method except it returns
error on failure. This method returns index of first occurred substring
and an error if there is no match found.
Syntax: str. index(sub[, start[,end]])
Example: [Link]
str1 = "python is a programming language"
str2 = [Link]("is")
print(str2)
str3 = [Link]("p",5)
print(str3)
str4 = [Link]("i",5,25) Output:
print(str4) python [Link]
str5 = [Link]("java") 7
print(str5) 12
7
Substring not found
String Methods in Python Cont..
☞ isalnum():
• In python, isalnum() method checks whether the all characters of the
string is alphanumeric or not.
• A character which is either a letter or a number is known as
alphanumeric. It does not allow special chars even spaces.
Syntax: [Link]()
Example: [Link]
str1 = "python"
str2 = "python123" Output:
str3 = "12345" python [Link]
str4 = "python@123" True
str5 = "python 123" True
print(str1. isalnum()) True
print(str2. isalnum()) False
print(str3. isalnum()) False
print(str4. isalnum())
print(str5. isalnum())
String Methods in Python Cont..
☞ isdigit():
• In python, isdigit() method returns True if all the characters in the string
are digits. It returns False if no character is digit in the string.
Syntax: [Link]()
Example: [Link]
str1 = "12345"
str2 = "python123"
str3 = "123-45-78"
str4 = "IIIV" Output:
str5 = "/u00B23" # 23 python [Link]
str6 = "/u00BD" # 1/2 True
print([Link]()) False
print([Link]()) False
print([Link]()) False
print([Link]()) False
print([Link]()) False
print([Link]())
String Methods in Python Cont..
☞ isnumeric():
• In python, isnumeric() method checks whether all the characters of the
string are numeric characters or not. It returns True if all the characters
are numeric, otherwise returns False.
Syntax: str. isnumeric()
Example: [Link]
str1 = "12345"
str2 = "python123"
str3 = "123-45-78" Output:
str4 = "IIIV" python [Link]
str5 = "/u00B23" # 23 True
str6 = "/u00BD" # 1/2
False
print([Link]())
False
print([Link]())
print([Link]()) False
print([Link]()) True
print([Link]()) True
print([Link]())
String Methods in Python Cont..
☞ islower():
• In python, islower() method returns True if all characters in the string
are in lowercase. It returns False if not in lowercase.
Syntax: [Link]()
Example: [Link]
str1 = "python"
str2="PytHOn"
str3="python3.7.3"
print([Link]())
print([Link]())
Output:
print([Link]())
python [Link]
True
False
True
String Methods in Python Cont..
☞ isupper():
• In python string isupper() method returns True if all characters in the
string are in uppercase. It returns False if not in uppercase.
Syntax: [Link]()
Example: [Link]
str1 = "PYTHON"
str2="PytHOn"
str3="PYTHON 3.7.3"
print([Link]())
print([Link]())
Output:
print([Link]())
python [Link]
True
False
True
List Creation
List in Python
• In python, a list can be defined as a collection of values or
items.
• The items in the list are separated with the comma (,) and
enclosed with the square brackets [ ].
Syntax:
list_name= [ item1, item2,item3…. ]
Example: “[Link]”
L1 = [] Output:
L2 = [123,"python", 3.7] python [Link]
L3 = [1, 2, 3, 4, 5, 6] []
L4 = ["C","Java","Python"] [123, 'python', 3.7]
print(L1) [1, 2, 3, 4, 5, 6]
print(L2) ['C','Java','Python']
print(L3)
print(L4)
List Operators
List Operators in Python
It is known as concatenation operator used to concatenate two
+ lists.
It is known as repetition operator. It concatenates the multiple
* copies of the same list.
It is known as slice operator. It is used to access the list item
[] from list.
It is known as range slice operator. It is used to access the range
[:] of list items from list.
It is known as membership operator. It returns if a particular
in item is present in the specified list.
Example: “[Link]”
num=[1,2,3,4,5]
lang=['python','c','java','php']
print(num + lang) #concatenates two lists
print(num * 2) #concatenates same list 2 times
print(lang[2]) # prints 2nd index value
print(lang[1:4]) #prints values from 1st to 3rd index.
print('cpp' in lang) # prints False
print(6 not in num) # prints True
• mylist[0]=”banana” mylist[1:3]=[”apple”,”mango”]
• mylist[2]=”mango”
List Indexing in Python cont…
• mylist[-1]=”berry” mylist[-4:-2]=[“apple”,mango”]
• mylist[-3]=”mango” mvlist[ -3 : ]=[“mango”,”tomato”,’berry’]
Slicing in list
• Slicing of lists is allowed in Python wherein a part of the list
can be extracted by
• specifying index range along with the colon (:) operator which
itself is a list.
• The syntax for list slicing is,
•
• List slicing returns a part of the list from the start index value
to stop index value which includes the start index value but
excludes the stop index value. Step specifies the increment
value to slice by and it is optional.
• 1. >>> fruits = ["grapefruit", "pineapple", "blueberries", "mango",
"banana"]
• 2. >>> fruits[1:3]
• ['pineapple', 'blueberries']
• 3. >>> fruits[:3]
• ['grapefruit', 'pineapple', 'blueberries']
• 4. >>> fruits[2:]
• ['blueberries', 'mango', 'banana']
• 5. >>> fruits[1:4:2]
• ['pineapple', 'mango']
• 6. >>> fruits[:]
• ['grapefruit', 'pineapple', 'blueberries', 'mango', 'banana']
• 7. >>> fruits[::2]
• ['grapefruit', 'blueberries', 'banana']
• 8. >>> fruits[::-1]
• ['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit']
• 9. >>> fruits[-3:-1]
• ['blueberries', 'mango']
How to update or change elements to a list?
• Python allows us to modify the list items by using the slice and
assignment operator.
• We can use assignment operator ( = ) to change an item or a
range of items.
Example: “[Link]”
num=[1,2,3,4,5]
print(num) Output:
num[2]=30 python [Link]
print(num) [1, 2, 3, 4, 5]
num[1:3]=[25,36] [1, 2, 30, 4, 5]
print(num) [1, 25, 36, 4, 5]
num[4]="Python" [1, 25, 36, 4, 'Python']
print(num) [1, 25, 36, 4, ‘python’]
List1=num1
Print(list1)
Built –in functions used on lists
List Functions & Methods in Python
• Python provides various in-built functions .Those are
• len()
• any()
• all()
• sum()
• sorted()
☞ len():
• In Python, len() function is used to find the length of list,i.e it
returns the number of items in the list..
Syntax: len(list)
Example: [Link] Output:
num=[1,2,3,4,5,6] python [Link]
print("length of list :",len(num)) length of list : 6
• ☞ any():
• The any() function returns True if any of the Boolean
values in the list is True.
• Syntax: any(iterable)
• Iterable: It is an iterable object such as a dictionary,
tuple, list, set, etc.
• Ex:
• any([1, 1, 0, 0, 1, 0])
• True
• any(0,0,0,0)
• False
• list2=[1,0,2]
• any(list2)
• True
• ☞ all():
• The all() function returns True if all the Boolean values in the
list are True, else returns False.
• Syntax: any(iterable)
• Iterable: It is an iterable object such as a dictionary, tuple, list,
set, etc.
• Ex:
• >>> all([1, 1, 1, 1])
• True
• >>> all([1,0,2])
• False
• >>> all([1,2,3,4,5,])
• True
List Functions in Python Cont..
☞ sum ():
• In python, sum() function returns sum of all values in the list. List
values must in number type.
Syntax: sum(list)
Example: [Link]
list1=[1,2,3,4,5,6]
print("Sum of list items :",sum(list1))
Output:
python [Link]
Sum of list items : 21
List Functions in Python Cont..
☞ sorted ():
• The sorted() function returns a modified copy of the list while
leaving the original list untouched.
Syntax: sorted(list)
Example: [Link]
num=[23,5,78,9]
print(sorted(num))
[5, 9, 23, 78]
print(num)
[23, 5, 78, 9]
List Methods
List Functions & Methods in Python
• Python provides various methods which can be used with list.
• Those are
• count() • extend
• index() •append()
• max()
• insert() • remove()
• min()
• pop() • sort()
• list()
• clear() • reverse()
List Methods in Python Cont..
☞ max ():
• In Python, max() function is used to find maximum value in the list.
Syntax: max(list)
Example: [Link]
list1=[1,2,3,4,5,6]
list2=['java','c','python','cpp']
print("Max of list1 :",max(list1))
print("Max of list2 :",max(list2))
Output:
python [Link]
Max of list1 : 6
Max of list2 : python
List Methods in Python Cont..
☞ min ():
• In Python, min() function is used to find minimum value in the list.
Syntax: min(list)
Example: [Link]
list1=[1,2,3,4,5,6]
list2=['java','c','python','cpp']
print("Min of list1 :",min(list1))
print("Min of list2 :",min(list2))
Output:
python [Link]
Min of list1 : 1
Min of list2 : c
List Methods in Python Cont..
☞ list ():
• In python, list() is used to convert given sequence (string or tuple)
into list.
Syntax: list(sequence)
Example: [Link]
str="python"
list1=list(str)
print(list1)
Output:
python [Link]
['p', 'y', 't', 'h', 'o', 'n']
List Methods in Python Cont..
☞ append ():
The append() method adds a single item to the end of the list. This
method does not return new list and it just modifies the original.
Syntax: [Link](item)
where item may be number, string, list and etc.
Example: num=[1,2,3,4,5]
lang=['python','java']
[Link](6) Output:
print(num) python [Link]
[Link]("cpp") [1, 2, 3, 4, 5, 6]
print(lang)
['python', 'java', 'cpp']
list=[1,2,3,4]
[1, 2, 3, 4, [6, 7]]
[Link]([6,7])
print(list)
List Methods in Python Cont..
☞ remove ():
• In python, remove() method removes item from the list. It removes
first occurrence of item if list contains duplicate items. It throws an
“value error” if the item is not present in the list.
Syntax: [Link](item)
Example: [Link]
list1=[1,2,3,4,5]
list2=['A','B','C','B','D'] Output:
[Link](2) python [Link]
print(list1)
[Link]("B") [1, 3, 4, 5]
print(list2) ['A', 'C', 'B', 'D']
[Link]("E")
print(list2) ValueError: x not in list
List Methods in Python Cont..
☞ sort ():
• In python, sort() method sorts the list elements into descending or
ascending order. By default, list sorts the elements into ascending
order. It takes an optional parameter 'reverse' which sorts the list
into descending order. This method modifies the original list.
Syntax: [Link]()
Example: [Link]
list1=[6,8,2,4,10]
Output:
[Link]()
print("\n After Sorting:\n") python [Link]
print(list1) After Sorting:
print("Descending Order:\n") [2, 4, 6, 8 , 10]
[Link](reverse=True) Descending Order:
print(list1) [10, 8, 6, 4 , 2]
List Methods in Python Cont..
☞ reverse ():
• In python, reverse() method reverses elements of the list. i.e. the
last index value of the list will be present at 0th index. This method
modifies the original list and it does not return a new list.
Syntax: [Link]()
Example: [Link]
list1=[6,8,2,4,10]
[Link]()
print("\n After reverse:\n")
print(list1)
Output:
python [Link]
After reverse:
[10, 4, 2, 8 , 6]
List Methods in Python Cont..
☞ count():
• In python, count() method returns the number of times an element
appears in the list. If the element is not present in the list, it
returns 0.
Syntax: [Link](item)
Example: [Link]
num=[1,2,3,4,3,2,2,1,4,5,8]
cnt=[Link](2)
print("Count of 2 is:",cnt)
cnt=[Link](10)
print("Count of 10 is:",cnt) Output:
python [Link]
Count of 2 is: 3
Count of 10 is: 0
List Methods in Python Cont..
☞ index():
• In python, index () method returns index of the passed element. If
the element is not present, it raises a ValueError.
• If list contains duplicate elements, it returns index of first
occurred element.
• This method takes two more optional parameters start and end
which are used to search index within a limit.
Syntax: list. index(item [, start[, end]])
Example: [Link] Output:
list1=['p','y','t','o','n','p'] python [Link]
print([Link]('t')) 2
Print([Link]('p')) 0
Print([Link]('p',3,10)) 5
Print([Link]('z')) ) Value Error
List Methods in Python Cont..
☞ insert():
• In python, the insert() method inserts the item at the given index,
shifting items to the right.
Syntax: [Link](index,item)
Example: [Link]
num=[10,20,30,40,50]
[Link](4,60)
print(num)
[Link](7,70) Output:
print(num)
python [Link]
[10, 20, 30, 40, 60, 50]
[10, 20, 30, 40, 60, 50, 70]
List Methods in Python Cont..
☞ pop():
• In python, pop() element removes an element present at specified
index from the list.
Syntax: [Link](index)
Example: [Link]
num=[10,20,30,40,50]
[Link]()
print(num)
[Link](2)
Output:
print(num)
[Link](7) python [Link]
print(num) [10, 20, 30, 40]
[10, 20, 40]
IndexError: Out of range
List Methods in Python Cont..
☞ clear():
• In python, clear() method removes all the elements from the list.
It clears the list completely and returns nothing.
Syntax: [Link]()
Example: [Link]
num=[10,20,30,40,50]
[Link]()
print(num)
Output:
python [Link]
[]
List Methods in Python Cont..
☞ Extend():
The extend() method adds the items in list2 to the end of the list.
Syntax: [Link](list2)
Example: [Link]
list=[1,3,2]
list1=[0,5,6]
[Link](list1)
print(list) Output:
[1, 3, 2, 0, 5, 6]
Iterating a List
• A list can be iterated by using a for - in loop. A simple list
containing four strings can be iterated as follows..
Example: “[Link]”
lang=['python','c','java','php‘]
print("The list items are \n")
for i in lang:
print(i)
Output:
python [Link]
The list items are
python
c
java
php
How to delete or remove elements from a list?
Example:
“[Link]”
num = [1,2,3,4,5]
print(num)
del num[1]
print(num)
del num[1:3] Output:
print(num) python [Link]
del num[:] [1, 2, 3, 4, 5]
[1, 3, 4, 5]
[1, 5]
[]
Nested list
• A list inside another list is called a nested list and you can get
the behavior of nested lists in Python by storing lists within the
elements of another list.
• You can traverse through the items of nested lists using the for
loop.
• The syntax for nested lists is
Ex: nested_list=[[item1,item2,item3],
[item4,item5,item6],
[item7,item8,item9]]
nested_list[0]= [item1,item2,item3]
nested_list[1]= [item4,item5,item6]
nested_list[2]= [item7,item8,item9]
nested_list[0][1]=[item2]
• list=[]
• list1=[1,2,3]
• list2=[4,5,6]
• list3=[7,8,9]
• [Link](list1)
• [Link](list2)
• [Link](list3)
• list
• [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
• list[0]
• [1, 2, 3]
• list[1]
• [4, 5, 6]
• list[2]
• [7, 8, 9]
• list[0][1]
• 2
• list[1][2]
• 6
• list[2][1]
• 8
Dictionaries
A dictionary is mutable and is another container type that can store any
number of Python objects, including other container types.
• Dictionaries consist of pairs (called items) of keys and their corresponding
values.
• Python dictionaries are also known as associative arrays or hash tables.
•dict={"v":"violet","o":"orange","b":"blue","y":"yellow"}
Creating Dictionary:
It is a collection of an unordered set of key:value pairs which are enclosed
in curly braces. The key value pairs are seperated by commas.
Eg: Alice: 2341
The words to the left of colon are called as keys and the words to the right
of the colon are called as values.
The dictionary is indexed by keys. Dictionary keys are case sensitive.
Syntax: dictionary_name ={key_1:value_1, key_2:value_2,
key_3:value_3….key_n:value_n}
Ex:
dict={"v":"violet","o":"orange","b":"blue","y":"yellow"}
print(dict)
output:
{'v': 'violet', 'o': 'orange', 'b': 'blue', 'y': 'yellow'}
Mixed Dictionary:
The keys and their associated values can be of different types.
Ex:
mixed_dict={"A":65,"a":97,66:"B",98:"b" ,0:48}
print(mixed_dict)
output:
{'A': 65, 'a': 97, 66: 'B', 98: 'b', 0: 48}
How to Create Empty Dictionary:
Empty dictionary can be created with a pair of curly braces without any key
value pairs.
Syntax: dictionary_name={}
Ex:
dict1={}
print(dict1)
{}
By using dict() function:
• The built-in dict() function is used to create dictionary. The syntax for dict()
function when the optional keyword arguments used is,
• If no keyword argument is given, an empty dictionary is created. If
keyword arguments are given, the keyword arguments and their values of
the form kwarg = value are added to the dictionary as key:value pairs.
For example,
numbers=dict()
print(numbers)
output:
{}
By passing Keyword arguments in dict() functions:
Syntax: dict([**kwarg])
Ex:
dict1=dict(one=1,two=2,three=3)
print(dict1)
Output:
{'one': 1, 'two': 2, 'three': 3}
Acessing and modifying key: value pairs in Dictionaries:
Syntax for accessing the value for a key in dictionary is,
dictionary_name[key].
Ex:
dict1={“one”: 1, “two”: 2, “three”: 3}
dict1["one"]
Output:
1
modifying the value of existing key or adding a new key:
• The syntax for modifying the value of an existing key or for
adding a new key:value pair to a dictionary is,
• dictionary_name[key] = value
Ex:
Adding key:value pair to dict:
dict1={'one': 1, 'two': 2, 'three': 3}
dict1["four"]=4
print(dict1)
Output:
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
dict1["one"]=2
print(dict1)
Output:
{'one': 2, 'two': 2, 'three': 3, 'four': 4}
Built-in Functions :
• Built-in Functions in dictionaries are:
• len()
• any()
• all()
• Sorted()
len():
Returns the number of items (key:value pairs) in dictionary
Ex:
dict1={'one': 2, 'two': 2, 'three': 3, 'four': 4}
len(dict1)
Output:
4
any() function:
The any() function returns True if any item in an iterable are true,
otherwise it returns False. If the iterable object is empty, the any() function
will return False.
Ex:
>>>dict1={'one': 2, 'two': 2, 'three': 3, 'four': 4}
any(dict1)
Output:
True
>>>dict3={1:12,"False":13}
>>>any(dict3)
Output: True
>>>dict3={0:13, 0:6}
>>>any(dict3)
Output: False
all() function:
Returns true value if all the keys in the dictionary are True else
returns false
Ex:
dict1={'one': 2, 'two': 2, 'three': 3, 'four': 4}
all(dict1)
Output:
True
dict2={0:"A",1:"B",2:"C"}
all(dict2)
Output:
False
sorted() function:
Returns a list of items, which are sorted based on dictionary keys
Ex:
dict={"one":1,"two":2,"three":3,"four":4}
sorted(dict) # sorted in ascending order.
['four', 'one', 'three', 'two']
print([Link]("five"))
None
[Link]("five",5)
5
• Clear() function:
• The clear() method removes all the key:value pairs from the
dictionary.
Syntax: dictionary_name. clear()
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
print(dict1)
{}
Popitem():
It removes and returns an arbitrary tuple pair from the
dictionary. Top of the dictionary is popped out.
syntax: dictionary_name.popitem
For Example:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
Output:
('four', 4)
Pop():
It removes the key from the dictionary and returns its value.
Syntax: dictionary_name.pop(key)
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]("one")
Output:
1
Values():
It returns the view consisting of all the values in the dictionary.
syntax: dictionary_name.values()
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
Output:
dict_values([1, 2, 3, 4])
Keys():
It returns the view consisting of all the keys in the dictionary.
syntax: dictionary_name.keys()
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
Output:
dict_keys(['one', 'two', 'three', 'four'])
Items():
The items() method returns a new view of dictionary’s key and
value pairs as tuples.
Syntax: dictionary_name. items()
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
Output:
dict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4)])
fromKeys():
The fromkeys() method creates a new dictionary from the given
sequence of elements with a value provided by the user.
• Syntax: dictionary_name.fromkeys(seq [, value])
For ex:
dict1={"apple":4,"orange":9,"mango":6}
dict2=[Link](dict1)
dict2
{'apple': None, 'orange': None, 'mango': None}
dict3=[Link](dict1,8)
dict3
{'apple': 8, 'orange': 8, 'mango': 8}
Update() function:
This function updates the key value pairs and is automatically added to the
dictionary.
• Syntax: dictionary_name.update([other])
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]({"five":5})
print(dict1)
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
[Link]({"six":6,"seven":7})
print(dict1)
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7}
• setdefault()
• The setdefault() method returns a value for the key present in
the dictionary. If the key is not present, then insert the key
into the dictionary with a default value and return the default
value.
• If key is present, default defaults to None, so that this method
never raises a KeyError.
Syntax: dictionary_name.setdefault (key[, default])
Ex:
dict1={"apple":4,"orange":9,"mango":6}
[Link]("apple")
4
[Link]("strawberry")
dict1
{'apple': 4, 'orange': 9, 'mango': 6, 'strawberry': None}
[Link]("pear",16)
16
dict1
{'apple': 4, 'orange': 9, 'mango': 6, 'strawberry': None, 'pear': 16}
Nested dictionaries:
Syntax: dictionary_name[“dict_marks”]
The dictionairies can be defined inside other dictionary
– CANNOT be concatenated
– CANNOT be repeated
– Can be nested
e.g., d = {"first":{1:1}, "second":{2:"a"}}
Nested Dictionary
In Python, a nested dictionary is a dictionary inside a dictionary. It's a
collection of dictionaries into one single dictionary.
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
Here, the nested_dict is a nested dictionary with the dictionary dictA and
dictB They are two dictionary each having own key and value.
Ex 1:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people)
Output:
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22',
'sex': 'Female'}}
Ex 2: Accessing the Elements using the [ ] syntax
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
Output: John
27
Male
Tuple in Python
Tuple Creation
Tuple in Python
• In python, a tuple is a sequence of immutable elements or items.
• Tuple is similar to list since the items stored in the list can be
changed whereas the tuple is immutable and the items stored in
the tuple cannot be changed.
• A tuple can be written as the collection of comma-separated
values enclosed with the small brackets ( ).
Syntax: var = ( value1, value2, value3,…. )
Example: “[Link]”
t1 = () Output:
t2 = (123,"python", 3.7) python [Link]
t3 = (1, 2, 3, 4, 5, 6) ()
t4 = ("C",) (123, 'python', 3.7)
print(t1) (1, 2, 3, 4, 5, 6)
print(t2) ('C',)
print(t3)
print(t4)
Tuple Indexing
Tuple Indexing in Python
• Like list sequence, the indexing of the python tuple starts from
0, i.e. the first element of the tuple is stored at the 0th index,
the second element of the tuple is stored at the 1st index, and
so on.
• The elements of the tuple can be accessed by using the slice
operator [].
Example:
mytuple=(‘banana’,’apple’,’mango’,’tomato’,’berry’)
• mytuple[0]=”banana” mytuple[1:3]=[”apple”,”mango”]
• mytuple[2]=”mango”
Tuple Indexing in Python cont…
• Unlike other languages, python provides us the flexibility to use
the negative indexing also. The negative indices are counted
from the right.
• The last element (right most) of the tuple has the index -1, its
adjacent left element is present at the index -2 and so on until
the left most element is encountered.
Example: mytuple=(‘banana’,’apple’,’mango’,’tomato’,’berry’)
• mytuple[-1]=”berry” mytuple[-4:-2]=[“apple”,mango”]
• mytuple[-3]=”mango”
Tuple Operators
Tuple Operators in Python
It is known as concatenation operator used to concatenate two
+ tuples.
It is known as repetition operator. It concatenates the multiple
* copies of the same tuple.
It is known as slice operator. It is used to access the item from
[] tuple.
It is known as range slice operator. It is used to access the range
[:] of items from tuple.
It is known as membership operator. It returns if a particular
in item is present in the specified tuple.
Example: “[Link]”
num=(1,2,3,4,5)
lang=('python','c','java','php')
print(num + lang) #concatenates two tuples
print(num * 2) #concatenates same tuple 2 times
print(lang[2]) # prints 2nd index value
print(lang[1:4]) #prints values from 1st to 3rd index.
print('cpp' in lang) # prints False
print(6 not in num) # prints True
Example: “[Link]”
tup=('python','c','java','php')
Output:
tup[3]="html" python [Link]
print(tup)
del tup[3] 'tuple' object does not
print(tup) support item assignment
del tup
'tuple' object doesn't
support item deletion
Tuples are unchangeable, meaning that you cannot change, add, or remove
items once the tuple is created.
Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable
Example: “[Link]”
lang=('python','c','java','php')
print("The tuple items are \n")
for i in lang:
print(i)
Output:
python [Link]
The tuple items are
python
c
java
php
Built in functions used on tuples
Tuples Functions in Python
• Python provides various in-built functions which can be used
with tuples. Those are
• len() • tuple()
• sum() • sorted()
☞len():
• In Python, len() function is used to find the length of tuple,i.e it
returns the number of items in the tuple.
Syntax: len(tuple)
☞sum ():
• In python, sum() function returns sum of all values in the tuple. The
tuple values must in number type.
Syntax: sum(tuple)
Example: [Link]
t1=(1,2,3,4,5,6)
print("Sum of tuple items :",sum(t1))
Output:
python [Link]
Sum of tuple items : 21
Tuple Functions in Python Cont..
☞sorted ():
• In python, The sorted() function returns a sorted copy of the tuple
as a list while leaving the original tuple untouched.
• .Syntax: sorted(tuple)
Example: [Link]
num=(1,3,2,4,6,5)
lang=('java','c','python','cpp')
print(sorted(num))
Print(sorted(num,reverse=True)
print(sorted(lang))
Output:
[1, 2, 3, 4, 5, 6]
['c', 'cpp', 'java', 'python‘]
Tuple Functions in Pytho n Cont..
☞tuple ():
• In python, tuple() is used to convert given sequence (string or list)
into tuple.
Syntax: tuple(sequence)
Example: [Link]
str="python"
Output:
t1=tuple(str)
python [Link]
print(t1) ('p', 'y', 't', 'h', 'o', 'n‘)
num=[1,2,3,4,5,6] (1, 2, 3, 4, 5, 6)
t2=tuple(num)
print(t2)
Tuple Functions in Pytho n Cont..
☞tuple ():
• In python, tuple() is used to convert given sequence (string or list)
into tuple.
Syntax: tuple(sequence)
Example: [Link]
str="python"
Output:
t1=tuple(str)
python [Link]
print(t1) ('p', 'y', 't', 'h', 'o', 'n‘)
num=[1,2,3,4,5,6] (1, 2, 3, 4, 5, 6)
t2=tuple(num)
print(t2)
Tuple Methods in Python Cont..
☞count():
• In python, count() method returns the number of times an element
appears in the tuple. If the element is not present in the tuple, it
returns 0.
Syntax: [Link](item)
Example: [Link]
num=(1,2,3,4,3,2,2,1,4,5,8)
cnt=[Link](2)
print("Count of 2 is:",cnt)
cnt=[Link](10)
print("Count of 10 is:",cnt) Output:
python [Link]
Count of 2 is: 3
Count of 10 is: 0
Tuple Methods in Python Cont..
☞index():
• In python, index () method returns index of the passed element. If
the element is not present, it raises a ValueError.
• If tuple contains duplicate elements, it returns index of first
occurred element.
• This method takes two more optional parameters start and end
which are used to search index within a limit.
Syntax: [Link](item [, start[, end]])
Example: [Link] Output:
t1=('p','y','t','o','n','p') python [Link]
print([Link]('t')) 2
Print([Link]('p')) 0
Print([Link]('p',3,10)) 5
Print([Link]('z')) ) Value Error
Relation between Tuples and Lists
• Tuples are immutable, and usually, contain a heterogeneous
sequence of elements that are accessed via unpacking or
indexing.
• Lists are mutable, and their items are accessed via indexing.
• Items cannot be added, removed or replaced in a tuple.
• Ex:
• tuple=(10,20,30,40,50)
• tuple[0]=15
• Traceback (most recent call last):
• File "<pyshell#5>", line 1, in <module>
• tuple[0]=15
• TypeError: 'tuple' object does not support item assignment
Relation between Tuples and Lists
Convert tuple to list:
X = (10,20,30,40,50)
tuple_to_list = list(x)
print(tuple_to_list)
[10, 20, 30, 40, 50]
• lang=["c","c++","java","python"]
• tuple=(10,20,30,40,50,lang)
• Print(tuple)
• (10, 20, 30, 40, 50, ['c', 'c++', 'java', 'python'])
• [Link]("php")
• lang
• ['c', 'c++', 'java', 'python', 'php']
• tuple
• (10, 20, 30, 40, 50, ['c', 'c++', 'java', 'python', 'php'])
Relation between Tuples and dictionaries
• Tuples can be used as key:value pairs to build dictionaries. For
example,
num=(("one",1),("two",2),("three",3))
tuple_to_dict=dict(num)
print(tuple_to_dict)
{'one': 1, 'two': 2, 'three': 3}
num
(('one', 1), ('two', 2), ('three', 3))
• The tuples can be converted to dictionaries by passing the tuple
name to the dict() function. This is achieved by nesting tuples
within tuples, wherein each nested tuple item should have two
items in it .
• The first item becomes the key and second item as its value when
the tuple gets converted to a dictionary
• The method items() in a dictionary returns a list of tuples
where each tuple corresponds to a key:value pair of the
dictionary. For example,
• dict1={"y":"yellow","o":"orange","b":"blue"}
• [Link]()
• dict_items([('y', 'yellow'), ('o', 'orange'), ('b', 'blue')])
• for symbol,colour in [Link]():
• print(symbol," ",colour)
Output:
• y yellow
• o orange
• b blue
• Tuple packing and unpacking:
The statement t = 12345, 54321, 'hello!' is an example of tuple packing.
t=12345,54321,'hello!'
t
(12345, 54321, 'hello!')
The values 12345, 54321 and 'hello!' are packed together into a tuple.
The reverse operation of tuple packing is also possible. For example,
tuple unpacking
x,y,z=t
x
12345
y
54321
z
'hello!‘
Tuple unpacking requires that there are as many variables on the left side of the
equals sign as there are items in the tuple.
Note that multiple assignments are really just a combination of tuple packing and
unpacking.
t = 12345,54321,'hello'
t
(12345, 54321, 'hello')
# The values 12345, 54321 and ‘hello’ are packed together
into a tuple
# The reverse operation (tuple unpacking) of tuple packing is
also possible.
x, y, z=t
x
12345
y
54321
z
'hello'
• Populating tuples with items:
• You can populate tuples with items using += operator and also by
converting list items to tuple items.
• Example: Ex: 2
tuple_items=() x=()
tuple_items+=(10,) y=x+(10,)
tuple_items+=(20,30,) y
(10,)
print(tuple_items) y=y+(20,30)
(10, 20, 30) y
(10, 20, 30)
• converting list to tuple :
list_items=[]
list_items.append(50)
list_items.append(60)
list_items
[50, 60]
tuple1=tuple(list_items)
print(tuple1)
(50, 60)
• Using zip() Function
• The zip() function makes a sequence that aggregates elements from each
of the iterables (can be zero or more). The syntax for zip() function is,
• zip(*iterables)
• An iterable can be a list, string, or dictionary.
• It returns a sequence of tuples, where the i-th tuple contains the i-th
element from each of the iterables.
For Example,
x=[1,2,3]
y=[4,5,6]
zipped=zip(x,y)
list(zipped)
[(1, 4), (2, 5), (3, 6)]
Here zip() function is used to zip two iterables of list type
To loop over two or more sequences at the same time, the
entries can be paired with the zip() function. For
example,
symbol=("y","o","b","r")
colour=("yellow","orange","blue","red")
for symbol,colour in zip(symbol,colour):
print(symbol," ",colour)
Output:
y yellow
o orange
b blue
r red
Since zip() function returns a tuple, you can use a for loop
with multiple iterating variables to print tuple items.
• SETS:
• A set is an unordered collection with no dupli- cate items.
• Sets also support mathematical operations, such as union,
intersection, difference, and symmetric difference.
• Curly braces { } or the set() function can be used to create sets with
a comma-separated list of items inside curly brackets { }.
• To create an empty set you have to use set() and not { } as the
later creates an empty dictionary.
Set operations:
Example:
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
Output: {'pear', 'orange', 'banana', 'apple'}
>>> 'orange' in basket
Output: True
>>> 'crabgrass' in basket
Output: False
Difference:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}
a-b
{'r', 's', 'd', 'b'}
It Displays letters present in a, but not in b, are printed.
Union:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}
a|b
{'b', 'z', 'c', 'a', 'r', 'd', 'm', 'l', 's'}
Letters present in set a and set b are printed.
Intersection:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}
a&b
{'c', 'a'}
Letters present in both set a and set b are printed
Symmetric Difference:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}
a^b
{'z', 'b', 'r', 'd', 'm', 'l', 's'}
Letters present in set a or set b, but not both are printed.
Length function():
>>>basket={'apple','orange','apple','pear','apple','banana'}
>>>print(basket)
>>>{'pear', 'apple', 'orange', 'banana'}
>>>len(basket)
4
Total number of items in the set basket is found using the len()
function
Sorted function():
>>>sorted(basket)
['apple', 'banana', 'orange', 'pear']
>>>sorted(basket, reverse=True)
['pear', 'orange', 'banana', 'apple']
The sorted() function returns a new sorted list from items in the
set .
Set Methods:
You can get a list of all the methods associated with the set by passing the set
function to dir().
dir(set)
[' and ', ' class ', ' class_getitem ', ' contains ', ' delattr ',
' dir ', ' doc ', ' eq ', ' format ', ' ge ', ' getattribute ',
' getstate ', ' gt ', ' hash ', ' iand ', ' init ', ' init_subclass ',
' ior ', ' isub ', ' iter ', ' ixor ', ' le ', ' len ', ' lt ',
' ne ', ' new ', ' or ', ' rand ', ' reduce ', ' reduce_ex ',
' repr ', ' ror ', ' rsub ', ' rxor ', ' setattr ', ' sizeof ',
' str ', ' sub ', ' subclasshook ', ' xor ', 'add', 'clear', 'copy',
'difference', 'difference_update', 'discard', 'intersection',
'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove',
'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
Set Methods:
Add():
The add() method adds an item to the set set_name.
Syntax: set_name.clear()
basket={"orange","Apple","strawberry","orange" }
basket
{'orange', 'Apple', 'strawberry'}
[Link]("pear")
basket
{'orange', 'Apple', 'strawberry', 'pear'}
Set Methods:
Difference():
• The difference() method returns a new set with items in the set set_name that
are not in the others sets.
• Syntax : set_name.difference(*others)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.difference(flowers)
{'orchid', 'daisies'}
intersection():
• The intersection() method returns a new set with items common to the set
set_name and all others sets.
• Syntax: set_name. Intersection(*others)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.intersection(flowers)
{'roses', 'tulips'}
Symmetric Difference: Set Methods:
The method symmetric difference() returns a new set with items in either
the set or other but not both.
• Syntax : set_name. symmetric_difference(other)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers. symmetric_difference (flowers)
{'orchid', 'lilies', 'daisies', 'sunflowers'}
Union:
• The method union() returns a new set with items from
• the set set_name and all others sets.
• Syntax: set_name.union(*others)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.union(flowers)
{'orchid', 'lilies', 'tulips', 'daisies', 'roses', 'sunflowers'}
Set Methods:
isdisjoint:
• The isdisjoint() method returns True if the set set_name has no items in
common with other set. Sets are disjoint if and only if their intersection is
the empty set.
• Syntax : set_name.isdisjoint(other)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.isdisjoint(flowers)
False
c={"a","b","c","d"}
d={"a","b","c","d"}
[Link](d)
True
Set Methods:
Issuperset():
• The issuperset() method returns True if every element in other set is in the
set set_name.
• Syntax : set_name.issuperset(other)
Ex: x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = [Link](y)
print(z)
Output: True
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = [Link](x)
print(z)
Output: False
Set Methods:
Pop():
• The method pop() removes and returns an arbitrary item from
the set set_name. It raises KeyError if the set is empty.
• Syntax : set_name.pop()
Ex:
d={'b', 'c', 'a', 'd'}
item=[Link]()
print(item)
b
print(d)
{'c', 'a', 'd'}
Pop()
The pop() method for sets in Python does not necessarily remove the last
element. Sets in Python are unordered collections, which means the order of
elements is not guaranteed. When you use pop() on a set, it removes and
returns an arbitrary element from the set. It doesn't specifically target the last
element.
If you need to remove a specific element from the set, you should use the
remove()
x={'q','w','e','r','t','y'}
y=[Link]()
print(y) #returns the poped value
Output: w
print(x)
Output: {'q', 'e', 't', 'r', 'y'}
remove()
The “remove()” method for sets in Python removes the specified element
from the set. However, unlike the ‘pop()’ method, it doesn't return the
removed element; it returns ‘None’ Therefore, when you print the result of
‘[Link](‘r ’)’ , it will print ‘None’.
Ex: x={'q','w','e','r','t','y'}
y=[Link]('r')
print(y) #doesn’t return removed value instead gives “None”
Output: None
print(x)
Output: {'w', 'q', 'e', 't', 'y'} # “r” has been removed from the set
OR
x={'q','w','e','r','t','y'}
[Link]('r')
print(x)
{'w', 'q', 'e', 't', 'y'}
Set Methods:
remove():
• The method remove() removes an item from the set set_name. It raises
KeyError if the item is not contained in the set.
• Syntax : set_name.remove(item)
• Ex:
• c={"a","b","c","d"}
[Link]("a")
print(c)
{'b', 'c', 'd'}
update():
Update the set set_name by adding items from all others sets.
Syntax : set_name.update(*others)
Ex:
c={'b', 'c', 'd'}
d={"e","f","g"}
[Link](d)
print(c)
{'b', 'c', 'f', 'g', 'd', 'e'}
Set Methods:
Discard():
• The discard() method removes an item from the set set_name if it is present.
Syntax: set_name.discard(item)
Ex:
d={"e","f","g"}
[Link]("e")
print(d)
{'f', 'g'}
Clear():
• The clear() method removes all the items from the set set_name.
• Syntax: set_name.clear()
• Ex: alpha={"a","b","c","d"}
• print(alpha)
output: {'a', 'b', 'c', 'd'}
[Link]()
print(alpha)
output: set()
Difference between discard() and remove() in python sets.
The discard() method removes the specified item from the set. This method is
different from the remove() method, because the remove() method will raise an
error if the specified item does not exist, and the discard() method will not.
d={"e","f","g"}
[Link]("e")
print(d)
Output: {'g', 'f'}
d={"e","f","g"}
[Link]("h") # specified item doesn’t exist in set. discard() doesn’t raise error
print(d)
Output: {'g', 'f', 'e'}
d={"e","f","g"}
[Link]("h") #specified item doesn’t exist in set. remove() raises error
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
[Link]("h")
KeyError: 'h'
Traversing of sets
You can iterate through each item in a set using a for loop.
Ex:
alpha={"a","b","c","d"}
print(alpha)
{'a', 'b', 'c', 'd'}
for i in alpha:
print(i)
Output:
a
b
c
d
Frozenset
methods in Frozenset:
1. >>> dir(frozenset)
[' and ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ', ' eq
', ' format ', ' ge ', ' getattribute ', ' gt ', ' hash ', ' init ', '
init_ subclass ', ' iter ', ' le ', ' len ', ' lt ', ' ne ', ' new ', ' or
', ' rand ', ' reduce ', ' reduce_ex ', ' repr ', ' ror ', ' rsub
', ' rxor ', ' setattr ', ' sizeof ', ' str ', ' sub ', ' subclasshook ', '
xor ', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset',
'issuperset', 'symmetric_difference', 'union']
Frozen set is just an immutable version of a Python set object. While elements of a
set can be modified at any time, elements of the frozen set remain the same after
creation.
Sy: frozenset([iterable])
Iterable can be set, dictionary, tuple, etc.
Example 1:
mylist = ['apple', 'banana', 'cherry']
mylist[1]="strawberry“
print(mylist)
Output: ['apple', 'strawberry', 'cherry']
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
print(x)
Output: frozenset({'apple', 'cherry', 'banana'})
x[1]="strawberry"
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
x[1]="strawberry"
TypeError: 'frozenset' object does not support item assignment
Frozenset Methods
• List of methods available for frozenset .For example,
Convert set to frozenset
set1 = {"d","o","g"}
fs=frozenset({"d","o","g"})
print(fs)
Output: frozenset({'d', 'o', 'g'})
Convert list to frozenset:
list=[10,20,30]
lfs=frozenset(list)
print(lfs)
Output: frozenset({10, 20, 30})
Convert dict to frozenset
dict1={"one":1,"two":2,"three":3,"four":4}
dfs=frozenset(dict1)
print(dfs)
Output: frozenset({'four', 'one', 'three', 'two'})
• frozenset used as a key in dictionary and item in set:
item=frozenset(["g"])
dict1={"a":95,"b":96,"c":97,item:6}
print(dict1)
{'a': 95, 'b': 96, 'c': 97, frozenset({'g'}): 6}
EX:
item=frozenset(["g"])
set={"a","b","c",item}
print(set)
{frozenset({'g'}), 'a', 'c', 'b'}
Files in Python
Files in Python
☞ FILE HANDLING:
It is a mechanism by which we can read data of disk
files in python program or write back data from
python program to disk files.
In Windows use backslash (\) and in Linux use forward slash (/) to
separate the components of a path.
The backslash (or forward slash) separates one directory name from
another directory name in a path and it also divides the file name from
the path leading to it.
Backslash (\) and forward slash (/) are reserved characters and you
cannot use them in the name for the actual file or directory.
Files in python
[Link]
[Link]/redirect
File and Directory names in Windows are not case sensitive while in
Linux it is case sensitive.
For example, the directory names ORANGE, Orange, and orange are
the same inWindows but are different in Linux Operating System.
In Windows, volume designators (drive letters) are case-insensitive. For
example, "D:\" and "d:\" refer to the same drive.
Files in python
The reserved characters that should not be used in naming files and
directories are < (less than), > (greater than),: (colon), " (double
quote), / (forward slash), \ (backslash), | (vertical bar or pipe), ?
(question mark) and * (asterisk).
myfile = open(“d:\\mydata\\[Link]”,”r”)
Here we are accessing “[Link]” file stored in separate
location i.e. d:\mydata folder.
At the time of giving path of file we must use double
backslash(\\) in place of single backslash because in python single
slash is used for escape character and it may cause problem like if
the folder name is “nitin” and we provide path as
d:\nitin\[Link] then in \nitin “\n” will become escape character
for new line, SO ALWAYS USE DOUBLE BACKSLASH IN PATH.
Files in python
Opening File:
myfile = open(“d:\\mydata\\[Link]”,”r”)
another solution of double backslash is using “r” before
the path making the string as raw string i.e. no special meaning
attached to any character as:
myfile = open(r“d:\mydata\[Link]”,”r”)
In the above example “myfile” is the file object or file handle or
file pointer holding the reference of disk file.
In python we will access and manipulate the disk file through
this file handle only.
Raw String
A raw string is created by prefixing the character r or R to the string.
In Python, a raw string ignores all types of formatting within a string
including the escape characters.
Ex 1: Without raw string
s = 'Hi\nHello'
print(s)
Output: Hi
Hello
Ex 2: With raw string
raw_s = r'Hi\nHello'
print(raw_s)
Output: Hi\nHello
Files in python
Access modes of the File:
Mode Description
“r” Opens the file in read only mode and this is the default mode.
“w” Opens the file for writing. If a file already exists, then it’ll get overwritten. If the file
does not exist, then it creates a new file.
“a” Opens the file for appending data at the end of the file automatically. If the file does
not exist it creates a new file.
“r+” Opens the file for both reading and writing
“w+” Opens the file for reading and writing. If the file does not exist it creates a new file. If
a file already exists then it will get overwritten.
“a+” Opens the file for reading and appending. If a file already exists, the data is appended.
If the file does not exist it creates a new file.
Files in python
Access modes of the File:
Mode Description
“x” Creates a new file. If the file already exists, the operation fails.
“rb+” Opens the file for both reading and writing in binary format.
Files in python
Example program:
# Create a file:
fp=open("[Link]","x")
You should not be writing to the file in the finally block, as any exceptions raised
there will not be caught by the except block.
The except block executes if there is an exception raised by the try block.
The finally block always executes regardless of whatever happens.
Files in python
Use of “with” statement to open and close files:
Instead of using try-except-finally blocks to handle file opening and closing operations,
a much cleaner way of doing this in Python is using the with statement.
You can use a with statement in Python such that you do not have to close the file
handler object.
Example: opening a file, manipulating a file and closing it with
open(“[Link]”,”w”) as f:
[Link](“Hello Python!”)
The with statement creates a context manager and it will automatically close the file
handler object for you when you are done with it, even if an exception is raised on the
way, and thus properly managing the resources.
Files in python
Use of “with” statement to open and close files:
Ex:
file_input = input('File Name: ') File Name:
[Link]
with open(file_input, 'w') as info:
klebca
for x in range(10): klebca
[Link]('klebca \n') klebca
klebca
klebca
with open(file_input, 'r') as info: klebca
data=[Link]() klebca
klebca
print(data) klebca
klebca
Files in python
File Object Attributes
Once a file is opened , we have one file object, which contain various info related to that
file.
1. [Link] – Returns true if the file is closed, False otherwise
2. [Link] – Returns access mode with wich file was opened
3. [Link]- Name of the file
Ex:
f=open("[Link]","w")
print("Name of the file:",[Link])
print("Closed or not :",[Link])
print("Opening mode :",[Link])
Output:
Name of the file: [Link]
Closed or not : False
Opening mode : w
File Methods to Read and Write Data:
Method Syntax Description
read() File_handler.read([size]) Used to read the contents of a file up to the size and return it as a string
write() File_handler.write(string) This method will write the contents of the strings to the file.
writelines() File_handle.writelines(sequence) This method will write a sequence of strings to the file
tell() File_handler.tell() File handler’s current position within the file is measured in bytes from the
beginning of the file
seek() File_handler.seek(offset, Change the file handler’s position. Position is computed by adding offset to
from_what) reference point. Reference point is selected by the from_what argument.
File Methods to Read and Write Data:
Ex: Output:
One
f=open("[Link]","r")# opening a file Two
line1 = [Link]() # reading a line Three
print(line1) ['five\n', 'six\n', 'seven\n', 'eight\n']
line2 = [Link]() # reading a line O
print(line2) n
line3 = [Link]() # reading a line e
print(line3)
line4 = [Link]() # reading a line
print(line4)
lines=[Link]()
print(list(lines))
for ch in line1:
print(ch)
[Link]()
..
writelines():
Ex:
f = open("[Link]", “w")
[Link](["See you soon!", "Over and out."])
[Link]()
#open and read the file :
f = open("[Link]", "r")
print([Link]())
[Link]()
Output:
See you soon!Over and out.
..
writelines():
Ex:
f = open("[Link]", “w")
[Link](["See you soon!", "Over and out."])
[Link]()
#open and read the file
f = open("[Link]", "r")
print([Link]())
fseek(5,0)
print([Link]())
[Link]()
Output:
See you soon!Over and out.
ou soon!Over and out.
..
Read Binary File:
#Opening a binary File in Read Only Mode
with open(r'C:\Test\\[Link]', mode='rb') as binaryFile:
lines = [Link]()
print(lines)
We are reading all the lines in the file in the lines variable above and print all the lines read in
form of a list.
Write Binary File
#Opening a binary File in Write Mode
with open('C:\\Test\\[Link]', mode='wb') as binaryFile:
#Assiging a Binary String
lineToWrite = b'You are on Banglore.'
#Writing the binary String to File.
[Link](lineToWrite)
#Closing the File after Writing
[Link]()
The Pickle Module
The pickle module implements binary protocols for serializing and de-serializing a Python
object structure.
This module can take any python object and convert it to a string representation (byte
stream).
If you have an object x and a file handler f, then it can be opened for writing as below
[Link](x,f)
Reconstructing the object from the string representation is called as unpickling.
If f is the file handler then the way to unpickle the object is,
x = [Link](f) The load method reads a pickled object and reconstructs the object.
The pickle module is used for implementing binary protocols for
serializing and de-serializing a Python object structure.
Pickling: It is a process where a Python object hierarchy is
converted into a byte stream.
Unpickling: It is the inverse of the Pickling process where a byte
stream is converted into an object hierarchy.
dumps() – This function is called to serialize an object hierarchy.
loads() – This function is called to de-serialize a data stream.
writing operation in binary files
import pickle
l=[10,43,76,33]
x=open("yt_l.dat","wb") #mode 'wb' for writing information
[Link](l,x) #list name, file object name
print("Data Successfully written into File")
[Link]()
Reading operation from Binary File
import pickle
x=open("yt_l.dat","rb") #mode 'rb' for reading information
y=[Link](x)
print(y)
[Link]
Writing and Reading operations in Binary files
import pickle
l=eval(input("enter the list:"))
x=open("yt_l.dat","w+b")
[Link](l,x) #list name, file object name
print("Data Successfully written into File")
[Link](0) #to read information from begining, so the position will be zero'0'
y=[Link](x)
print(y)
[Link]()
#in the above program if you don't use seek() method it throws an error because the
cursor will be pointing at the end of the string. To read data from beginning we use
seek(0) - 0 is the position
Output: enter the list:[17,'preetha',11.5]
Data Successfully written into File
€]q (KX preethaqG@' e. (in Notepad)
#writing data into file using dump()
[17, 'preetha', 11.5]
#reading data from file using load() data will be
printed in python shell after reading
Characteristics of the CSV format
Characteristics of the CSV format are:
Each record is located on a separate line, delimited by a line break
(CRLF)
A line break may or may not be present at the end of the last record in
the file.
Optional header line may appear as the first line of the file.
Commas are to be used to separate the fields in each record. Each line
should have the same number of fields throughout the file.
Double quotes may or may not be used to enclose each field.
Write a program in python to read data from an external
file test_meet.csv
Step 1: open Notepad and enter the data. Save the file as test_meet.csv
Note: The file test_meet.csv has to be saved where the python shell is
available. If not it is mandatory to give Absolute path.
Reading data from CSV file
import csv
with open('test_meet.csv') as cs:
csv_reader=[Link](cs)
for line in csv_reader:
print(line)
[Link]()
Output:
Reading and Writing CSV (Comma Separated Values) Files
[Link]() method is used to read from a CSV file.
[Link](csvfile): csv is the module name and csvfile is the file
object. This returns a csv reader object which will iterate over lines
in the given csvfile.
[Link](csvfile): This method returns a csv writer object
responsible for converting the user’s data into comma separated
strings on the given file like object.
[Link](row): csvwriter is the object returned by
writer() method and writerow() method will write the row
argument to the writer() method’s file object.
[Link](rows): writerows() method will write all the
rows argument to the writer() method’s file object.
Writing Data into CSV file
import csv
with open('test_demo.csv','w+') as cs1:
csv_writer = [Link](cs1)
csv_writer.writerow(['1009','Rahul','India'])
print("data inserted successfully")
[Link](0)
csv_reader = [Link](cs1)
csv_reader = [Link](cs1)
Syntax:
Class computer:
The statements inside a class definition will usually be function definitions. Because of these
functions are indented under a class, they are called methods. Methods are a special kind of
method attributes.
object_name.data_attribute_name
object_name.data_attribute_name = value
where value can be of integer, float, string types, or another object itself. The
syntax to call method attribute is,
object_name.method_attribute_name()
Syntax:
def init (self,parameter1,parameter2……parameter):
statements(s)
The Constructor Method:
It starts with the def keyword, like all other functions in Python.
student_1.display()
student_2.display()
student_3.display()
Using Object As Argument:
• An object can be passed to a calling function as an argument.
• Ex:
o Numeric values(int,float,complex,etc)
o collections/ Sequences(list,tuple,dictionary,etc)
# Define a class
class Animal:
def __init__(self, name):
[Link] = name
def main():
number = Sum(4, 5)
returned_object = number.add_sum()
print("Sum:", returned_object.result)
print("ID:", id(returned_object))
print("Is instance of Sum class?", isinstance(returned_object, Sum))
if __name__ == "__main__":
main()
Ex: Return Values from methods :
class student:
def init (self,m1,m2,m3):
self.m1=m1 #The constructor initializes instance variables (self.m1, self.m2, self.m3)
self.m2=m2
self.m3=m3
def avg(self):
return((self.m1+self.m2+self.m3)/3)
std1=student(34,56,78)
print([Link]())
std2=student(89,65,45) Output:
print([Link]()) 116.0
169.0
Class Attributes and Data attributes
Class Attributes:
Are Class variables that is shared by all objects of a class.
Data Attributes
Are instance variables unique to each object of a class.
class Dog:
kind ='Canine'
d=Dog('Fido')
e=Dog("Buddy")
print(f"{[Link]}") Output:
Canine
print(f"{[Link]}") Canine
print(f"{d.dog_name}") Fido
print(f"{e.dog_name}") Buddy
Encapsulation
• Encapsulation -> Information hiding
• It is the process of combining variables that store data and methods that
work on those variables into a single unit called class.
• Abstraction -> Implementation hiding
• Abstraction is a process where you show only “relevant” variables that are
used to access data and “hide” implementation details of an object from the
user.
Ex:
1. class Arithmetic_op:
7. Real_object = Arithmetic_op(3,4)
8. print(Real_object.add()) Output:
7
Inheritance:
• Inheritance is a powerful feature in object oriented programming
• It generally means “inheriting or transfer of characteristics from
parent to child class without any modification”.
• The new class is called the derived/child class and the one from
which it is derived is called a parent/base class.
Multilevel Inheritance:
• Multi-level inheritance enables a derived class to inherit
properties from another derived class, this process is known
as multilevel inheritance.
Hierarchical Inheritance:
• In which there is single base class and multiple derived class
•Hierarchical level inheritance enables more than one derived
class to inherit properties from a parent class.
Multiple Inheritance:
• Multiple level inheritance enables one derived class to inherit
properties from more than one base class.
Syntax:
class DerivedClassName(Base_1, Base_2, Base_ 3):
<statement-1>
.
<statement-N>
Derived class DerivedClassName is inherited from
multiple base classes, Base_1, Base_2, Base_3.
Accessing the inherited variables and methods:
class person:
x=person("renuka",“T")
print(" person details")
[Link]()
class student(person):
def display(self):
print(" student details")
x=student(“Joshitha",”K")
[Link]()
[Link]()
Accessing the inherited variables and methods:
• The derived class init () method contains its own parameters along with the
parameters specified in the init () method of base class.
• No need to specify self while invoking base class init () method using super().
Usage of Super() method:
• Ex: •The init () method for child class take two
parameters name and txt1.
class Parent: •With in the init () method of child derived
def init (self, txt1): class, the init () method of the person base
self. message = txt1
class is invoked using super() function.
def printmessage(self): •when you use super() function to invoke base
print([Link]) class init () method, you need to pass the
txt1 parameter as an argument to init ()
class Child(Parent): function to match the method signature.
def init (self,name,txt1): •On invoking the base class init () method,
super(). init (txt1) the txt1 value gets assigned to message data
[Link]=name attribute in the person base class.
def display(self):
print(f"{[Link]},{[Link]}")
def printmessage(self):
print(self.txt1) •When the same method exists in both
the base class and the derived class, the
class Child(Parent): method in the derived class will be
def init (self,name,txt1): executed .
super(). init (txt1) •Derived class method overrides the
[Link]=name base class method.
def printmessage(self): •You can also directly invoke the base
print(f"{[Link]},{self.txt1}") class printmessage method from within
def invoke_base_class_method(self): the derived class by using super()
super().printmessage() function.
•You need to put super().printmessage()
x = Child("renuka","how are you") under another method within the
[Link]() derived class.
x.invoke_base_class_method()
Multiple Inheritances
Python also supports a form of multiple inheritances. A derived class definition
with multiple base classes looks like this:
Syntax:
class DerivedClassName(Base_1, Base_2, Base_ 3):
<statement-1>
.
.
.
<statement-N>
Derived class DerivedClassName is inherited from multiple base classes,
Base_1, Base_2, Base_3.
MRO:
Method Resolution Order, or “MRO” in short, denotes the way Python
programming language resolves a method found in multiple base classes.
Method Resolution Ordere - MRO
• Method Resolution Order(MRO) it denotes the way a programming
language resolves a method or attribute. Python supports classes inheriting
from other classes.
• The class being inherited is called the Parent or Superclass, while the class
that inherits is called the Child or Subclass.
• In python, method resolution order defines the order in which the base
classes are searched when executing a method. First, the method or
attribute is searched within a class and then it follows the order we specified
while inheriting.
• This order is also called Linearization of a class and set of rules are called
MRO(Method Resolution Order). While inheriting from another class, the
interpreter needs a way to resolve the methods that are being called via an
instance.
Multiple Inheritances
Using Super() function in Multiple Inheritances:
Ex:
class A: Output:
def init (self): Init in C
print("Init In A") Init In A
super(). init () Init In B
Method resolution Order Is :
class B: [<class ' main .C'>, <class ' main .A'>, <class
def init (self): ' main .B'>, <class 'object'>]
print("Init In B")
super(). init ()
obj=C()
print(f" Method resolution Order Is :{[Link]()}")
Multiple inheritance with method overrriding:
class A:
def init (self,fname,mname): class C(A,B):
print("Init In A") def init (self,fname,mname,Lname):
super(). init (mname) print("Init in C")
super(). init (fname,mname)
[Link]=fname
[Link]=Lname
def feature1(self): def feature3(self):
print("feature1 is working") print("feature3 is working")
print(f"{[Link]},{[Link]},{[Link]}")
class B:
def init (self,mname): x=C("nitish","pradsd","k")
print("Init In B") x.feature1()
super(). init () x.feature2()
[Link]=mname x.feature3()
print(f" Method resolution Order Is :{[Link]()}")
def feature2(self):
print("feature2 is working")
Multiple inheritance with method overrriding:
Output:
Init in C
Init In A
Init In B
feature1 is working
feature2 is working
feature3 is working
nitish,pradsd,k
Method resolution Order Is :[<class ' main .C'>, <class ' main .A'>,
<class ' main .B'>, <class 'object'>]
Polymorphism:
• Poly means many and morphism means forms.
• Polymorphism is one of the tenets of Object Oriented Programming (OOP).
• Polymorphism means that you can have multiple classes where each class
implements the same variables or methods in different ways.
Let's take an example:
class Complex:
def init (self, real, imaginary):
[Link] = real
[Link] = imaginary
def add (self, other):
return Complex([Link] + [Link], [Link] + [Link])
def str (self):
return (f"{[Link]} + i{[Link]}“)
complex_number_1 = Complex(4, 5)
complex_number_2 = Complex(2, 3)
complex_number_sum = complex_number_1 + complex_number_2
print(f"Addition of two complex numbers {complex_number_1} and {complex_
number_2} is {complex_number_sum}")
class Circle:
self.r = radius
def perimeter(self): return 2 * pi * self.r
def area(self):
# Initialize the classes
return pi * self.r ** 2
sqr = square(10)
c1 = Circle(4)
print("Perimeter computed for square: ", [Link]()) print("Area computed for
square: ", [Link]()) print("Perimeter computed for Circle: ", [Link]())
print("Area computed for Circle: ", [Link]())
import math
pi = 3.141
class Square:
def __init__(self, length):
self.l = length
def perimeter(self):
return 4 * self.l
def area(self):
return self.l * self.l
class Circle:
self.r = radius
def perimeter(self):
return 2 * pi * self.r
def area(self):
# Initialize the classes
return pi * self.r ** 2
# Create instances of the classes
sqr = Square(10)
c1 = Circle(4)
# Print computed values
print("Perimeter computed for square:", [Link]())
print("Area computed for square:", [Link]())
print("Perimeter computed for Circle:", [Link]())
print("Area computed for Circle:", [Link]())
•Square and Circle are the derived classes
•The derived classes have the methods perimeter() and area()
which are common to both
•But the implementation of these two methods is different in
each of the 2 classes.
• Output:
• Perimeter computed for square: 40
• Area computed for square: 100
• Perimeter computed for Circle: 25.128
• Area computed for Circle: 50.256
DATA VISUALIZATION
Generating Data
DATA VISUALIZATION
Python is used for data-intensive work in
genetics, climate research, sports, political and
economic analysis.
Mathematical Plotting Library is a popular tool
used to make simple plots such as line graphs
and scatter plots.
Plotly package creates visualizations that work
well on digital devices.
Matplotlib is installed using the command
squares =[1,4,9,16,25]
fig, ax = [Link]()
[Link](squares)
[Link]()
PLOTTING A SIMPLE LINE GRAPH
Pyplot is a collection of functions that make
matplotlib work like MATLAB.
Plt is used so that we don’t type [Link]
repeatedly
The [Link] method provides a
way to plot multiple plots on a single figure.
Fig – indicates the entire figure or collection of plots
ax -> represents a single plot
Plot() function is used to plot the data in a meaningful
way
The function [Link]() opens MATplotlib’s viewer
and displays the plot.
CORRECTING THE LINE PLOT (W.R.T X- AXIS)
import [Link] as plt
squares = [1,4,9,16,25]
input_values = [1,2,3,4,5]
fig,ax = [Link]()
[Link](input_values, squares, linewidth = 3)
[Link]()
CHANGING THE LABEL TYPE AND LINE
THICKNESS
import [Link] as plt
squares =[1,4,9,16,25]
input=[1,2,3,4,5]
fig,ax = [Link]()
[Link](input, squares, linewidth=3)
# Set chart title and label axes
[Link]()
EXPLANATION OF PROGRAM
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig, ax = [Link]()
[Link](x,y)
[Link]()
SCATTER PLOT WITH BUILT-IN SEABORN STYLE AND PLOTTING A
SERIES OF POINTS WITH SCATTER
x = [1, 2, 3, 4, 5]
y= [1, 4, 9, 16, 25]
[Link]('seaborn-v0_8')
fig, ax = [Link]()
[Link](x,y,s=100)
[Link]()
CALCULATING THE DATA AUTOMATICALLY
import [Link] as plt
x_values = range(1,1001)
y_values = [x**2 for x in x_values]
[Link]('seaborn-v0_8')
fig, ax = [Link]()
#[Link](x_values,y_values,s=10)
[Link] ([0,1100,0,1100000])
Removes the
extra white
[Link]() spaces around
[Link]('squares_plot.png', bbox_inches='tight') the plot
RANDOM WALKS
Using RANDOM module, python will generate a series of
random decisions each of which is left entirely to change.
You can image a random walk as the path a confused ant
would take if it took every step in a random direction.
Random walks have practical applications in nature,
physics, biology, chemistry, and economics.
def fill_walk(self):
: # keep taking Steps until the walk reaches desired length
while len(self.x_values)<self.num_points
#decide which direction to go and how far to go in that direction.
x_direction= choice([1,-1])
x_distance=choice([0,1])
x_step=x_direction * x_distance rw_visual.py
import [Link] as plt
y_direction= choice([1,-1])
y_distance=choice([0,1]) from random_walk import
y_step=y_direction * y_distance Randomwalk
edgecolor='none',s=10)
[Link](0,0,c='green',edgecolor='none',s=1500)
[Link](rw.x_values[-1], rw.y_values[-1],
c="red",edgecolor='none',s = 1500)
ROLLING DICE WITH PLOTLY:
Python package plotly is used to produce
interactive visualizations.
x_axis_title={'title':'Result'}
y_axis_title={'title':'Frequency of Result'}
my_layout = Layout(title='Histogram of Dice rolling
100 times', xaxis = x_axis_title, yaxis = y_axis_title)
[Link]({'data':data, 'layout' : my_layout})
ROLLING TWO DICE
class Die:
def __init__(self,num_sides=6):
self.num_sides = num_sides
def roll(self):
return randint(1,self.num_sides)
def main():
die1 = Die()
die2 = Die()
results =[]
for roll_num in range(1000):
result = [Link]() + [Link]()
[Link](result)
ROLLING TWO DICE
frequencies =[]
max_result = die1.num_sides + die2.num_sides
for value in range(2,max_result + 1):
frequency = [Link](value)
[Link](frequency)
x_axis_title={'title':'Face of Dice','dtick':1}
y_axis_title={'title':'Frequency of Dice face occurance '}
my_layout = Layout(title='Histogram of Dice rolling 1000 times', xaxis =
x_axis_title, yaxis = y_axis_title)
[Link]({'data':data, 'layout' : my_layout})
if __name__=="__main__":
main()
ROLLING DICE OF DIFFERENT SIZES
die2 = Die(10)
SUMMARY
Visualization of Data – Simple Line Plots using
matplotlib.
Scatter Plots to explore random walks.
with open(r'C:\Users\KLEBCA-
2\Desktop\data\sitka_weather_07-2018_simple.csv','r') as
f:
reader = [Link](f)
header_row = next(reader)
Parsing the csv File Header
import csv
with open(r'C:\Users\KLEBCA-
2\Desktop\data\sitka_weather_07-2018_simple.csv','r') as f:
reader = [Link](f)
header_row = next(reader)
with open(r'C:\Users\KLEBCA-2\Desktop\data\sitka_weather_2018_full.csv','r') as f:
reader = [Link](f)
header_row = next(reader)
# Get dates, and high and low temperatures from this file.
dates, highs, lows = [], [], []
for row in reader:
current_date = [Link](row[2], '%d-%m-%Y')
high = int(row[6])
low = int(row[7])
[Link](current_date)
[Link](high)
[Link](low)
Plotting the Two Data Series
# Plot the high and low temperatures.
[Link]('seaborn-v0_8')
fig, ax = [Link]()
[Link](dates, highs, c='red',alpha=0.5)
[Link](dates, lows, c='green',alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='green',alpha=0.1)
# Format plot.
[Link]("Daily high and low temperatures - 2018", fontsize=14)
[Link]('', fontsize=16)
fig.autofmt_xdate()
[Link]("Temperature (F)", fontsize=14)
[Link]()
Plotting the Highest and Least temperatures in a day
Error Handling in Datasets
Missing data can result in exceptions that crash our programs unless we handle them
properly.
Each time we examine a row, we try to extract the date and the high and low
temperature
.If any data is missing, Python will raise a ValueError and we handle it by printing an
error message that includes the date of the missing data
.After printing the error, the loop will continue processing the next row.
fh = open(r'C:\Users\Admin\Desktop\Death_valley.csv', 'r')
try:
high = int(row[4])
low =int(row[5])
except ValueError:
print(f"Missing data for {current_date}")
else:
[Link](high)
[Link](current_date)
[Link](low)
Download your own data
[Link] In Dataset box
choose Daily Summaries.
Mapping Global Data Sets : JSON Format
Downloading Earthquake Data
In this section we'll work with data stored in JSON format. First
we'll download a data set representing all the earthquakes that
have occurred in the world during the previous month.
{"type":"FeatureCollection","metadata":{"generated":15503614610
00,...
{"type":"Feature","properties":{"mag":1.2,"place":"11km NNE of
Nor...
{"type":"Feature","properties":{"mag":4.3,"place":"69km NNW of
Ayn...
{"type":"Feature","properties":{"mag":3.6,"place":"126km SSE of
Co...
This file is formatted more for machines than it is for humans.
But we can see that the file contains some dictionaries, as well as
information that we’re interested in, such as earthquake
magnitudes and
locations.
The json module provides a variety of tools for exploring and
working with JSON data.
There are
i) load
ii)dump
Examining Json Data:
import json
readable_file = 'data/readable_eq_data.json'
with open(readable_file, 'w') as f:
[Link](all_eq_data, f, indent=4)
We first import the json module to load the data properly from
the file, and then store the entire set of data in all_eq_data. The
[Link]() function converts the data into a dictionary.
Next we create a file to write this same data into a more readable
format. The [Link]() function takes a JSON data object and a
file object, and writes the data to that file.
The indent=4 argument tells dump() to format the data using
indentation that matches the data’s structure.
Making a list of all earthquakes:
The first part of the file includes a section with the key
"metadata". This tells us when the data file was generated and
where we can find the data online.
It also gives us a human-readable title and the number of
earthquakes included in this file.
In this 24-hour period, 158 earthquakes were recorded.
This geoJSON file has a structure that’s helpful for location-based
data.
Making a list of all earthquakes:
he following program makes a list that contains all the
information about every earthquake that occurred:
import json
all_eq_dicts = all_eq_data[‘metadata']
all_eq=all_eq_dicts[‘count’]
Extracting Magnitudes:
The key "properties" contains a lot of information about each
earthquake. We’re mainly interested in the magnitude of each quake,
which is associated with the key "mag".
The program pulls the magnitudes from each earthquake.
mags = []
for eq_dict in all_eq_dicts:
mag = eq_dict['properties']['mag']
[Link](mag)
print(mags[:10])
Now we’ll pull the location data for each earthquake, and then we can
make a map of the earthquakes.
The location data is stored under the key "geometry". Inside the
geometry dictionary is a "coordinates" key, and the first two values in
this list are the longitude and latitude.
The following program pulls the location data:
POST: adds new data to the server. Using this type of request, you
can, for example, add a new item to your inventory.
[Link]
Response:
{"resources":{"core":{"limit":60,"remaining":60,"reset":16771
22209,"used":0,"resource":"core"},"graphql":{"limit":0,"remai
ning":0,"reset":1677122209,"used":0,"resource":"graphql"},"in
tegration_manifest":{"limit":5000,"remaining":5000,"reset":16
77122209,"used":0,"resource":"integration_manifest"},"search"
:{"limit":10,"remaining":10,"reset":1677118669,"used":0,"reso
urce":"search"}},"rate":{"limit":60,"remaining":60,"reset":167
7122209,"used":0,"resource":"core"}}
Rate Limited – How many requests you can make in a certain
amount of time.
Visualizing repositories using plotly
We will import the Bar class and offline module from plotly.
Repo_names and stars are 2 lists created. They will contain
the repo names and the stars that each project in the
repository procured.
Data contains the data list dictionary with x value, y value
and the type of graph (bar)
We will define the layout for this chart using the dictionary
approach.
from plotly.graph_objs import Bar
from plotly import offline
Visualizing
repo_names,stars =[],[]
repositories using plotly
for repo_dict in repo_dicts:
repo_names.append(repo_dict['name'])
[Link](repo_dict['stargazers_count'])
data =[{
'type' :'bar',
'x': repo_names,
'y': stars,
}]
my_layout ={
'title':'Most_Starred python projects on github',
'xaxis':{'title': 'Repository'},
'yaxis':{'title': 'Stars'},
}
url = '[Link]
[Link]/v0/item/[Link]'
r = [Link](url)
response_dict = [Link]()
readable_file = 'readable_hn_data.json'
with open(readable_file, 'w') as f:
[Link](response_dict,f,indent =4)
The keys “descendants” tells us the number of comments the article received.
The key “kids” provides the IDs of all comments made in response to the article.
Output:
{
"by": "jimktrains2",
"descendants": 221,
"id": 19155826,
"kids": [
19156572,
19158857,
……..
],
"score": 728,
"time": 1550085414,
"title": "Nasa\u2019s Mars Rover Opportunity Concludes a 15-Year Mission",
"type": "story",
"url": "[Link]
[Link]"
}
Conclusion:
How to use APIs to write programs