Python PPT 03

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

Pytho

n
Introduction
What can python
do?
• Instagram
• Spotify
• Netflix
• Google
• Dropbox
Why
Python?
• Readable and Maintainable Code
• Multiple Programming Paradigms
• Compatible with Major Platforms and Systems
• Robust Standard Library
• Many Open Source Frameworks and Tools
• Web app development
• Data science
• Scripting
• Database programming
• Quick prototyping
Comparison with
Java
• Java • Python

public class HelloWorld print("Hello, world!")


{
public static void main (String[] args)
{
System.out.println("Hello,world!");
}
}
Contd.
.
Install
Python
• https://www.python.org/downloads/
• https://www.liquidweb.com/kb/install-pip-windows/
• https://programwithus.com/learn-to-code/Pip-and-virtualenv-on-
Windows/
• https://www.jetbrains.com/pycharm/download/
• virtualenv -p python3 virtualenv_name
• myenv\Scripts\activate
Printing in
Python
Multiple values can be displayed by the single print() function separated by comma.
The following example displays values of name and age variables using the
single print() function.
Example:
name="Ram"
age=21
print("Name:
", name,
"Age:",age)
print(name,a
ge,sep=",")
print("Name:
Input
sThe input() function is a part of the core library of standard Python distribution. It
reads the key strokes as a string object which can be referred to by a variable
having a suitable name

Example:
name=input("Enter your name: ")
Comment
s
In a Python script, the symbol # indicates the start of a comment line. It iseffective
till the end of the line in the editor. If # is the first character of the line, then the
entire line is a comment. It can be used also in the middle of a line. The textbefore
it is a valid Python expression, while the text following is treated as acomment.
Example:
# this is a comment
print ("Hello World")
print ("Welcome to
Python Tutorial")
#this is also a
comment but after a
statement.
Variables
Any value of certain type is stored
in the computer's memory for
processing. Out of available
100
memory locations, one is
randomly allocated for storage. In
order to conveniently and 104

repeatedly refer to the stored


value, it is given a suitable name.
A value is bound to a name by the 108

assignment operator '='.


Dynamic
Typing
• One of the important features of Python is that it is a dynamically-
typed language. Programming languages such as C, C++, Java, and C#
are statically-typed languages. A variable in these languages is a user-
friendly name given to a memory location and is intended to store the
value of a particular data type.
• A variable in Python is not bound permanently to a specific data type.
Instead, it only serves as a label to a value of a certain type. Hence,
the prior declaration of variable's data type is not possible. In Python,
the data assigned to a variable decides its data type and not the other
way around.
Built in data
types
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set
Boolean Type: bool
Binary Types: bytes
Sequence
types
• 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.
Mutable and Immutable
Objects
Data objects are stored in a computer's memory for processing. Some of these
values can be modified during processing, but contents of others can't be altered
once they are created in the memory.
Number values, strings, and tuple are immutable, which means their contents can't
be altered after creation.
On the other hand, collection of items in a List or Dictionary object can be
modified. It is possible to add, delete, insert, and rearrange items in a list or
dictionary. Hence, they are mutable objects
Styling
Guidelines
• https://www.python.org/dev/peps/pep-0008/
Arithmeti • Assume variable a holds 10 and
c variable b holds 20, then −
Operators
Operator Description Example
• These operators compare the values on either sides of them
Compariso and decide the relation among them. They are also called
n Relational operators.
• Assume variable a holds 10 and variable b holds 20, then −
Operators
Functions in
Python
• A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
• As you already know, Python gives you many built-in functions like print(), etc. but you can also
create your own functions. These functions are called user-defined functions.
• Defining a Function
• You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string of the
function or docstring.
• The code block within every function starts with a colon (:) and is indented.
Contd.
.
• Function Arguments
• You can call a function by using the following types of formal
arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Lambd
a
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can only
have one expression.
x = lambda a : a + 10
print(x(5))
Ma
p
• Map is a Python built-in function that takes in a function and
a sequence as arguments and then calls the input function on each
item of the sequence.
l=[1,2,3,4]
list(map(lambda x :x*2,l))
[2, 4, 6, 8]
Function
s
• Create a function showEmployee() in such a way that it should
accept employee name, and it’s salary and display both, and if the
salary is missing in function call it should show it as 9000
• First, def a function called distance_from_zero, with one argument
(choose any argument name you like). If the type of the argument is
either int or float, the function should return the absolute value of
the function input. Otherwise, the function should return "Nope".
Check if it works calling the function with -5.6 and "what?".
Modules in
Python
• 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.
• Simply, a module is a file consisting of Python code. A module can define
functions, classes and variables. A module can also include runnablecode.
• Example
• The Python code for a module named aname normally resides in a file
named aname.py. Here's an example of a simple module, support.py
• def print_func( par ): print "Hello : ", par return
The Module Search
Path
When a module named spam is imported, the interpreter first searches for a built-in
module with that name. If not found, it then searches for a file named spam.py in a list of
directories given by the variable sys.path. sys.path is initialized from these locations:
The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
The installation-dependent default.
Note
On file systems which support symlinks, the directory containing the input script is
calculated after the symlink is followed. In other words the directory containing the symlink
is not added to the module search path.
After initialization, Python programs can modify sys.path. The directory containing the
script being run is placed at the beginning of the search path, ahead of the standardlibrary
path. This means that scripts in that directory will be loaded instead of modules of the
same name in the library directory. This is an error unless the replacement is intended.
Exception
s
• Even if a statement or expression is syntactically correct, it may cause
an error when an attempt is made to execute it. Errors detected
during execution are called exceptions and are not unconditionally
fatal. Most exceptions are not handled by programs.
• 10 * (1/0)
• 4 + spam*3
• '2' + 2
Handling
Exceptions
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid
number. Try again...")
Files in
Python
• File handling is an important part of any application.
• Python has several functions for creating, reading, updating, and deleting files.
• 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 notexist
"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 fileexists

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

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

• Because "r" for read, and "t" for text are the
default values, you do not need to specify
Read.
.The open() function returns a file object, which has a read() method for reading the
content of the file. By default the read() method returns the whole text, but you
can also specify how many characters you want to return:
f = open("demofile.txt", "r")
print(f.read())# print(f.read(5))
Can return one line by using the readline() method:
f = open("demofile.txt", "r")
print(f.readline())

Note: Always close the file


using f.close()
Write
To write to an existing file:
• "a" - Append - will append to the end of the file
• "w" - Write - will overwrite any existing content
To create a new file in Python, use the open() method, with one of the following parameters:
• "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
f = open("demofile2.txt", ”w")
f.write("Now the file content!")
f.close()
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Classe
s• Classes provide a means of bundling data and functionality together. Creating a new class
creates a new type of object, allowing new instances of that type to be made. Each class
instance can have attributes attached to it for maintaining its state. Class instances can
also have methods (defined by its class) for modifying its state.
Syntax:
class ClassName:
<statement-1>
.
.
.
<statement-N>
Inheritanc
e
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
Syntax:
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
Polymorphism and
Inheritance
The child classes in Python also inherit methods and attributes from
the parent class. We can redefine certain methods and attributes
specifically to fit the child class, which is known as Method Overriding.
Polymorphism allows us to access these overridden methods and
attributes that have the same name as the parent class.
Iterator
•The built-in function iter takes an iterable object and returns an iterator.
x = iter([1, 2, 3])
x
<listiterator object at 0x1004ca850>
next(x)
1
next(x)
2
next(x)
3
next(x)
Iterator
Example
class yrange:
def init (self,
n): self.i = 0
self.n = n

def iter
(self): return
self

def next
(self): if self.i <
self.n:
i = self.i
self.i += 1
return i
else:
raise
StopIte
Generator
s
• Generators simplifies creation of iterators. A generator is a function
that produces a sequence of results instead of a single value.
def yrange(n):
i=0
while i < n:
yield i
i += 1
Condition Return Value

any() All values are true True

function All values are false False

• The any() function returns One value is true (others are false) True
True if any element of an
iterable is True. If not,
any() returns False.
any(iterable) One value is false (others are true) True

Empty Iterable False


Truth table for all()

When Return Value


all() All values are true True
function
All values are false False

• The all() method returns


True when all elements in One value is true (others are false) False
the given iterable are true.
If not, it returns False.

One value is false (others are true) False

Empty Iterable
True
With
statement
• with statement in Python is used in exception handling to make the
code cleaner and much more readable. It simplifies the management
of common resourc# using with statement
with open('file_path', 'w') as file:
file.write('hello world !')
Context
Management
• A high-level explanation of the context management protocol is:
• The expression is evaluated and should result in an object called a “context manager”. The context manager
must have enter () and exit () methods.
• The context manager’s enter () method is called. The value returned is assigned to
VAR. If no as VAR clause is present, the value is simply discarded.
• The code in BLOCK is executed.
• If BLOCK raises an exception, the context manager’s exit () method is called with three arguments,
the exception details (type, value, traceback, the same values returned by sys.exc_info(), which can also
be None if no exception occurred). The method’s return value controls whether an exception is re-raised:
any false value re-raises the exception, and True will result in suppressing it. You’ll only rarely want to
suppress the exception, because if you do the author of the code containing the ‘with’ statement will never
realize anything went wrong.
• If BLOCK didn’t raise an exception, the exit () method is still called, but type, value, and traceback
are all None.
Working
# a simple file writer object

class MessageWriter(object):
def init (self, file_name):
self.file_name = file_name

def enter (self):


self.file = open(self.file_name, 'w')
return self.file

def exit (self):


self.file.close()

# using with statement with MessageWriter

with MessageWriter('my_file.txt') as xfile:


xfile.write('hello world')
Problem
s
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,


return [0, 1].
Database and
Python
A database is an organized collection of structured information, or data, typically stored electronically in a
computer system. A database is usually controlled by a database management system (DBMS). Together, the
data and the DBMS, along with the applications that are associated with them, are referred to as a database
system, often shortened to just database.
Data within the most common types of databases in operation today is typically modelled in rows and columns
in a series of tables to make processing and data querying efficient. The data can then be easily accessed,
managed, modified, updated, controlled, and organized. Most databases use structured query language (SQL)
for writing and querying data.
SQL:
SQL is a programming language used by nearly all relational databases to query, manipulate, and define data,
and to provide access control. SQL was first developed at IBM in the 1970s with Oracle as a major contributor,
which led to implementation of the SQL ANSI standard, SQL has spurred many extensions from companiessuch
as IBM, Oracle, and Microsoft. Although SQL is still widely used today, new programming languages are
beginning to appear.
Thread
sIn simple words, a thread is a sequence of such instructions within a program that can be executed
independently of other code. For simplicity, you can assume that a thread is simply a subset of a process!
A thread contains all this information in a Thread Control Block (TCB):
• Thread Identifier: Unique id (TID) is assigned to every new thread
• Stack pointer: Points to thread’s stack in the process. Stack contains the local variables under thread’s
scope.
• Program counter: a register which stores the address of the instruction currently being executedby
thread.
• Thread state: can be running, ready, waiting, start or done.
• Thread’s register set: registers assigned to thread for computations.
• Parent process Pointer: A pointer to the Process control block (PCB) of the process that the thread
lives on.
Problems – Race
Condition
A race condition occurs when two or more threads can access shared data and they try to change it at the same
time. As a result, the values of variables may be unpredictable and vary depending on the timings of context
switches of the processes.
Semaphor
e
A semaphore is a synchronization object that controls access by multiple processes/threads to a common
resource in a parallel programming environment. It is simply a value in a designated place in operating system
(or kernel) storage that each process/thread can check and then change. Depending on the value that is found,
the process/thread can use the resource or will find that it is already in use and must wait for some period
before trying again. Semaphores can be binary (0 or 1) or can have additional values. Typically, a
process/thread using semaphores checks the value and then, if it using the resource, changes the value to
reflect this so that subsequent semaphore users will know to wait.
REST
Framework
A REST API is a standardized way to provide data to other applications. Those applications can then use the
data however they want. Sometimes, APIs also offer a way for other applications to make changes to the data.
There are a few key options for a REST API request:
• GET — The most common option, returns some data from the API based on the endpoint you visit and any
parameters you provide
• POST — Creates a new record that gets appended to the database
• PUT — Looks for a record at the given URI you provide. If it exists, update the existing record. If not, create a
new record
• DELETE — Deletes the record at the given URI
• PATCH — Update individual fields of a record
Typically, an API is a window into a database. The API backend handles querying the database and formatting
the response. What you receive is a static response, usually in JSON format, of whatever resource you
requested.
XM
L
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>
JSO
N
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}
JSON Data
types
Datatypes:
• In JSON, values must be one of the following data types:
• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null
RegE
xA Regular Expression (RegEx) is a sequence of characters that defines a search pattern.
^a...s$
The pattern is: any five letter string starting with a and ending with s.

MetaCharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a list of metacharacters:
[] . ^ $ * + ? {} () \ |

[] - Square brackets
Square brackets specifies a set of characters you wish to match.
Contd.
.Period
• A period matches any single character (except newline '\n’).
^ - Caret
• The caret symbol ^ is used to check if a string starts with a certain character
Dollar
• The dollar symbol $ is used to check if a string ends with a certain character.
Star
• The star symbol * matches zero or more occurrences of the pattern left to it.
Question Mark
• The question mark symbol ? matches zero or one occurrence of the pattern left to it.
Contd.
.
{} - Braces
• Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern left to it.

() - Group
• Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string thatmatches
either a or b or c followed by xz

\ - Backslash
• Backlash \ is used to escape various characters including all metacharacters. For example,
• \$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine in a
special way.
• If you are unsure if a character has special meaning or not, you can put \ in front of it. This makes sure the
character is not treated in a special way.
Contd.
.• \A - Matches if the specified characters are at the start of a string.
• \b - Matches if the specified characters are at the beginning or end of a word.
• \B - Opposite of \b. Matches if the specified characters are not at the beginning or end of a word.
• \d - Matches any decimal digit. Equivalent to [0-9]
• \D - Matches any non-decimal digit. Equivalent to [^0-9]
• \s - Matches where a string contains any whitespace character.
• \S - Matches where a string contains any non-whitespace character.
• \w - Matches any alphanumeric character (digits and alphabets).
• \W - Matches any non-alphanumeric character
• \Z - Matches if the specified characters are at the end of a string.
Client Server
Python

You might also like