0% found this document useful (0 votes)
86 views

Python

Python is a popular high-level programming language that can be used for a wide range of applications. It is an interpreted language that is easy to read and write, and it has a large standard library. Python can be used for web development, software development, data science, and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Python

Python is a popular high-level programming language that can be used for a wide range of applications. It is an interpreted language that is easy to read and write, and it has a large standard library. Python can be used for web development, software development, data science, and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Python 

Python is a General Purpose High Level programming language.


Python can be used on a server to create web applications.
What is Python?
• Python is a popular Dynamic programming language. It was created
by Guido van Rossum(Nether Land), Dev in 1989 and released in Feb
20th 1991.
• It is used for:
• web development (server-side),

• 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?

• Python can be used on a server to create web applications.


• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.
• Python can be used for Standalone applications, Game development,
Network applications,
• Machine Learning, Artificial Intelligence, Data Science, Neuro Networks, IOT
Etc..
Why Python?

• Python works on different platforms (Windows, Mac, Linux,


Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with
fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
• Python can be treated in a procedural way, an object-orientated way
or a functional way.
Good to know

• The most recent major version of Python is Python 3, which we shall


be using in this tutorial. However, Python 2, although not being
updated with anything other than security updates, is still quite
popular.
• In this tutorial Python will be written in a text editor. It is possible to
write Python in an Integrated Development Environment, such as
Thonny, Pycharm, Netbeans or Eclipse which are particularly useful
when managing larger collections of Python files.
Python Syntax compared to other programming languages

• Python was designed for readability, and has some similarities to


the English language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope;
such as the scope of loops, functions and classes. Other
programming languages often use curly-brackets for this purpose.
Python Install
• To check if you have python installed on a Windows PC
C:\Users\Your Name>python –version (or)
C:\Users\Your Name>py
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

to quit the python command line interface:


exit()
Python Variables

• 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.

x = 5 x = 4 # x is of type int x = "John"


y = "John" x = "Sally" # x is now of type # is the same as
print(x) str x = 'John'
print(y) print(x)
Python Variables
Variable Names

• A variable can have a short name (like x and y) or a more descriptive


name (age, carname, total_volume).
• Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
• Remember that variable names are case-sensitive
Python Variables
Assign Value to Multiple Variables

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

• Built-in Data Types


• Getting the Data Type
• Setting the Data Type
• Setting the Specific Data Type
Python Data Types
Python Numbers

• 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)

• List is a collection which is ordered and changeable. Allows duplicate


members.
• Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set is a collection which is unordered and unindexed. No duplicate
members.
• Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.
Python Lists
A list is a collection which is ordered and changeable. In Python lists are
written with square brackets

• 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 Tuple • Tuple Length


• Access Tuple Items • Add Items
• Negative Indexing • Create Tuple With One Item
• Range of Indexes • Join Two Tuples
• The tuple() Constructor
• Range of Negative Indexes
• Tuple Methods
• Change Tuple Values
• Loop Through a Tuple
• Check if Item Exists
Python List & Tuples Differences
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets.
A list is a collection which is ordered and changeable. In Python lists are written with square brackets
Python Sets
A set is a collection which is unordered and unindexed. In Python sets
are written with curly 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

• The while Loop


• The break Statement
• The continue Statement
• The else Statement
• Python For Loops
• Looping Through a String
• The break Statement
• The continue Statement
• The range() Function
• Else in For Loop
• Nested Loops
• The pass Statement
Python Functions
A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result.

• 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.

• Create a Parent Class


• Create a Child Class
• Add the __init__() Function
• Use the super() Function
• Add Properties
• Add Methods
Python Iterators
An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through
all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

• 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.

• Defining Json in python


• Parse JSON - Convert from JSON to Python
• Convert from Python to JSON
• Format the Result
• Order the Result
Python RegEx
A RegEx, or Regular Expression, is a sequence of characters that forms a search
pattern. RegEx can be used to check if a string contains the specified search pattern.

• 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)

• Note: Python stops executing when it comes to the input() function,


and continues when the user has given some input.
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
• 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

• The format() method allows you to format selected parts of a string.


• Sometimes there are parts of a text that you do not control, maybe they come 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 If you want to use more values, just add
Add a placeholder where you want to display the price: more values to the format() method:
price = 49
txt = "The price is {} dollars" print(txt.format(price, itemno, count))
print(txt.format(price))

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

Open a File on the Server Read Only Parts of the File

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

Write to an Existing File

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

Create a New File

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")

Result: a new empty file is created!


Python File Delete

Delete a File Check if File exist: Delete Folder

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:

Example Check if file exists, then delete it: Example


import os
Remove the file "demofile.txt": if os.path.exists("demofile.txt"): Remove the folder “myfolder":
  os.remove("demofile.txt")
import os else:
os.remove("demofile.txt") import os
  print("The file does not exist") os.rmdir("myfolder")

You might also like