SlideShare a Scribd company logo
1 of 225
Download to read offline
p ho d e
by Ab i h ma
Who I ā€¦.?
My a s A is K ma d I
an A ro f ar el , as l
as P ho S r r . I li wo n
ne c lo n r e t to .
So I've d P ho x a n
Hop u l ke .
Linkedin : www.linkedin.com/in/abhishek-kumar-24ab98167
Gmail : abhiak11.ak@gmail.com
Topices
Module 1.
Bas In od on & s in ,li s
Module 2.
Tup
Module 3.
Dic ar
Module 4.
Fun n
Module 5.
Fil I t/Out
Module 6.
Mod
Introduction to Python :
ā€¢ Py on : It i n e p d ri n n u .Gu d a s i k n he
fo r o y on g mi . It a c ed n 1985-1990.
It i m e, e s le , po f , hi l an j -or ed g mi
la ge. It u En is y d re t w e s o r gu us c u on,
an h ew y ac l o s c o s n er g a .
* Py on I t re : Py on r e s ru m t e t re .
*Py on I t a t : we c u l t a P t p o p d er w t e
in p er c y o r o p ra .
* Py on O j -Ori d : Py on p s O ec -Ori d y e t ni o
p o r n ha c ul co t i b t .
Features Of Python :
ā€¢1) Eas Us ,
ā€¢2) Ex es Lan e ,
ā€¢3) In e p d La ge ,
ā€¢4) Cro -p a f l u g ,
ā€¢5) Fre Ope S ce ,
ā€¢6) Ob e t-Ori d a g e ,
ā€¢7) Ex e s ,
ā€¢8) Lar n a d L r ,
ā€¢9) GU ro m g ,
ā€¢10) In e r .
Application Of Python :
ā€¢ 1) Con Bas A p i t o : Py on b u t e l on ba p ic o s.
ā€¢ 2) Aud o V o b Ap ic o s : Py on v an n ti a s on. Lik : Tim r,c ay .
ā€¢ 3) 3D A p ic o s : Fan g i al l a n ic r es l a r o CA .
ā€¢ 4) Web A li on : Py on l o se d e p ba p ic o . Som or t el n ar :
Py on E gi ,Poc ,Py on f ar .
ā€¢ 5) En e p Ap ic o s : Py on b u t e t a l i n h ca se t an E r se
Or a z i . Lik : Ope p, Tr on, Pic e c.
ā€¢ 6) Ap ic o s Im e : Usi Py on ra p at an ve d o m e. Ap ic o s lo re:
V y on, Gog , im S et .
Installation of python
windowsā— Open a Web browser and go to https://www.python.org/downloads/.
ā— Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install.
ā— To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your
local machine and then run it to find out if your machine supports MSI.
ā— Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings,
wait until the install is finished, and you are done
Linuxā— Open a Web browser and go to https://www.python.org/downloads/.
ā— Follow the link to download zipped source code available for Unix/Linux.
ā— Download and extract files.
ā— Editing the Modules/Setup file if you want to customize some options.
ā— run ./configure script
ā— make
ā— make install
This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the
version of Python.
Example of Python :
ā€¢A simple python example which will print "Basics Of Python" is
given below.
a="Welcome To Python"
print (a)
Output : Welcome To Python
Execution of Python :
We can execute the Python in 3 different ways ā€“
1) Interactive Mode:
we can enter python in the command prompt and execute.
1) Script Mode:
We can write our Python code in a separate file using any editor
with the .py extension.
3) Using IDE: (Integrated Development Environment)
We can execute our Python code using a Graphical User Interface
(GUI).
Interactive Mode :
Script Mode :
Using IDE :
Python Variables :
ā€¢Variable is a name of the memory location where data is stored.
Once a variable is stored that means a space is allocated in
memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by
assigning different data types to the variables, we can store integers,
decimals or characters in these variables
Assigning values to Variable :
We need not to declare explicitly variable in Python. When we
assign any value to the variable that variable is declared
automatically.
The assignment is done using the equal (=) operator.
Example :
car=500
truck=2
print(car)
print(truck)
Assigning value to variables :
Multiple Assignment :
Multiple assignment can be done in Python at a time.
There are two ways to assign values in Python:
1) Assigning single value to multiple variables:
2) Assigning multiple values to multiple variables:
Assigning single value to multiple variables
:
Assigning multiple values to multiple
variables:
Basic Fundamentals :
There are some basic fundamental of Python :
i)Tokens and their types.
ii) Comments
Tokens :
Tokens can be defined as a punctuator mark, reserved words and
each individual word in a statement.
Token is the smallest unit inside the given program.
āž¢There are following tokens in Python:
ā‘Keywords.
ā‘Identifiers.
ā‘Literals.
ā‘Operators.
Tuples :
Tuple is another form of collection where different type of data can
be stored.
It is similar to list where data is separated by commas. Only the
difference is that list uses square bracket and tuple uses
parenthesis.
Tuples are enclosed in parenthesis and cannot be changed.
Example of tuple :
Result of Example of Tuple :
Dictionary :
Dictionary is a collection which works on a key-value pair.
It works like an associated array where no two keys can be same.
Dictionaries are enclosed by curly braces ({}) and values can be
retrieved by square bracket([]).
Example of Dictionary :
Result of example of dictionary :
Python Keywords :
Python Keywords are special reserved words which convey a
special meaning to the compiler/interpreter. Each keyword have a
special meaning and a specific operation.
List of keywords used in Python :
Identifiers :
Identifiers are the names given to the fundamental building blocks in a
program. These can be variables ,class ,object ,functions , lists , dictionaries
etc.
There are certain rules defined for naming i.e., Identifiers.
I. An identifier is a long sequence of characters and numbers.
II. No special character except underscore ( _ ) can be used as an identifier.
III. Keyword should not be used as an identifier name.
IV. Python is case sensitive. So using case is significant.
V. First character of an identifier can be character, underscore ( _ ) but not
digit.
Reserved Words :
Python Literals :
Literals can be defined as a data that is given in a variable or
constant.
Python support the following literals:
I. String literals:
II. Numeric literals:
III. Boolean literals:
IV. Special literals.
V. Literal Collections.
String Literals :
String literals can be formed by enclosing a text in the quotes. We
can use both single as well as double quotes for a String.
Example:
"Ashish" , '12345'
Types of String Literals :
There are two types of String :
There are two types of Strings supported in Python:
a).Single line String-
Strings that are terminated within a single line are known as Single
line Strings
Example :
>>> text=ā€˜helloā€™
Multiline String :
A piece of text that is spread along multiple lines is known as
Multiple line String.
There are two ways to create Multiline Strings:
1). Adding black slash at the end of each line.
Example :
>>> text=ā€˜basicpythonā€™
>>> text
ā€˜basicpythonā€™
Multiline String :
2).Using triple quotation marks:
Example :
>>> str1=ā€˜ā€™ā€™welcome
To
Pythonā€™ā€™ā€™
>>> print str1
Welcome
To
Python
Numeric literals:
Python Operators :
Operators are particular symbols which operate on some values and
produce an output.
The values are known as Operands.
Eg. :
50+30=80
Here 50&30 are Operands and (+),(=) signs are the operators. Which
produce the result 80.
Operators in Python :
ā€¢Arithmetic Operators.
ā€¢Relational Operators.
ā€¢Assignment Operators.
ā€¢Logical Operators.
ā€¢Membership Operators.
ā€¢Identity Operators.
ā€¢Bitwise Operators.
Arithmetic Operators :
Relational Operators :
Assignment Operators :
Logical Operators :
Membership operators :
Identity Operators :
Python Comments :
Python supports two types of comments:
1) Single lined comment :
If user wants to specify a single line comment, then comment must start
with ?#?
Eg : #This is introduction to python.
2) Multi lined Comment:
Multi lined comment can be given inside triple quotes.
ā€œā€™ā€™ā€™ This
Is
Ashishā€™ā€™ā€™
If Statement :
The if statement in python is same as c language which is used test a
condition. If condition is true, statement of if block is executed otherwise it
is skipped.
Syntax of python if statement:
if(condition):
statements
Eg:
a=20
if a==20:
print (ā€œtrueā€)
Result= true
If else statement :
Syntax :
if(condition): False
statements
else: True
statements
Flow chart of if else :
Example of if else :
Result of Example of if else :
elif statement :
Syntax :
If statement:
Body
elif statement:
Body
else:
Body
Example of elif :
Result of example of elif :
for Loop :
for Loop is used to iterate a variable over a sequence(i.e., list or string) in
the order that they appear.
Syntax :
for <variable> in <sequence>:
Explanation :
ā€¢ Firstly, the first value will be assigned in the variable.
ā€¢ Secondly all the statements in the body of the loop are executed with the
same value.
ā€¢ Thirdly, once step second is completed then variable is assigned the next
value in the sequence and step second is repeated.
ā€¢ Finally, it continues till all the values in the sequence are assigned in the
variable and processed.
Example of for Loop :
Result of for Loop :
Nested Loop :
Loops defined within another Loop is called Nested Loop.
When an outer loop contains an inner loop in its body it is called
Nested Looping.
Syntax :
for <expression>:
for <expression>:
Body
Example of Nested Loop :
Result of nested loop :
While Loop :
while Loop is used to execute number of statements or body till the
condition passed in while is true. Once the condition is false, the
control will come out of the loop.
Syntax :
while <expression>:
Body
Example of while loop :
Result of example of while loop :
Python String :
Strings are the simplest and easy to use in Python.
String pythons are immutable.
We can simply create Python String by enclosing a text in single as
well as double quotes. Python treat both single and double quotes
statements same.
Accessing Strings :
In Python, Strings are stored as individual characters in a contiguous
memory location.
The benefit of using String is that it can be accessed from both the
directions in forward and backward.
Both forward as well as backward indexing are provided using
Strings in Python.
ā€¢ Forward indexing starts with 0,1,2,3,....
ā€¢ Backward indexing starts with -1,-2,-3,-4,....
String Operators :
There are basically 3 types of Operators supported by String:
1)Basic Operators.
2)Membership Operators.
3)Relational Operators.
ā€¢Basic Operators:
ā€¢There are two types of basic operators in String. They are "+"
and "*".
String Functions and Methods:
ā€¢ capitalize() It capitalizes the first character of the String.
ā€¢ count(string,begin,end) Counts number of times substring occurs in a String
between begin and end index.
ā€¢ endswith(suffix ,begin=0,end=n) Returns a Boolean value if the string
terminates with given suffix between begin and end.
ā€¢ find(substring ,beginIndex, endIndex) It returns the index value of the string
where substring is found between begin index and end index.
ā€¢ index(subsring, beginIndex, endIndex) Same as find() except it raises an
exception if string is not found.
ā€¢ isalnum() It returns True if characters in the string are alphanumeric i.e.,
alphabets or numbers and there is at least 1 character. Otherwise it returns
False.
ā€¢ isalpha() It returns True when all the characters are alphabets and there is at
least one character, otherwise False.
String Functions and Methods :
ā€¢ isdigit() It returns True if all the characters are digit and there is at least one
character, otherwise False.
ā€¢ islower() It returns True if the characters of a string are in lower case,
otherwise False.
ā€¢ isupper() It returns False if characters of a string are in Upper case, otherwise
False.
ā€¢ isspace() It returns True if the characters of a string are whitespace,
otherwise false.
ā€¢ len(string) len() returns the length of a string.
ā€¢ lower() Converts all the characters of a string to Lower case.
ā€¢ upper() Converts all the characters of a string to Upper Case.
ā€¢ startswith(str ,begin=0,end=n) Returns a Boolean value if the string starts
with given str between begin and end.
String Functions and Methods
ā€¢swapcase() Inverts case of all characters in a string.
ā€¢lstrip() Remove all leading whitespace of a string. It can also be
used to remove particular character from leading.
ā€¢rstrip() Remove all trailing whitespace of a string. It can also be
used to remove particular character from trailing.
Capitalize () :
Result of Capitalization() :
Count(string) :
Endswith(string) :
Result of endswith(string)
Find(string)
Result of find(string)
Isalnum :
Result of isalnum :
Isalpha
Result of isalpha
Isdigit :
Result of isdigit :
Islower :
Result of islower :
Isnumeric :
Result of isnumeric :
Isspace :
Result of isspace :
Isupper :
Result of isupper :
Join :
Result of join :
Length :
Result of length
Istrip :
Result of istrip :
Maketrans :
Result of maketrans :
Max :
Result of Max :
Min :
Result of min :
rfind :
Result of rfind :
rindex :
Result of rindex :
Python List :
ā€¢1).Python lists are the data structure that is capable of holding
different type of data.
ā€¢2).Python lists are mutable i.e., Python will not create a new list if
we modify an element in the list.
ā€¢3).It is a container that holds other objects in a given order.
Different operation like insertion and deletion can be performed
on lists.
ā€¢4).A list can be composed by storing a sequence of different type
of values separated by commas.
ā€¢5).A python list is enclosed between square([]) brackets.
ā€¢6).The elements are stored in the index basis with starting index
as 0.
Append List :
Result of Append List :
Count :
Result of count :
Extend list :
Result of Extend list :
Index :
Result Of Index :
Index :
Result of Index :
Len :
Result of len :
List :
Result of list :
Max :
Result of max :
Min :
Result of Min :
Tuples
Introduction
ā–¶ A tuple is a sequence of immutable Python objects. Tuples
are sequences, just like lists. The differences between tuples
and lists are, the tuples cannot be changed unlike lists and
tuples use parentheses, whereas lists use square brackets.
ā–¶ Creating a tuple is as simple as putting different
comma-separated values. Optionally you can put these
comma-separated values between parentheses also.
Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and slicing work the same way for
tuples as they do for strings. Assuming following input:
L = ('spam', 'Spam', 'SPAM!')
Expression Results Description
L[2] ā€˜SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Updating Tuples program
ā–¶ tupl1=("sunday","Monday","tuesday","wednesday")
ā–¶ tuple2=("Thrusday","friday","Saturday")
ā–¶ tuple3=tupl1+tuple2
ā–¶ print(tuple3)
Updating Tuple result
Delete Tuple Program
ā–¶ tuple1=("mango","apple","banana")
ā–¶ print(tuple1)
ā–¶ del tuple1
ā–¶ print(tuple1)
Delete tuple Result
Length Tuple Program
ā–¶ tupl1=("sunday","Monday","tuesday","wednesday")
ā–¶ tuple2=("Thrusday","friday","Saturday")
ā–¶ tuple3=tupl1+tuple2
ā–¶ print(tuple3)
ā–¶ print(len(tuple3))
Length Tuple Result
Maximum Element in tuple Program
ā–¶ tuple=("123","234","567")
ā–¶ print(max(tuple))
ā–¶ tuple1=("Mango","Apple","Banana")
ā–¶ print(max(tuple1))
Maximum Element in tuple Result
Minimum Element in Tuple Program
ā–¶ tuple=("123","234","567")
ā–¶ print(min(tuple))
ā–¶ tuple1=("Mango","Apple","Banana")
ā–¶ print(min(tuple1))
Minimum Element in Tuple Result
Convert Element into Tuple program
ā–¶ list1=["Abhishek","Ashish","anshu"]
ā–¶ print(list1)
ā–¶ tuple1=tuple(list1)
ā–¶ print(tuple1)
Convert Element into Tuple Result
Dictionary
Introduction
ā–¶ Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces.
An empty dictionary without any items is written with just two curly
braces, like this: {}.
ā–¶ Keys are unique within a dictionary while values may not be. The values
of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.
Normal
Program
ā–¶ # Dictionary
ā–¶ dict={"ROll":'1',"Name":"Abhishek","Course":"BCA"}
ā–¶ print("Dictionary is",dict)
Result
Updating Dictionary
Program
ā–¶ # Dictionary
ā–¶ dict={"ROll":'1',"Name":"Abhishek","Course":"BCA"}
ā–¶ print("Dictionary is",dict)
ā–¶ # Updating Dictionary
ā–¶ dict["ROll"]=4
ā–¶ dict["Name"]="Ashish"
ā–¶ print("nUpdating Dictionary is",dict)
Update Dictionary
Result
Deleted Dictionary
Program
ā–¶ # Dictionary
ā–¶ dict={"ROll":'1',"Name":"Abhishek","Course":"BCA"}
ā–¶ print("Dictionary is",dict)
ā–¶ # Delete Dictionary
ā–¶ del dict["Name"]; # remove entry with key 'Name
ā–¶ print("Now Dictionary is",dict)
ā–¶ dict.clear(); # remove all entries in dict
ā–¶ print("Now Dictionary is",dict)
ā–¶ del dict ; # delete entire dictionary
ā–¶ print("Now Dictionary is",dict)
Deleted Dictionary
Result
Properties Of Dictionary
ā–¶ Dictionary values have no restrictions. They can be any arbitrary Python object,
either standard objects or user-defined objects. However, same is not true for
the keys.
ā–¶ There are two important points to remember about dictionary keys:
I. More than one entry per key not allowed. Which means no duplicate key is
allowed. When duplicate keys encountered during assignment, the last
assignment wins.
II. Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.
Built-in Dictionary Functions and Methods
Length in Dictionary
Description
ā–¶ The method len() gives the total length of the dictionary. This would be
equal to the number of items in the dictionary.
Length in Dictionary
Progarm
ā–¶ # Length in Dictionary
ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"}
ā–¶ print("The Dictionary is",dict)
ā–¶ print("n")
ā–¶ print(len(dict))
Length in Dictionary
Result
Clear in Dictionary
Program
ā–¶ # Clear in Dictionary
ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"}
ā–¶ print("The Dictionary is",dict)
ā–¶ print("n Dictionary Length ",len(dict))
ā–¶ dict.clear() #Clear Dictionary
ā–¶ print("n Now Dictionary Length ",len(dict))
Clear in Dictionary
Result
Copy in Dictionary
program
ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"}
ā–¶ print("The Dictionary is",dict)
ā–¶ # Copy in Dictionary
ā–¶ dict2=dict.copy()
ā–¶ print("n Copy Dictionary is ",dict2)
Copy in Dictionary
Result
Get the Element from Key
Program
This method return a value for the given key. If key is not
available, then returns default value None.
ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"}
ā–¶ print("The Dictionary is",dict)
ā–¶ #get the Element from keys
ā–¶ print("Get elemnt is ",dict.get(1))
ā–¶ #if key is not in dictionary give default values
ā–¶ print("nGet element is ",dict.get(5,"defaultvalue"))
Get the Element from Key
Result
Dict.items() Method in Dictionary
Result
Dict.keys() Method in Dictionary
Program
The method keys() returns a list of all the available keys in the dictionary
āž¢ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"}
āž¢ print("The Dictionary is",dict)
āž¢ # dict.key()
āž¢ print("n Item is ",dict.keys())
Dict.keys() Method in Dictionary
Result
dict.setdefault(key,
default=None)Method in Dictionary
Program
The method setdefault() is similar to get(), but will set dict[key]=default if
key is not already in dict.
āž¢ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"}
āž¢ print("The Dictionary is",dict)
āž¢ # dict.setdefault(key, default=None)
āž¢ print("n vlaue: ",dict.setdefault(4,"None"))
dict.setdefault(key, default=None)Method
in Dictionary Result
dict.update(dict2) Method in Dictionary
Program
ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"}
ā–¶ print("The Dictionary is",dict)
ā–¶ # dict.update(dict2)
ā–¶ dict2={5:"Sam",6:"Atif Aslam"}
ā–¶ dict.update(dict2)
ā–¶ print("Update Dictionary is",dict)
dict.update(dict2) Method in
Dictionary Result
dict.values() Method in Dictionary
Program
The method values() returns a list of all the values available in a given
dictionary.
āž¢ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"}
āž¢ print("The Dictionary is",dict)
āž¢ # dict.values
āž¢ print("nvalues :",dict.values())
dict.values() Method in Dictionary
Result
Function
Intro
ā–¶ A Function is a self block of code.
ā–¶ A Function can be called as a section of a program that is written once
and can be executed whenever required in the program, thus making
code reusability.
ā–¶ A Function is a subprogram that works on data and produce some
output.
Types Of Function
There are two types of Functions.
ā–¶ a) Built-in Functions: Functions that are predefined. We have used many
predefined functions in Python.
ā–¶ b) User- Defined: Functions that are created according to the
requirements.
Defining a Function
A Function defined in Python should follow the following format:
ā–¶ 1) Keyword def is used to start the Function Definition. Def specifies the
starting of Function block.
ā–¶ 2) def is followed by function-name followed by parenthesis.
ā–¶ 3) Parameters are passed inside the parenthesis. At the end a colon is
marked.
Syntax
ā–¶ defĀ <function_name>([parameters]):Ā Ā 
</function_name>Ā Ā 
Example Normal Program
ā–¶ def Sum():
ā–¶ x=10;
ā–¶ y=10;
ā–¶ z=x+y
ā–¶ print("Sum is ",z)
ā–¶
ā–¶ Sum()
ā–¶
Result
Invoking a Function Program
ā–¶ def Sum(a,b):
ā–¶ x=a;
ā–¶ y=b;
ā–¶ z=x+y
ā–¶ print("Sum is ",z)
ā–¶
ā–¶ Sum(10,10) # invoking a Function
Result
return Statement:
ā–¶ return[expression] is used to send back the control to the caller with the
expression.
ā–¶ In case no expression is given after return it will return None.
ā–¶ In other words return statement is used to exit the Function definition.
Return statement
Program
ā–¶ def Sum(a,b):
ā–¶ x=a;
ā–¶ y=b;
ā–¶ z=x+y
ā–¶ return z # return a variable
ā–¶
ā–¶ ret=Sum(10,20) # invoking a Function
ā–¶ print("return result function is ",ret)
Function Arguments
ā–¶ You can call a function by using the following types of formal
arguments-
ā–¶ Required arguments
ā–¶ Keyword arguments
ā–¶ Default arguments
ā–¶ Variable-length arguments
Required Arguments
ā–¶ Required arguments are the arguments passed to a function in correct
positional order.
ā–¶ Here, the number of arguments in the function call should match
exactly with the function
Program
ā–¶ # Function definition is here
ā–¶ def printme( str ):
ā–¶ "This prints a passed string into this function"
ā–¶ print (str)
ā–¶ return
ā–¶ # Now you can call printme function
ā–¶ printme() # This is wrong call Because function need arugument
Result
Keyword Arguments
ā–¶ Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
File Input/output
Python can be used to read and write
data. Also it supports reading and
writing data to Files
Printing to the Screen
ā–¶ "print" statement is used to print the output on the screen.
ā–¶ print statement is used to take string as input and place that string to
standard output.
ā–¶ Whatever you want to display on output place that expression inside
the inverted commas. The expression whose value is to printed place it
without inverted commas.
Example
ā–¶ Print(ā€œHello Abhishekā€)
ā–¶ >>Hello Abhishek # Result
Input from keybord
Python offers two in-built functions for taking input from user. They are:
āž¢ Input()
Input Program
ā–¶ a=input("Enter Number ")
ā–¶ print("The Number is ",a)
ā–¶ b=input("Input String ")
ā–¶ print("This is a String ",b)
Input Result
Opening and Closing a File
ā–¶ Before working with Files you have to open the File. To open a File,
Python built in function open() is used. It returns an object of File
which is used with other functions. Having opened the file now you can
perform read, write, etc. operations on the File
Syntax
obj=open(filenameĀ ,Ā modeĀ ,Ā buffer)Ā Ā Ā  #Opening
obj.close() # Closing
Here are parameter details-
>> file_: The file_name argument is a string value that contains the name
of the filnamee that you want to access.
>> access_mode: The access_mode determines the mode in which the file
has to be opened, i.e., read, write, append, etc. A complete list of possible
values is given below in the table. This is an optional parameter and the
default file access mode is read (r).
>> buffering: If the buffering value is set to 0, no buffering takes place. If
the buffering value is 1, line buffering is performed while accessing a file.
If you specify the buffering value as an integer greater than 1, then
buffering action is performed with the indicated buffer size. If negative,
the buffer size is the system default (default behavior).
MODES OF FILE
Mode Description
R
It opens in Reading mode. It
is default mode of File.
Pointer is at beginning of the
file.
rb
It opens in Reading mode for
binary format. It is the
default mode. Pointer is at
beginning of file.
r+
Opens file for reading and
writing. Pointer is at
beginning of file
rb+
Opens file for reading and writing in
binary format. Pointer is at
beginning of file.
W
Opens file in Writing mode. If file
already exists, then overwrite the file
else create a new file.
wb
Opens file in Writing mode in binary
format. If file already exists, then
overwrite the file else create a new
file.
w+
Opens file for reading and writing. If
file already exists, then overwrite the
file else create a new file
MODES OF FILE
MODES OF FILE
wb+
Opens file for reading and
writing in binary format. If file
already exists, then overwrite
the file else create a new file.
a
Opens file in Appending
mode. If file already exists,
then append the data at the
end of existing file, else
create a new file.
ab
Opens file in Appending
mode in binary format. If file
already exists, then append
the data at the end of existing
file, else create a new file.
a+
Opens file in reading and
appending mode. If file
already exists, then append
the data at the end of existing
file, else create a new file.
ab+
Opens file in reading and
appending mode in binary
format. If file already exists,
then append the data at the
end of existing file, else
FILE OBJECT ATTRIBUTES
Attribute Description
file.closed Returns true if file is closed, false otherwise
file.mode Returns access mode with which file was opened.
file.name Returns name of the file
Example
ā–¶ obj=open("abhi.txt","wb") # Opening a File
ā–¶ print("Name of the file : ",obj.name)
ā–¶ print("Closed File or Not",obj.closed)
ā–¶ print ("Opening mode : ", obj.mode)
ā–¶ obj.close() # Closing a File
Result
Reading and writing a file
ā–¶ The file object provides a set of access methods to make our lives easier.
We would see how to use read() and write() methods to read and write
files.
Writing File
Program
Syntax
fileObject.write(string);
Program
āž¢ obj=open("abhi.txt","w")
āž¢ print("Name of the file : ",obj.name)
āž¢ obj.write("Hello Abhishek") # Writing a File
āž¢ print("Succsess fully Write")
āž¢ obj.close()
Writing File
Result
Reading File
Program
Syntax
fileObject.read([count]);
Program
āž¢ obj=open("abhi.txt","r")
āž¢ print("Name of the file : ",obj.name)
āž¢ tmp=obj.read()# Reading a File
āž¢ print("n")
āž¢ print(tmp) #print reading File
āž¢ print("nSuccsess fully Read")
āž¢ obj.close()
Reading File
Result
Renaming and Deleting File
Python os module provides methods that help you perform file-processing
operations, such as renaming and deleting files.
Syntax
rename : os.rename(current_file_name, new_file_name)
syntax
Delete : os.remove(file_name)
Program to rename the file
ā–¶ import os
ā–¶ os.rename("old.txt","newFile.txt")
ā–¶ print(" Reame Successfully ")
Rename file
Result
Deleting File
Program
ā–¶ import os
ā–¶ os.remove("newfile.txt")
ā–¶ print(" Remove Successfully ")
Deleting File
Result
Directories in Python
All files are contained within various directories, and Python has no problem
handling these too. The os module has several methods that help you create,
remove, and change directories.
Make a directory by mkdir() Method
Program
āž¢ import os
āž¢ os.mkdir("New Directory")
āž¢ print(" Directory made Successfully ")
mkdir() Method
Result
Get working directory by getcwd() Method
Program
āž¢ import os
āž¢ get=os.getcwd()
āž¢ print("Current working directory is",get)
getcwd () Result
Remove Directory Program
by rmdir() Method
ā–¶ import os
ā–¶ os.rmdir("hello")
ā–¶ print("Successfully Removed")
rmdir() Method
Result
Module
ā–¶ A module allows you to logically organize your Python code. Grouping
related code into a module makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that you can
bind and reference.
Advantages
Python provides the following advantages for using module:
ā–¶ 1) Reusability: Module can be used in some other python code. Hence it
provides the facility of code reusability.
ā–¶ 2) Categorization: Similar type of attributes can be placed in one module.
Importing a Module:
There are different ways by which you we can
import a module. These are as follows
ā–¶ Using import statement
ā–¶ Using from.. import statement
Using import statement
program
Save this Fie Example.py
# Example
ā–¶ # Example.py
ā–¶ def sum(a,b):
ā–¶ x=a
ā–¶ y=b
ā–¶ total=x+y;
ā–¶ return total
Using import statement
program
Import the Example.py File by import keyword
āž¢ import Example
āž¢ z=Example.sum(10,20)
āž¢ print("Total is ",z)
Using import statement
Result
Using from.. import statement
program
Save this file Example.py
āž¢ # Example
āž¢ def sum(a,b):
āž¢ x=a
āž¢ y=b
āž¢ total=x+y;
āž¢ return total
āž¢
āž¢ def Minus(a,b):
āž¢ x=a
āž¢ y=b;
āž¢ result= x-y
āž¢ return result
Using from.. import statement
program
Import the Example.py
āž¢ from Example import sum,Minus
āž¢ z=sum(10,20)
āž¢ print("Total is ",z)
āž¢ z=Minus(10,20)
āž¢ print("Total is ",z)
Using from.. import statement
Result
Python made easy

More Related Content

What's hot

Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
Ā 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Edureka!
Ā 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialQA TrainingHub
Ā 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
Ā 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming LanguageLaxman Puri
Ā 
Why Python?
Why Python?Why Python?
Why Python?Adam Pah
Ā 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019Samir Mohanty
Ā 
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Edureka!
Ā 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu SharmaMayank Sharma
Ā 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaEdureka!
Ā 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slidesrfojdar
Ā 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming pptismailmrribi
Ā 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in PythonPooja B S
Ā 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in pythonRaginiJain21
Ā 

What's hot (20)

Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
Ā 
Python ppt
Python pptPython ppt
Python ppt
Ā 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
Ā 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Ā 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
Ā 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
Ā 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Ā 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
Ā 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
Ā 
Why Python?
Why Python?Why Python?
Why Python?
Ā 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
Ā 
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Ā 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu Sharma
Ā 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Ā 
Python
PythonPython
Python
Ā 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slides
Ā 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
Ā 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Ā 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
Ā 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
Ā 

Similar to Python made easy

Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentalsnatnaelmamuye
Ā 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptxParveenShaik21
Ā 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptxParveenShaik21
Ā 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
Ā 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizeIruolagbePius
Ā 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
Ā 
Python for katana
Python for katanaPython for katana
Python for katanakedar nath
Ā 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptxTamalSengupta8
Ā 
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfCSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfAbdulmalikAhmadLawan2
Ā 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
Ā 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of pythonBijuAugustian
Ā 
Unit -1 CAP.pptx
Unit -1 CAP.pptxUnit -1 CAP.pptx
Unit -1 CAP.pptxmalekaanjum1
Ā 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfMichpice
Ā 
Python PPT.pptx
Python PPT.pptxPython PPT.pptx
Python PPT.pptxJosephMuez2
Ā 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
Ā 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfSanjeedaPraween
Ā 

Similar to Python made easy (20)

Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
Ā 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
Ā 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
Ā 
Python 01.pptx
Python 01.pptxPython 01.pptx
Python 01.pptx
Ā 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
Ā 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
Ā 
GE3151_PSPP_UNIT_2_Notes
GE3151_PSPP_UNIT_2_NotesGE3151_PSPP_UNIT_2_Notes
GE3151_PSPP_UNIT_2_Notes
Ā 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
Ā 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
Ā 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Ā 
Python for katana
Python for katanaPython for katana
Python for katana
Ā 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptx
Ā 
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfCSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
Ā 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
Ā 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of python
Ā 
Unit -1 CAP.pptx
Unit -1 CAP.pptxUnit -1 CAP.pptx
Unit -1 CAP.pptx
Ā 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Ā 
Python PPT.pptx
Python PPT.pptxPython PPT.pptx
Python PPT.pptx
Ā 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
Ā 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdf
Ā 

Recently uploaded

Call Girls in Defence Colony Delhi šŸ’ÆCall Us šŸ”8264348440šŸ”
Call Girls in Defence Colony Delhi šŸ’ÆCall Us šŸ”8264348440šŸ”Call Girls in Defence Colony Delhi šŸ’ÆCall Us šŸ”8264348440šŸ”
Call Girls in Defence Colony Delhi šŸ’ÆCall Us šŸ”8264348440šŸ”soniya singh
Ā 
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...Suhani Kapoor
Ā 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
Ā 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Delhi Call girls
Ā 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
Ā 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
Ā 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
Ā 
Predicting Employee Churn: A Data-Driven Approach Project Presentation
Predicting Employee Churn: A Data-Driven Approach Project PresentationPredicting Employee Churn: A Data-Driven Approach Project Presentation
Predicting Employee Churn: A Data-Driven Approach Project PresentationBoston Institute of Analytics
Ā 
Decoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in ActionDecoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in ActionBoston Institute of Analytics
Ā 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
Ā 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
Ā 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
Ā 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsappssapnasaifi408
Ā 
Digi Khata Problem along complete plan.pptx
Digi Khata Problem along complete plan.pptxDigi Khata Problem along complete plan.pptx
Digi Khata Problem along complete plan.pptxTanveerAhmed817946
Ā 
Delhi Call Girls Punjabi Bagh 9711199171 ā˜Žāœ”šŸ‘Œāœ” Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ā˜Žāœ”šŸ‘Œāœ” Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ā˜Žāœ”šŸ‘Œāœ” Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ā˜Žāœ”šŸ‘Œāœ” Whatsapp Hard And Sexy Vip Callshivangimorya083
Ā 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
Ā 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...dajasot375
Ā 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts ServiceSapana Sha
Ā 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
Ā 

Recently uploaded (20)

Call Girls in Defence Colony Delhi šŸ’ÆCall Us šŸ”8264348440šŸ”
Call Girls in Defence Colony Delhi šŸ’ÆCall Us šŸ”8264348440šŸ”Call Girls in Defence Colony Delhi šŸ’ÆCall Us šŸ”8264348440šŸ”
Call Girls in Defence Colony Delhi šŸ’ÆCall Us šŸ”8264348440šŸ”
Ā 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Ā 
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
Ā 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Ā 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Ā 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Ā 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
Ā 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Ā 
Predicting Employee Churn: A Data-Driven Approach Project Presentation
Predicting Employee Churn: A Data-Driven Approach Project PresentationPredicting Employee Churn: A Data-Driven Approach Project Presentation
Predicting Employee Churn: A Data-Driven Approach Project Presentation
Ā 
Decoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in ActionDecoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in Action
Ā 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
Ā 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
Ā 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
Ā 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Ā 
Digi Khata Problem along complete plan.pptx
Digi Khata Problem along complete plan.pptxDigi Khata Problem along complete plan.pptx
Digi Khata Problem along complete plan.pptx
Ā 
Delhi Call Girls Punjabi Bagh 9711199171 ā˜Žāœ”šŸ‘Œāœ” Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ā˜Žāœ”šŸ‘Œāœ” Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ā˜Žāœ”šŸ‘Œāœ” Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ā˜Žāœ”šŸ‘Œāœ” Whatsapp Hard And Sexy Vip Call
Ā 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
Ā 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Ā 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts Service
Ā 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
Ā 

Python made easy

  • 1. p ho d e by Ab i h ma
  • 2. Who I ā€¦.? My a s A is K ma d I an A ro f ar el , as l as P ho S r r . I li wo n ne c lo n r e t to . So I've d P ho x a n Hop u l ke . Linkedin : www.linkedin.com/in/abhishek-kumar-24ab98167 Gmail : abhiak11.ak@gmail.com
  • 3. Topices Module 1. Bas In od on & s in ,li s Module 2. Tup Module 3. Dic ar Module 4. Fun n Module 5. Fil I t/Out Module 6. Mod
  • 4. Introduction to Python : ā€¢ Py on : It i n e p d ri n n u .Gu d a s i k n he fo r o y on g mi . It a c ed n 1985-1990. It i m e, e s le , po f , hi l an j -or ed g mi la ge. It u En is y d re t w e s o r gu us c u on, an h ew y ac l o s c o s n er g a . * Py on I t re : Py on r e s ru m t e t re . *Py on I t a t : we c u l t a P t p o p d er w t e in p er c y o r o p ra . * Py on O j -Ori d : Py on p s O ec -Ori d y e t ni o p o r n ha c ul co t i b t .
  • 5. Features Of Python : ā€¢1) Eas Us , ā€¢2) Ex es Lan e , ā€¢3) In e p d La ge , ā€¢4) Cro -p a f l u g , ā€¢5) Fre Ope S ce , ā€¢6) Ob e t-Ori d a g e , ā€¢7) Ex e s , ā€¢8) Lar n a d L r , ā€¢9) GU ro m g , ā€¢10) In e r .
  • 6. Application Of Python : ā€¢ 1) Con Bas A p i t o : Py on b u t e l on ba p ic o s. ā€¢ 2) Aud o V o b Ap ic o s : Py on v an n ti a s on. Lik : Tim r,c ay . ā€¢ 3) 3D A p ic o s : Fan g i al l a n ic r es l a r o CA . ā€¢ 4) Web A li on : Py on l o se d e p ba p ic o . Som or t el n ar : Py on E gi ,Poc ,Py on f ar . ā€¢ 5) En e p Ap ic o s : Py on b u t e t a l i n h ca se t an E r se Or a z i . Lik : Ope p, Tr on, Pic e c. ā€¢ 6) Ap ic o s Im e : Usi Py on ra p at an ve d o m e. Ap ic o s lo re: V y on, Gog , im S et .
  • 7. Installation of python windowsā— Open a Web browser and go to https://www.python.org/downloads/. ā— Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. ā— To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. ā— Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done Linuxā— Open a Web browser and go to https://www.python.org/downloads/. ā— Follow the link to download zipped source code available for Unix/Linux. ā— Download and extract files. ā— Editing the Modules/Setup file if you want to customize some options. ā— run ./configure script ā— make ā— make install This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.
  • 8. Example of Python : ā€¢A simple python example which will print "Basics Of Python" is given below. a="Welcome To Python" print (a) Output : Welcome To Python
  • 9. Execution of Python : We can execute the Python in 3 different ways ā€“ 1) Interactive Mode: we can enter python in the command prompt and execute. 1) Script Mode: We can write our Python code in a separate file using any editor with the .py extension. 3) Using IDE: (Integrated Development Environment) We can execute our Python code using a Graphical User Interface (GUI).
  • 13. Python Variables : ā€¢Variable is a name of the memory location where data is stored. Once a variable is stored that means a space is allocated in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, we can store integers, decimals or characters in these variables
  • 14. Assigning values to Variable : We need not to declare explicitly variable in Python. When we assign any value to the variable that variable is declared automatically. The assignment is done using the equal (=) operator. Example : car=500 truck=2 print(car) print(truck)
  • 15. Assigning value to variables :
  • 16. Multiple Assignment : Multiple assignment can be done in Python at a time. There are two ways to assign values in Python: 1) Assigning single value to multiple variables: 2) Assigning multiple values to multiple variables:
  • 17. Assigning single value to multiple variables :
  • 18. Assigning multiple values to multiple variables:
  • 19. Basic Fundamentals : There are some basic fundamental of Python : i)Tokens and their types. ii) Comments
  • 20. Tokens : Tokens can be defined as a punctuator mark, reserved words and each individual word in a statement. Token is the smallest unit inside the given program. āž¢There are following tokens in Python: ā‘Keywords. ā‘Identifiers. ā‘Literals. ā‘Operators.
  • 21. Tuples : Tuple is another form of collection where different type of data can be stored. It is similar to list where data is separated by commas. Only the difference is that list uses square bracket and tuple uses parenthesis. Tuples are enclosed in parenthesis and cannot be changed.
  • 23. Result of Example of Tuple :
  • 24. Dictionary : Dictionary is a collection which works on a key-value pair. It works like an associated array where no two keys can be same. Dictionaries are enclosed by curly braces ({}) and values can be retrieved by square bracket([]).
  • 26. Result of example of dictionary :
  • 27. Python Keywords : Python Keywords are special reserved words which convey a special meaning to the compiler/interpreter. Each keyword have a special meaning and a specific operation.
  • 28. List of keywords used in Python :
  • 29. Identifiers : Identifiers are the names given to the fundamental building blocks in a program. These can be variables ,class ,object ,functions , lists , dictionaries etc. There are certain rules defined for naming i.e., Identifiers. I. An identifier is a long sequence of characters and numbers. II. No special character except underscore ( _ ) can be used as an identifier. III. Keyword should not be used as an identifier name. IV. Python is case sensitive. So using case is significant. V. First character of an identifier can be character, underscore ( _ ) but not digit.
  • 31. Python Literals : Literals can be defined as a data that is given in a variable or constant. Python support the following literals: I. String literals: II. Numeric literals: III. Boolean literals: IV. Special literals. V. Literal Collections.
  • 32. String Literals : String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for a String. Example: "Ashish" , '12345'
  • 33. Types of String Literals : There are two types of String : There are two types of Strings supported in Python: a).Single line String- Strings that are terminated within a single line are known as Single line Strings Example : >>> text=ā€˜helloā€™
  • 34. Multiline String : A piece of text that is spread along multiple lines is known as Multiple line String. There are two ways to create Multiline Strings: 1). Adding black slash at the end of each line. Example : >>> text=ā€˜basicpythonā€™ >>> text ā€˜basicpythonā€™
  • 35. Multiline String : 2).Using triple quotation marks: Example : >>> str1=ā€˜ā€™ā€™welcome To Pythonā€™ā€™ā€™ >>> print str1 Welcome To Python
  • 37. Python Operators : Operators are particular symbols which operate on some values and produce an output. The values are known as Operands. Eg. : 50+30=80 Here 50&30 are Operands and (+),(=) signs are the operators. Which produce the result 80.
  • 38. Operators in Python : ā€¢Arithmetic Operators. ā€¢Relational Operators. ā€¢Assignment Operators. ā€¢Logical Operators. ā€¢Membership Operators. ā€¢Identity Operators. ā€¢Bitwise Operators.
  • 45. Python Comments : Python supports two types of comments: 1) Single lined comment : If user wants to specify a single line comment, then comment must start with ?#? Eg : #This is introduction to python. 2) Multi lined Comment: Multi lined comment can be given inside triple quotes. ā€œā€™ā€™ā€™ This Is Ashishā€™ā€™ā€™
  • 46. If Statement : The if statement in python is same as c language which is used test a condition. If condition is true, statement of if block is executed otherwise it is skipped. Syntax of python if statement: if(condition): statements Eg: a=20 if a==20: print (ā€œtrueā€) Result= true
  • 47. If else statement : Syntax : if(condition): False statements else: True statements
  • 48. Flow chart of if else :
  • 49. Example of if else :
  • 50. Result of Example of if else :
  • 51. elif statement : Syntax : If statement: Body elif statement: Body else: Body
  • 53. Result of example of elif :
  • 54. for Loop : for Loop is used to iterate a variable over a sequence(i.e., list or string) in the order that they appear. Syntax : for <variable> in <sequence>: Explanation : ā€¢ Firstly, the first value will be assigned in the variable. ā€¢ Secondly all the statements in the body of the loop are executed with the same value. ā€¢ Thirdly, once step second is completed then variable is assigned the next value in the sequence and step second is repeated. ā€¢ Finally, it continues till all the values in the sequence are assigned in the variable and processed.
  • 55. Example of for Loop :
  • 56. Result of for Loop :
  • 57. Nested Loop : Loops defined within another Loop is called Nested Loop. When an outer loop contains an inner loop in its body it is called Nested Looping. Syntax : for <expression>: for <expression>: Body
  • 60. While Loop : while Loop is used to execute number of statements or body till the condition passed in while is true. Once the condition is false, the control will come out of the loop. Syntax : while <expression>: Body
  • 62. Result of example of while loop :
  • 63. Python String : Strings are the simplest and easy to use in Python. String pythons are immutable. We can simply create Python String by enclosing a text in single as well as double quotes. Python treat both single and double quotes statements same.
  • 64. Accessing Strings : In Python, Strings are stored as individual characters in a contiguous memory location. The benefit of using String is that it can be accessed from both the directions in forward and backward. Both forward as well as backward indexing are provided using Strings in Python. ā€¢ Forward indexing starts with 0,1,2,3,.... ā€¢ Backward indexing starts with -1,-2,-3,-4,....
  • 65. String Operators : There are basically 3 types of Operators supported by String: 1)Basic Operators. 2)Membership Operators. 3)Relational Operators. ā€¢Basic Operators: ā€¢There are two types of basic operators in String. They are "+" and "*".
  • 66. String Functions and Methods: ā€¢ capitalize() It capitalizes the first character of the String. ā€¢ count(string,begin,end) Counts number of times substring occurs in a String between begin and end index. ā€¢ endswith(suffix ,begin=0,end=n) Returns a Boolean value if the string terminates with given suffix between begin and end. ā€¢ find(substring ,beginIndex, endIndex) It returns the index value of the string where substring is found between begin index and end index. ā€¢ index(subsring, beginIndex, endIndex) Same as find() except it raises an exception if string is not found. ā€¢ isalnum() It returns True if characters in the string are alphanumeric i.e., alphabets or numbers and there is at least 1 character. Otherwise it returns False. ā€¢ isalpha() It returns True when all the characters are alphabets and there is at least one character, otherwise False.
  • 67. String Functions and Methods : ā€¢ isdigit() It returns True if all the characters are digit and there is at least one character, otherwise False. ā€¢ islower() It returns True if the characters of a string are in lower case, otherwise False. ā€¢ isupper() It returns False if characters of a string are in Upper case, otherwise False. ā€¢ isspace() It returns True if the characters of a string are whitespace, otherwise false. ā€¢ len(string) len() returns the length of a string. ā€¢ lower() Converts all the characters of a string to Lower case. ā€¢ upper() Converts all the characters of a string to Upper Case. ā€¢ startswith(str ,begin=0,end=n) Returns a Boolean value if the string starts with given str between begin and end.
  • 68. String Functions and Methods ā€¢swapcase() Inverts case of all characters in a string. ā€¢lstrip() Remove all leading whitespace of a string. It can also be used to remove particular character from leading. ā€¢rstrip() Remove all trailing whitespace of a string. It can also be used to remove particular character from trailing.
  • 98. Max :
  • 100. Min :
  • 106. Python List : ā€¢1).Python lists are the data structure that is capable of holding different type of data. ā€¢2).Python lists are mutable i.e., Python will not create a new list if we modify an element in the list. ā€¢3).It is a container that holds other objects in a given order. Different operation like insertion and deletion can be performed on lists. ā€¢4).A list can be composed by storing a sequence of different type of values separated by commas. ā€¢5).A python list is enclosed between square([]) brackets. ā€¢6).The elements are stored in the index basis with starting index as 0.
  • 108. Result of Append List :
  • 112. Result of Extend list :
  • 117. Len :
  • 119. List :
  • 121. Max :
  • 123. Min :
  • 125. Tuples
  • 126. Introduction ā–¶ A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. ā–¶ Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also.
  • 127. Indexing, Slicing, and Matrixes Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input: L = ('spam', 'Spam', 'SPAM!') Expression Results Description L[2] ā€˜SPAM!' Offsets start at zero L[-2] 'Spam' Negative: count from the right L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
  • 128. Updating Tuples program ā–¶ tupl1=("sunday","Monday","tuesday","wednesday") ā–¶ tuple2=("Thrusday","friday","Saturday") ā–¶ tuple3=tupl1+tuple2 ā–¶ print(tuple3)
  • 130. Delete Tuple Program ā–¶ tuple1=("mango","apple","banana") ā–¶ print(tuple1) ā–¶ del tuple1 ā–¶ print(tuple1)
  • 132. Length Tuple Program ā–¶ tupl1=("sunday","Monday","tuesday","wednesday") ā–¶ tuple2=("Thrusday","friday","Saturday") ā–¶ tuple3=tupl1+tuple2 ā–¶ print(tuple3) ā–¶ print(len(tuple3))
  • 134. Maximum Element in tuple Program ā–¶ tuple=("123","234","567") ā–¶ print(max(tuple)) ā–¶ tuple1=("Mango","Apple","Banana") ā–¶ print(max(tuple1))
  • 135. Maximum Element in tuple Result
  • 136. Minimum Element in Tuple Program ā–¶ tuple=("123","234","567") ā–¶ print(min(tuple)) ā–¶ tuple1=("Mango","Apple","Banana") ā–¶ print(min(tuple1))
  • 137. Minimum Element in Tuple Result
  • 138. Convert Element into Tuple program ā–¶ list1=["Abhishek","Ashish","anshu"] ā–¶ print(list1) ā–¶ tuple1=tuple(list1) ā–¶ print(tuple1)
  • 139. Convert Element into Tuple Result
  • 141. Introduction ā–¶ Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. ā–¶ Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
  • 142. Normal Program ā–¶ # Dictionary ā–¶ dict={"ROll":'1',"Name":"Abhishek","Course":"BCA"} ā–¶ print("Dictionary is",dict)
  • 143. Result
  • 144. Updating Dictionary Program ā–¶ # Dictionary ā–¶ dict={"ROll":'1',"Name":"Abhishek","Course":"BCA"} ā–¶ print("Dictionary is",dict) ā–¶ # Updating Dictionary ā–¶ dict["ROll"]=4 ā–¶ dict["Name"]="Ashish" ā–¶ print("nUpdating Dictionary is",dict)
  • 146. Deleted Dictionary Program ā–¶ # Dictionary ā–¶ dict={"ROll":'1',"Name":"Abhishek","Course":"BCA"} ā–¶ print("Dictionary is",dict) ā–¶ # Delete Dictionary ā–¶ del dict["Name"]; # remove entry with key 'Name ā–¶ print("Now Dictionary is",dict) ā–¶ dict.clear(); # remove all entries in dict ā–¶ print("Now Dictionary is",dict) ā–¶ del dict ; # delete entire dictionary ā–¶ print("Now Dictionary is",dict)
  • 148. Properties Of Dictionary ā–¶ Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys. ā–¶ There are two important points to remember about dictionary keys: I. More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. II. Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed.
  • 150. Length in Dictionary Description ā–¶ The method len() gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
  • 151. Length in Dictionary Progarm ā–¶ # Length in Dictionary ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"} ā–¶ print("The Dictionary is",dict) ā–¶ print("n") ā–¶ print(len(dict))
  • 153. Clear in Dictionary Program ā–¶ # Clear in Dictionary ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"} ā–¶ print("The Dictionary is",dict) ā–¶ print("n Dictionary Length ",len(dict)) ā–¶ dict.clear() #Clear Dictionary ā–¶ print("n Now Dictionary Length ",len(dict))
  • 155. Copy in Dictionary program ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"} ā–¶ print("The Dictionary is",dict) ā–¶ # Copy in Dictionary ā–¶ dict2=dict.copy() ā–¶ print("n Copy Dictionary is ",dict2)
  • 157. Get the Element from Key Program This method return a value for the given key. If key is not available, then returns default value None. ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"} ā–¶ print("The Dictionary is",dict) ā–¶ #get the Element from keys ā–¶ print("Get elemnt is ",dict.get(1)) ā–¶ #if key is not in dictionary give default values ā–¶ print("nGet element is ",dict.get(5,"defaultvalue"))
  • 158. Get the Element from Key Result
  • 159. Dict.items() Method in Dictionary Result
  • 160. Dict.keys() Method in Dictionary Program The method keys() returns a list of all the available keys in the dictionary āž¢ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"} āž¢ print("The Dictionary is",dict) āž¢ # dict.key() āž¢ print("n Item is ",dict.keys())
  • 161. Dict.keys() Method in Dictionary Result
  • 162. dict.setdefault(key, default=None)Method in Dictionary Program The method setdefault() is similar to get(), but will set dict[key]=default if key is not already in dict. āž¢ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"} āž¢ print("The Dictionary is",dict) āž¢ # dict.setdefault(key, default=None) āž¢ print("n vlaue: ",dict.setdefault(4,"None"))
  • 164. dict.update(dict2) Method in Dictionary Program ā–¶ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"} ā–¶ print("The Dictionary is",dict) ā–¶ # dict.update(dict2) ā–¶ dict2={5:"Sam",6:"Atif Aslam"} ā–¶ dict.update(dict2) ā–¶ print("Update Dictionary is",dict)
  • 166. dict.values() Method in Dictionary Program The method values() returns a list of all the values available in a given dictionary. āž¢ dict={1:"Abhishek",2:"Ashish",3:"Shubham",4:"Anshu"} āž¢ print("The Dictionary is",dict) āž¢ # dict.values āž¢ print("nvalues :",dict.values())
  • 167. dict.values() Method in Dictionary Result
  • 169. Intro ā–¶ A Function is a self block of code. ā–¶ A Function can be called as a section of a program that is written once and can be executed whenever required in the program, thus making code reusability. ā–¶ A Function is a subprogram that works on data and produce some output.
  • 170. Types Of Function There are two types of Functions. ā–¶ a) Built-in Functions: Functions that are predefined. We have used many predefined functions in Python. ā–¶ b) User- Defined: Functions that are created according to the requirements.
  • 171. Defining a Function A Function defined in Python should follow the following format: ā–¶ 1) Keyword def is used to start the Function Definition. Def specifies the starting of Function block. ā–¶ 2) def is followed by function-name followed by parenthesis. ā–¶ 3) Parameters are passed inside the parenthesis. At the end a colon is marked.
  • 173. Example Normal Program ā–¶ def Sum(): ā–¶ x=10; ā–¶ y=10; ā–¶ z=x+y ā–¶ print("Sum is ",z) ā–¶ ā–¶ Sum() ā–¶
  • 174. Result
  • 175. Invoking a Function Program ā–¶ def Sum(a,b): ā–¶ x=a; ā–¶ y=b; ā–¶ z=x+y ā–¶ print("Sum is ",z) ā–¶ ā–¶ Sum(10,10) # invoking a Function
  • 176. Result
  • 177. return Statement: ā–¶ return[expression] is used to send back the control to the caller with the expression. ā–¶ In case no expression is given after return it will return None. ā–¶ In other words return statement is used to exit the Function definition.
  • 178. Return statement Program ā–¶ def Sum(a,b): ā–¶ x=a; ā–¶ y=b; ā–¶ z=x+y ā–¶ return z # return a variable ā–¶ ā–¶ ret=Sum(10,20) # invoking a Function ā–¶ print("return result function is ",ret)
  • 179. Function Arguments ā–¶ You can call a function by using the following types of formal arguments- ā–¶ Required arguments ā–¶ Keyword arguments ā–¶ Default arguments ā–¶ Variable-length arguments
  • 180. Required Arguments ā–¶ Required arguments are the arguments passed to a function in correct positional order. ā–¶ Here, the number of arguments in the function call should match exactly with the function
  • 181. Program ā–¶ # Function definition is here ā–¶ def printme( str ): ā–¶ "This prints a passed string into this function" ā–¶ print (str) ā–¶ return ā–¶ # Now you can call printme function ā–¶ printme() # This is wrong call Because function need arugument
  • 182. Result
  • 183. Keyword Arguments ā–¶ Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
  • 185. Python can be used to read and write data. Also it supports reading and writing data to Files
  • 186. Printing to the Screen ā–¶ "print" statement is used to print the output on the screen. ā–¶ print statement is used to take string as input and place that string to standard output. ā–¶ Whatever you want to display on output place that expression inside the inverted commas. The expression whose value is to printed place it without inverted commas. Example ā–¶ Print(ā€œHello Abhishekā€) ā–¶ >>Hello Abhishek # Result
  • 187. Input from keybord Python offers two in-built functions for taking input from user. They are: āž¢ Input()
  • 188. Input Program ā–¶ a=input("Enter Number ") ā–¶ print("The Number is ",a) ā–¶ b=input("Input String ") ā–¶ print("This is a String ",b)
  • 190. Opening and Closing a File ā–¶ Before working with Files you have to open the File. To open a File, Python built in function open() is used. It returns an object of File which is used with other functions. Having opened the file now you can perform read, write, etc. operations on the File Syntax obj=open(filenameĀ ,Ā modeĀ ,Ā buffer)Ā Ā Ā  #Opening obj.close() # Closing
  • 191. Here are parameter details- >> file_: The file_name argument is a string value that contains the name of the filnamee that you want to access. >> access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is an optional parameter and the default file access mode is read (r). >> buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default (default behavior).
  • 192. MODES OF FILE Mode Description R It opens in Reading mode. It is default mode of File. Pointer is at beginning of the file. rb It opens in Reading mode for binary format. It is the default mode. Pointer is at beginning of file. r+ Opens file for reading and writing. Pointer is at beginning of file
  • 193. rb+ Opens file for reading and writing in binary format. Pointer is at beginning of file. W Opens file in Writing mode. If file already exists, then overwrite the file else create a new file. wb Opens file in Writing mode in binary format. If file already exists, then overwrite the file else create a new file. w+ Opens file for reading and writing. If file already exists, then overwrite the file else create a new file MODES OF FILE
  • 194. MODES OF FILE wb+ Opens file for reading and writing in binary format. If file already exists, then overwrite the file else create a new file. a Opens file in Appending mode. If file already exists, then append the data at the end of existing file, else create a new file. ab Opens file in Appending mode in binary format. If file already exists, then append the data at the end of existing file, else create a new file. a+ Opens file in reading and appending mode. If file already exists, then append the data at the end of existing file, else create a new file. ab+ Opens file in reading and appending mode in binary format. If file already exists, then append the data at the end of existing file, else
  • 195. FILE OBJECT ATTRIBUTES Attribute Description file.closed Returns true if file is closed, false otherwise file.mode Returns access mode with which file was opened. file.name Returns name of the file
  • 196. Example ā–¶ obj=open("abhi.txt","wb") # Opening a File ā–¶ print("Name of the file : ",obj.name) ā–¶ print("Closed File or Not",obj.closed) ā–¶ print ("Opening mode : ", obj.mode) ā–¶ obj.close() # Closing a File
  • 197. Result
  • 198. Reading and writing a file ā–¶ The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.
  • 199. Writing File Program Syntax fileObject.write(string); Program āž¢ obj=open("abhi.txt","w") āž¢ print("Name of the file : ",obj.name) āž¢ obj.write("Hello Abhishek") # Writing a File āž¢ print("Succsess fully Write") āž¢ obj.close()
  • 201. Reading File Program Syntax fileObject.read([count]); Program āž¢ obj=open("abhi.txt","r") āž¢ print("Name of the file : ",obj.name) āž¢ tmp=obj.read()# Reading a File āž¢ print("n") āž¢ print(tmp) #print reading File āž¢ print("nSuccsess fully Read") āž¢ obj.close()
  • 203. Renaming and Deleting File Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files. Syntax rename : os.rename(current_file_name, new_file_name) syntax Delete : os.remove(file_name)
  • 204. Program to rename the file ā–¶ import os ā–¶ os.rename("old.txt","newFile.txt") ā–¶ print(" Reame Successfully ")
  • 206. Deleting File Program ā–¶ import os ā–¶ os.remove("newfile.txt") ā–¶ print(" Remove Successfully ")
  • 208. Directories in Python All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories.
  • 209. Make a directory by mkdir() Method Program āž¢ import os āž¢ os.mkdir("New Directory") āž¢ print(" Directory made Successfully ")
  • 211. Get working directory by getcwd() Method Program āž¢ import os āž¢ get=os.getcwd() āž¢ print("Current working directory is",get)
  • 213. Remove Directory Program by rmdir() Method ā–¶ import os ā–¶ os.rmdir("hello") ā–¶ print("Successfully Removed")
  • 215. Module
  • 216. ā–¶ A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
  • 217. Advantages Python provides the following advantages for using module: ā–¶ 1) Reusability: Module can be used in some other python code. Hence it provides the facility of code reusability. ā–¶ 2) Categorization: Similar type of attributes can be placed in one module.
  • 218. Importing a Module: There are different ways by which you we can import a module. These are as follows ā–¶ Using import statement ā–¶ Using from.. import statement
  • 219. Using import statement program Save this Fie Example.py # Example ā–¶ # Example.py ā–¶ def sum(a,b): ā–¶ x=a ā–¶ y=b ā–¶ total=x+y; ā–¶ return total
  • 220. Using import statement program Import the Example.py File by import keyword āž¢ import Example āž¢ z=Example.sum(10,20) āž¢ print("Total is ",z)
  • 222. Using from.. import statement program Save this file Example.py āž¢ # Example āž¢ def sum(a,b): āž¢ x=a āž¢ y=b āž¢ total=x+y; āž¢ return total āž¢ āž¢ def Minus(a,b): āž¢ x=a āž¢ y=b; āž¢ result= x-y āž¢ return result
  • 223. Using from.. import statement program Import the Example.py āž¢ from Example import sum,Minus āž¢ z=sum(10,20) āž¢ print("Total is ",z) āž¢ z=Minus(10,20) āž¢ print("Total is ",z)
  • 224. Using from.. import statement Result