Python Made Easy PDF
Python Made Easy PDF
Python Made Easy PDF
• 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 lo 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 in 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,
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.
● 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)
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:
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=‘basic\python’
>>> 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.
▶ 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
▶ 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
▶ 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)
▶
▶ 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
▶
▶ 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
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
▶ 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).
Mode Description
It opens in Reading mode. It
is default mode of File.
R
Pointer is at beginning of the
file.
It opens in Reading mode for
binary format. It is the
rb
default mode. Pointer is at
beginning of file.
Opens file for reading and
r+ writing. Pointer is at
beginning of file
MODES OF FILE
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
▶ 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
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
➢ 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