Python
Python
• software development,
• mathematics,
• system scripting.
Python futures
• Python is Procedural/ Object Oriented/ Scripting Language / Modular Oriented
Programing Language
• Python is Procedural Oriented Programing language futures from C language
• Python is Object Oriented Programing Language futures from C++
• Python is Scripting Oriented Language futures from Pearl, Shell
• Python is Modular Oriented Programing Language futures from Modula
• Python is Freeware and Open Source(Customization possible)
• Python Flavors: Java_Jython, C#.net_Iron Python, BigData_Anakonda Python. Etc..
• Python is Program Friendly High level Language.
• Python is Platform Independent Language. (Same Py program application is run in
different OS )
Python futures
• Python is portable language ( Migrating one platform to another
platform is possible without changing code)
• Python is Dynamical typed other languages are static typed.
• Python is Interpreted (Automatically immediate compile), we not
required compile
• Python is extensible (Other language module/code can be used in
python code)
• We can use legacy of non-python code
• For performance wise little bit slow so where ever we require performance
we go for other language ex: c
Python futures
• Python is Embedded (we can use Python code any other language
applications)
• Python have extensive library (every requirement library is available)
Python Limitations
• Python not having library support for mobile applications
• Python not a good choice for Enterprise applications (ex Banking and
Telecom applications) no library support
• Performance is low (Because Interpreted (line by line code execution)
pypy flavor (JIT Compiler+PVM) is high performance in python flavors
Python Flavors
• Cpython- Standard python (support C language applications)
• Jpython/Jython –(support Java language applications)
• Iron Python– C#.net
• Ruby Python– Ruby
• Anakonda python – for Data Science , Michine Learning applications
• Stakless – python for concorence
• Pypy – Python for speed.
What can Python do?
• Creating Variables
• Variable Names
• Assign Value to Multiple Variables
• Output Variables
• Global Variables
• The global Keyword
Python Key words
total:33
Python Variables
Creating Variables
Variables are containers for storing data values. Unlike other programming languages, Python has no command
for declaring a variable.
A variable is created the moment Variables do not need to be String variables can be declared
you first assign a value to it. declared with any particular either by using single or double
type and can even change quotes:
type after they have been set.
Python allows you to assign values to multiple Python allows you to assign values to
variables in one line multiple variables in one line
x, y, z = "Orange", "Banana", "Cherry" x = y = z = "Orange"
print(x) print(x)
print(y) print(y)
print(z) print(z)
Python Variables
Output Variables
The Python print statement is often used to output variables
To combine both text and a You can also use For numbers, If you try to combine a
variable, Python uses the + character to add a the + character works string and a number,
the + character: variable to another as a mathematical Python will give you an
variable: operator: error:
x = "awesome" x = "Python is " x = 5 x = 5
print("Python is " + x) y = "awesome" y = 10 y = "John"
z = x + y print(x + y) print(x + y)
print(z)
Result: Python is awesome Result: 15 Result: Error
Result: Python is awesome
Python Variables
Global Variables
Variables that are created outside of a function are known as global variables. Global variables can be used by
everyone, both inside of functions and outside.
Create a variable outside of a Create a variable inside a function, with the same name
function, and use it inside the as the global variable
function
x = "awesome" x = "awesome"
def myfunc(): def myfunc():
print("Python is " + x) x = "fantastic"
print("Python is " + x)
myfunc()
myfunc()
print("Python is " + x)
If you create a variable with the same name inside a function,
this variable will be local, and can only be used inside the
function. The global variable with the same name will remain as
it was, global and with the original value.
Python Variables
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used
inside that function.
To create a global variable inside a function, Python use the global keyword if you
you can use the global keyword want to change a global variable inside a
function.
If you use the global keyword, the variable To change the value of a global variable
belongs to the global scope: inside a function, refer to the variable by
using the global keyword:
def myfunc():
global x x = "awesome"
x = "fantastic"
def myfunc():
myfunc() global x
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Python Data Types
• Int
• Float
• Complex
• Type Conversion
• Random Number
Python Type-Casting
Python Strings
• Assign String to a Variable
• Multiline Strings
• Strings are Arrays
• Slicing
• Negative Indexing
• String Length
• String Methods
• Check String
• String Concatenation
• String Format
• Escape Character
• String Methods
Python Booleans
• Boolean Values
• Evaluate Values and Variables
• Most Values are True
• Most Values are True
• Functions can Return a Boolean
Python Operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Python Collections (Arrays)
• Create List
• Remove Item
• Access Items
• Copy a List
• Negative Indexing • Join Two Lists
• Range of Indexes • The list() Constructor
• Range of Negative Indexes • List Methods
• Change Item Value
• Loop Through a List
• Check if Item Exists
• List Length
• Add Items
Python Tuples
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
• Create a Set
• Access Items
• Change Items
• Add Items
• Get the Length of a Set
• Remove Item
• Join Two Sets
• The set() Constructor
• Set Methods
Python Sets & list, tuple & frozenset differ
A set is a collection which is unordered and unindexed. In Python sets are written with curly
brackets.
Python Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values
• Create a Dictionary
• Accessing Items
• Change Values
• Loop Through a Dictionary
• Check if Key Exists
• Dictionary Length
• Adding Items
• Removing Items
• Copy a Dictionary
• Nested Dictionaries
• The dict() Constructor
• Dictionary Methods
Python Operators
Python If ... Else
• Python Conditions and If statements
• Indentation
• Elif
• Else
• Short Hand If
• Short Hand If ... Else
• And
• Or
• Nested If
• The pass Statement
Python Loops
• Creating a Function
• Calling a Function
• Arguments
• Parameters or Arguments?
• Number of Arguments
• Arbitrary Arguments, *args
• Keyword Arguments
• Arbitrary Keyword Arguments, **kwargs
• Default Parameter Value
• Passing a List as an Argument
• Return Values
• The pass Statement
• Recursion
Python Lambda Function
A lambda function is a small anonymous function. A lambda function can take any number of arguments,
but can only have one expression.
• Syntax <lambda arguments : expression>
• Why Use Lambda Functions?
Python Arrays
Arrays are used to store multiple values in one single variable. Python does
not have built-in support for Arrays, but Python Lists can be used instead.
• Create an Arrays
• What is an Array?
• Access the Elements of an Array
• The Length of an Array
• Looping Array Elements
• Adding Array Elements
• Removing Array Elements
• Array Methods
Python Classes and Objects
Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.
• Create a Class
• Create Object
• The __init__() Function
• Object Methods
• The self Parameter
• Modify Object Properties
• Delete Object Properties
• Delete Objects
• The pass Statement
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also
called derived class.
• Iterator vs Iterable
• Looping Through an Iterator
• Create an Iterator
• StopIteration
Python Scope
A variable is only available from inside the region it is created.
This is called scope.
• Local Scope
• Function Inside Function
• Global Scope
• Naming Variables
• Global Keyword
Python Modules
Consider a module to be the same as a code library. A file containing a set of
functions you want to include in your application.
• Create a Module
• Use a Module
• Variables in Module
• Naming a Module
• Re-naming a Module
• Built-in Modules
• Using the dir() Function
• Import From Module
Python Datetime
A date in Python is not a data type of its own, but we can import
a module named datetime to work with dates as date objects.
• Python Dates
• Date Output
• Creating Date Objects
• The strftime() Method
Python JSON
Python has a built-in package called json, which can be used to work with JSON data. JSON is a syntax
for storing and exchanging data. JSON is text, written with JavaScript object notation.
• RegEx Module
• RegEx in Python
• RegEx Functions
• Metacharacters
• Special Sequences
• Sets
• The findall() Function
• The search() Function
• The split() Function
• The sub() Function
• Match Object
Python PIP
PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.
• What is a Package?
• Check if PIP is Installed
• Install PIP
• Download a Package
• Using a Package
• Find Packages
• Remove a Package
• List Packages
Python Try Except
The try block lets you test a block of code for errors. The except block lets you
handle the error. The finally block lets you execute code, regardless of the result
of the try- and except blocks.
• Exception Handling
• Many Exceptions
• Else
• Finally
• Raise an exception
Python User Input
Python allows for user input. That means we are able to ask the user for input. The method is a bit
different in Python 3.6 than Python 2.7. Python 3.6 uses the input() method. Python 2.7 uses the
raw_input() method.
• Python 3.6
• username = input("Enter username:")
print("Username is: " + username)
• Python 2.7
• username = raw_input("Enter username:")
print("Username is: " + username)
• String format()
• Multiple Values
• Index Numbers
• Named Indexes
Python String Formatting
To make sure a string will display as expected, we can format the
result with the format() method.
String format() Multiple Values
You can add parameters inside the curly brackets to specify And add more placeholders:
how to convert the value: Example
Example quantity = 3
Format the price to be displayed as a number with two itemno = 567
price = 49
decimals: myorder = "I want {} pieces of item
number {} for {:.2f} dollars."
txt = "The price is {:.2f} dollars" print(myorder.format(quantity,
itemno, price))
Python String Formatting
To make sure a string will display as expected, we can format the
Multiple Values result with the format() Multiple
method. Values
The format() method allows you to format selected parts of a string. If you want to use more values, just add more
values to the format() method:
Sometimes there are parts of a text that you do not control, maybe they come print(txt.format(price, itemno, count))
from a database, or user input?
To control such values, add placeholders (curly brackets {}) in the text, and run the
values through the format() method:
Example And add more placeholders:
Add a placeholder where you want to display the price: Example
price = 49 quantity = 3
txt = "The price is {} dollars" itemno = 567
print(txt.format(price)) price = 49
myorder = "I want {} pieces of item number
{} for {:.2f} dollars."
You can add parameters inside the curly brackets to specify how print(myorder.format(quantity, itemno,
to convert the value: price))
Example
Format the price to be displayed as a number with two decimals:
txt = "The price is {:.2f} dollars"
Python File Handling
File handling is an important part of any web application. Python has several functions for creating, reading, updating, and
deleting files.
• Python File Open
• File Handling Keys
• Syntax
• Open a File on the Server
• Read Only Parts of the File
• Read Lines
• Close Files
• Python File Write
• Write to an Existing File
• Create a New File
• Python Delete File
• Check if File exist:
• Delete Folder
Python File Handling
Python File Open open()
• File Handling
• The key function for working with files in Python is the open() function
• The open() function takes two parameters; filename, and mode.
• There are four different methods (modes) for opening a file:
• “r” - Read - Default value. Opens a file for reading, error if the file does not exist
• “a” - Append - Opens a file for appending, creates the file if it does not exist
• “w” - Write - Opens a file for writing, creates the file if it does not exist
• “x” - Create - Creates the specified file, returns an error if the file exists
• In addition you can specify if the file should be handled as binary or text mode
• “t” - Text - Default value. Text mode
• “b” - Binary - Binary mode (e.g. images)
• Syntax
• To open a file for reading it is enough to specify the name of the file:
• f = open("demofile.txt")
• The code above is the same as:
• f = open("demofile.txt", "rt") (r-read & t-Text both are default values, we do not need to specify them)
• Note: Make sure the file exists, or else you will get an error.
Python File Handling
Assume we have the following file, located in the same Assume we have the following file, located in the
folder as Python: same folder as Python:
demofile.txt demofile.txt
Hello! Welcome to demofile.txt Hello! Welcome to demofile.txt
This file is for testing purposes. This file is for testing purposes.
Good Luck! Good Luck!
The open() function returns a file object, which has By default the read() method returns the whole
a read() method for reading the content of the file: text, but you can also specify how many
characters you want to return:
Example Example
f = open("demofile.txt", "r") Return the 5 first characters of the file:
print(f.read()) f = open("demofile.txt", "r")
print(f.read(5))
Python File Handling
Read Lines Close Files
You can return one line by using the readline() method: It is a good practice to always close the file when
Example you are done with it.
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines: Example
Example:- Read two lines of the file: Close the file when you are finish with it:
f = open("demofile.txt", "r") f = open("demofile.txt", "r")
print(f.readline()) print(f.readline())
print(f.readline()) f.close()
By looping through the lines of the file, you can read the whole file, line by line: Note: You should always close your files, in some
Example:- Loop through the file line by line: cases, due to buffering, changes made to a file
f = open("demofile.txt", "r") may not show until you close the file.
for x in f:
print(x)
Python File Write
To write to an existing file, you must add a parameter to the open() function: Note: the "w" method will overwrite the entire file.
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example Example
Open the file "demofile2.txt" and append content to the file: Open the file "demofile3.txt" and overwrite the
content:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!") f = open("demofile3.txt", "w")
f.close() f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r") #open and read the file after the appending:
print(f.read()) f = open("demofile3.txt", "r")
print(f.read())
Python File Create
To create a new file in Python, use the open() method, with one of the Note: the "w" method will Create a new file if it
following parameters:
does not exist.
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example Example
Create a file called "myfile.txt": Create a new file if it does not exist:
f = open("myfile.txt", "x") f = open("myfile.txt", "w")
To delete a file, you must import the OS To avoid getting an error, you might want To delete an entire folder, use
module, and run its os.remove() function: to check if the file exists before you try to the os.rmdir() method:
delete it: