Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Python

Uploaded by

asoktiruppur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python

Uploaded by

asoktiruppur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 194

PYTHON

By Malathi.K
Python

• Python is a very popular general-purpose interpreted, interactive,


object-oriented, and high-level programming language.

• Python is dynamically-typed (data types are checked during


execution)and garbage-collected programming language. It was
created by Guido van Rossum during 1985- 1990
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.
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-oriented way or a functional way.


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 Installation

• Python downloads
• https://www.python.org/downloads/
Print statement

• print("Hello, World!")

• To print a statement “print” method is used


Comments

Comments can be used to explain Python code.


• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing
code.

• Comments start with #,python will ignore them

print("Hello, World!") #This is a comment


Comments

• Since Python will ignore string literals that are not assigned to a variable, you can add a
multiline string (triple quotes) in your code, and place your comment inside it:

• """
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Data structures
• Data Structures are a way of organizing data so that it can be accessed
more efficiently depending upon the situation.
• Data Structures are fundamentals of any programming language around
which a program is built.
• Python helps to learn the fundamental of these data structures in a
simpler way as compared to other programming languages.The in_build
data structures are
• - List
• - Set
• -Tuple
• - Dictionary
List
• Lists are used to store multiple items in a single variable
• Lists are created using square brackets:
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second
item has index [1] etc.
list1 = ["apple", "banana", "cherry"]
print(list1)
• Allow Duplicates
Set

• Sets are used to store multiple items in a single variable.


• A set is a collection which is unordered, unchangeable*,
and unindexed.
• Set items are unchangeable, but you can remove items and
add new items.
• Sets are written with curly brackets.
• set1 = {"apple", "banana", "cherry", True, 1, 2}

print(set1)
Tuple
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Tuple items are ordered, unchangeable, and allow duplicate
values.
• Tuple items are indexed, the first item has index [0], the
second item has index [1] et
• tuple1= ("apple", "banana", "cherry", "apple", "cherry")
print(tuple1)
• Allows duplicates
Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not
allow duplicates..
• Dictionaries are written with curly brackets, and have keys and values:
• Dictionary items are presented in key:value pairs, and can be referred
to by using the key name.
• dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(dict1)
Data types
• x = str("Hello World") str
• x = int(20) int
• x = float(20.5) float
• x = complex(1j) complex
• x = list(("apple", "banana", "cherry")) list
• x = tuple(("apple", "banana", "cherry")) tuple
• x = range(6) range
• x = dict(name="John", age=36) dict
• x = set(("apple", "banana", "cherry")) set
• x = frozenset(("apple", "banana", "cherry")) frozenset
• x = bool(5) bool
String

• Strings in python are surrounded by either single quotation marks, or double


quotation marks.
• 'hello' is the same as "hello".

• You can display a string literal with the print() function:


• a = "Hello"
print(a)
Slicing

• You can return a range of characters by using the slice syntax.


• Specify the start index and the end index, separated by a colon,
to return a part of the string.
•b = "Hello, World!"
print(b[2:5])
• Get the characters from the start to position 5 (not included)
• b = "Hello, World!"
print(b[:5])
• Get the characters from position 2, and all the way to the
end:
•b = "Hello, World!"
print(b[2:])
• Use negative indexes to start the slice from the end of the
string
•b = "Hello, World!"
print(b[-5:-2])
Tuple Slicing
• # Tuple slicing
• T = (1, 2, 3, 4, 5)
• slice_obj1 = slice(3)
• slice_obj2 = slice(1, 5, 2)

• print("Tuple slicing")
• print(T[slice_obj1])
• print(T[slice_obj2])
String

• The upper() method returns the string in upper case:


• The lower() method returns the string in lower case
• The strip() method removes any whitespace from the beginning or the end
Simple input and output

• # Taking input from the user


• name = input("Enter your name: ")

• # Output
• print("Hello, " + name)
• print(type(name))
Simple Output formating

• Using String Modulo Operator(%)

• quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f}
dollars."
print(myorder.format(quantity, itemno, price))
• age = 36
• name = "John"
• txt = "His name is {1}. {1} is {0} years old."
• print(txt.format(age, name))

myorder = "I have a {carname}, it is a {model}."


print(myorder.format(carname = "Ford", model = "Mustang"))
Operators
Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y
Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3


Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Operator Description Example

and Returns True if both x < 5 and x < 10


statements are true

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, not(x < 5 and x < 10)


returns False if the result
is true
is Returns True if both x is y
variables are the same
object

is not Returns True if both x is not y


variables are not the
same object

in Returns True if a x in y
sequence with the
specified value is
present in the object

not in Returns True if a x not in y


sequence with the
specified value is not
present in the object
Operat Name Description Example
or

& AND Sets each bit to 1 if x&y


both bits are 1

| OR Sets each bit to 1 if x|y


one of two bits is 1

^ XOR Sets each bit to 1 if x^y


only one of two bits is
1
~ NOT Inverts all the bits ~x
<< Zero fill left Shift left by pushing zeros x << 2
shift in from the right and let
the leftmost bits fall off

>> Signed right Shift right by pushing x >> 2


shift copies of the leftmost bit
in from the left, and let the
rightmost bits fall off
Identation

• Indentation refers to the spaces at the beginning of a code


line.
• Where in other programming languages the indentation in
code is for readability only, the indentation in Python is very
important.
• Python uses indentation to indicate a block of code.
• if 5 > 2:
print("Five is greater than two!")
If statement

• An "if statement" is written by using the if keyword.


• a = 33
b = 200
if b > a:
print("b is greater than a")
Elif statement

• The elif keyword is Python's way of saying "if the previous conditions were not
true, then try this condition".
• a = 33
• b = 33
• if b > a:
• print("b is greater than a")
• elif a == b:
• print("a and b are equal")
While loop

• With the while loop we can execute a set of statements as


long as a condition is true.
•i = 1
while i < 6:
print(i)
i += 1
For Loop

• A for loop is used for iterating over a sequence (that is either


a list, a tuple, a dictionary, a set, or a string).
• With the for loop we can execute a set of statements, once
for each item in a list, tuple, set etc.
• fruits= ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Range statement

• The range() function returns a sequence of numbers, starting from 0 by


default, and increments by 1 (by default), and stops before a specified
number.
• Syntax-range(start, stop, step)
• x = range(3, 6)
for n in x:
print(n)
Break

• With the break statement we can stop the loop even if the
while condition is true:
•i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Continue

• With the continue statement we can stop the current


iteration, and continue with the next:
•i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Assert

• The assert keyword is used when debugging code.


• The assert keyword lets you test if a condition in your code returns True, if
not, the program will raise an AssertionError.
•x = "hello"

#if condition returns True, then nothing happens:


assert x == "hello"

#if condition returns False, AssertionError is raised:


assert x == "goodbye"
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.
• In Python a function is defined using the def keyword:
• def my_function():
print("Hello from a function")

my_function()
Variable arguments

• Information can be passed into functions as arguments.


• Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
• def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
2 Argumnets

• This function expects 2 arguments, and gets 2 arguments:

• def my_function(fname, lname):


• print(fname + " " + lname)

• my_function("Emil", "Refsnes")
Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.

• This way the function will receive a tuple of arguments, and can access the
items accordingly:

• def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


Keyword Arguments

• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
• def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


Arbitrary Keyword Arguments, **kwargs
• If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the function
definition.
• This way the function will receive a dictionary of arguments, and can access
the items accordingly:
• def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")


Default Parameter Value
The following example shows how to use a default parameter value.
• If we call the function without argument, it uses the default value:
• def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Lambda
• 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
• x = lambda a : a + 10
print(x(5))
Map

• The map() function executes a specified function for each item in an


iterable.
• The item is sent to the function as a parameter.
• Syntax
• map(function, iterables)
• def myfunc(a, b):
return a + b

x = map(myfunc, ('apple', 'banana', 'cherry'),


('orange', 'lemon', 'pineapple'))
Module

• 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
• To create a module just save the code you want in a file with the file extension .py:
• Use a Module
• Now we can use the module we just created, by using the import statement:
• Import the module named mymodule, and call the greeting function:
• import mymodule
mymodule.greeting("Jonathan")

• person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
• Import the module named mymodule, and access the person1 dictionary:
• import mymodule
a = mymodule.person1["age"]
print(a)
Standard Module
• # importing module calc.py
• import calc

• print(calc.add(10, 2))

• # importing sqrt() and factorial from the module math


• from math import sqrt, factorial
• # if we simply do "import math", then
• # math.sqrt(16) and math.factorial() are required.
• print(sqrt(16))
• print(factorial(6))
Exception Handling
• When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
• These exceptions can be handled using the try statement:

• The try block lets you test a block of code for errors.

• The except block lets you handle the error.

• The else block lets you execute code when there is no error.

• The finally block lets you execute code, regardless of the result of the try- and
except blocks.
• The try block will generate an exception, because x is not defined:

• try:
• print(x)
• except:
• print("An exception occurred“)

• Since the try block raises an error, the except block will be executed.
• Without the try block, the program will crash and raise an error:
Multiple Exceptions
• You can define as many exception blocks as you want, e.g. if you want to execute a
special block of code for a special kind of error:
• Print one message if the try block raises a NameError and another for other errors:

• try:
• print(x)
• except NameError:
• print("Variable x is not defined")
• except:
• print("Something else went wrong")
Else
• You can use the else keyword to define a block of code to be executed if no errors
were raised:

• Example
• In this example, the try block does not generate any error:

• try:
• print("Hello")
• except:
• print("Something went wrong")
• else:
• print("Nothing went wrong")
Finally

• The finally block, if specified, will be executed regardless if the try block raises an
error or not.

• Example
• try:
• print(x)
• except:
• print("Something went wrong")
• finally:
• print("The 'try except' is finished")
File Handling

• File handling is an important part of any web 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.


• f = open("demofile.txt")
• 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
Reading Files

• To open the file, use the built-in open() function.


• The open() function returns a file object, which has a read() method for
reading the content of the file:
• f = open("demofile.txt", "r")
print(f.read())
• Read Only Parts of the File

• Return the 5 first characters of the file:


• f = open("demofile.txt", "r")
print(f.read(5))
Read Lines

• You can return one line by using the readline() method:


• f = open("demofile.txt", "r")
• print(f.readline())
Close Files

• It is a good practice to always close the file when you are done with it.
• Example
• Close the file when you are finish with it:
• f = open("demofile.txt", "r")
print(f.readline())
f.close()
Python File Write

• Write to an Existing File


• To write to an existing file, you must add a parameter to the open() function:

• "a" - Append - will append to the end of the file

• "w" - Write - will overwrite any existing content


• f = open("demofile2.txt", "a")
• f.write("Now the file has more content!")
• f.close()

• #open and read the file after the appending:


• f = open("demofile2.txt", "r")
• print(f.read())
Delete file

• To delete a file, you must import the OS module, and run its os.remove()
function:

• Example
• import os
os.remove("demofile.txt")
Handling file exceptions

• try:
• fh = open("testfile", "w")
• fh.write("This is my test file for exception handling!!")
• except IOError:
• print "Error: can\'t find file or read data"
• else:
• print "Written content in the file successfully"
• fh.close()
With statement

• In Python, with statement is used in exception handling to make the code cleaner
and much more readable.

• It simplifies the management of common resources like file streams. Observe the
following code example on how the use of with statement makes code cleaner.

• # using with statement


• with open('file_path', 'w') as file:
• file.write('hello world !')
Python Classes

• 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
• To create a class, use the keyword class:
• class MyClass:
x=5

• Create an object named p1, and print the value of x:


• p1 = MyClass()
print(p1.x)
The __init__() Function

• All classes have a function called __init__(), which is always executed when the
class is being initiated.

• Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created:

• Create a class named Person, use the __init__() function to assign values for name
and age:
• class Person:
• def __init__(self, name, age):
• self.name = name
• self.age = age

• p1 = Person("John", 36)

• print(p1.name)
• print(p1.age)
Self
• self – It is a keyword which points to the current passed instance. But it need not be passed every time
while calling an instance method.

• class Person:

• # init method or constructor
• def __init__(self, name):
• self.name = name

• # Sample Method
• def say_hi(self):
• print('Hello, my name is', self.name)

• p = Person('Nikhil')
• p.say_hi()
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 class named Person, with firstname and lastname properties, and a printname
method:

• class Person:
• def __init__(self, fname, lname):
• self.firstname = fname
• self.lastname = lname

• def printname(self):
• print(self.firstname, self.lastname)

• #Use the Person class to create an object, and then execute the printname method:

• x = Person("John", "Doe")
• x.printname()
Polymorphism

• The word "polymorphism" means "many forms", and in programming,


• it refers to methods/functions/operators with the same name that can be
executed on many objects or classes.
• Create a class called Vehicle and make Car, • print("Sail!")
Boat, Plane child classes of Vehicle:
• class Plane(Vehicle):
• class Vehicle:
• def move(self):
• def __init__(self, brand, model):
• print("Fly!")
• self.brand = brand
• self.model = model
• car1 = Car("Ford", "Mustang") #Create a
Car object
• def move(self): • boat1 = Boat("Ibiza", "Touring 20") #Create
• print("Move!")
a Boat object
• plane1 = Plane("Boeing", "747") #Create a
Plane object
• class Car(Vehicle):
• pass • for x in (car1, boat1, plane1):
• print(x.brand)
• class Boat(Vehicle): • print(x.model)
• def move(self):
Custom Exception

• A custom exception is an exception that is defined by the user. It is


used when the built-in exceptions are not sufficient to handle a
particular scenario in a program.
• Custom exceptions are created by subclassing the built-in Exception
class or any of its subclasses.
• By creating a custom exception, you can define your own error
message and customize the exception handling.
• class CustomException(Exception):
• def __init__(self, message):
• super().__init__(message)

• try:
• raise CustomException("This is a custom exception")
• except CustomException as e:
• print(e)
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__().
• mytuple= ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))
Generators

• A generator function in Python is defined like a normal function, but


whenever it needs to generate a value, it does so with the yield
keyword rather than return.
• If the body of a def contains yield, the function automatically becomes a
Python generator function.
• Python Generator functions return a generator object that is iterable, i.e.,
can be used as an Iterator.
• Generator objects are used either by calling the next method of the
generator object or using the generator object in a “for in” loop.
• # A Python program to demonstrate use of
• # generator object with next()

• # A generator function
• def simpleGeneratorFun():
• yield 1
• yield 2
• yield 3

• # x is a generator object
• x = simpleGeneratorFun()

• # Iterating over the generator object using next

• # In Python 3, __next__()
• print(next(x))
• print(next(x))
• print(next(x))
Data compression

• With the help of zlib.compress(s) method, we can get compress the bytes of
string by using zlib.compress(s) method.

• Syntax : zlib.compress(string)
• Return : Return compressed string.
• # import zlib and compress
• import zlib
• s = b'This is GFG author, and final year student.'
• print(len(s))

• # using zlib.compress(s) method


• t = zlib.compress(s)
• print(len(t))

• Output :
• 43
• 49
Specialized sorts

• sorted takes three parameters from which two are optional.


• Iterable: sequence (list, tuple, string) or collection (dictionary, set,
frozenset) or any other iterator that needs to be sorted.
• Key(optional): A function that would serve as a key or a basis of sort
comparison.
• Reverse(optional): If True, then the iterable would be sorted in
reverse (descending) order, by default it is set as False.
• Return: Returns a list with elements in sorted order.
• x = [2, 8, 1, 4, 6, 3, 7]

• print("Sorted List returned :", sorted(x))

• print("Reverse sort :", sorted(x, reverse=True))

• print("\nOriginal list not modified :", x)

• Sorted List returned : [1, 2, 3, 4, 6, 7, 8]


• Reverse sort : [8, 7, 6, 4, 3, 2,0 1]
• Original list not modified : [2, 8, 1, 4, 6, 3, 7]
Namedtuple

• In Python, NamedTuple is present inside the collections module. It


provides a way to create simple, lightweight data structures similar to a
class, but without the overhead of defining a full class.
• Like dictionaries, they contain keys that are hashed to a particular value.
• On the contrary, it supports both access from key-value and iteration,
the functionality that dictionaries lack.
• Python NamedTuple Syntax
• namedtuple(typename, field_names)

• typename – The name of the namedtuple.


• field_names – The list of attributes stored in the namedtuple.
• # Python code to demonstrate namedtuple()
• from collections import namedtuple

• # Declaring namedtuple()
• Student = namedtuple('Student', ['name', 'age', 'DOB'])

• # Adding values
• S = Student('Nandini', '19', '2541997')

• # Access using index


• print("The Student age using index is : ", end="")
• print(S[1])

• # Access using name


• print("The Student name using keyname is : ", end="")
• print(S.name)
Deque

• Deque (Doubly Ended Queue) in Python is implemented using


the module “collections“.
• Deque is preferred over a list in the cases where we need quicker
append and pop operations from both the ends of the container, as
deque provides an O(1) time complexity for append and pop
operations as compared to a list that provides O(n) time complexity.
• # importing "collections" for deque operations
• import collections

• # initializing deque
• de = collections.deque([1, 2, 3])
• print("deque: ", de)

• # using append() to insert element at right end


• # inserts 4 at the end of deque
• de.append(4)

• # printing modified deque


• print("\nThe deque after appending at right is : ")
• print(de)

• # using appendleft() to insert element at left end


• # inserts 6 at the beginning of deque
• de.appendleft(6)

• # printing modified deque


• print("\nThe deque after appending at left is : ")
• print(de)
Chainsmap
• Python contains a container called “ChainMap” which encapsulates
many dictionaries into one unit.
• ChainMap is member of module “collections“
• d1 = {'a': 1, 'b': 2}
• d2 = {'c': 3, 'd': 4}
• d3 = {'e': 5, 'f': 6}

• # Defining the chainmap
• c = ChainMap(d1, d2, d3)
• print(c)
Counter

• Counter is a sub-class that is used to count hashable objects. It


implicitly creates a hash table of an iterable when invoked.
• elements() is one of the functions of Counter class, when invoked on
the Counter object will return an itertool of all the known elements in
the Counter object.
• # import counter class from collections module
• from collections import Counter

• # Creation of a Counter Class object using


• # string as an iterable data container
• x = Counter("geeksforgeeks")
• print(x)
• # printing the elements of counter object
• for i in x.elements():
• print ( i, end = " ")
Ordered List

• An OrderedDict is a dictionary subclass that remembers the order that


keys were first inserted. The only difference between dict() and
OrderedDict() is that:
• OrderedDict preserves the order in which the keys are inserted.
• A regular dict doesn’t track the insertion order and iterating it gives the
values in an arbitrary order.
• By contrast, the order the items are inserted is remembered by OrderedDict.
• from collections import OrderedDict

• print("Before:\n")
• od = OrderedDict()
• od['a'] = 1
• od['b'] = 2
• od['c'] = 3
• od['d'] = 4
• for key, value in od.items():
• print(key, value)

• print("\nAfter:\n")
• od['c'] = 5
• for key, value in od.items():
• print(key, value)
Default Dict

• Dictionary in Python is an unordered collection of data values that


are used to store data values like a map.
• Unlike other Data Types that hold only single value as an element, the
Dictionary holds key-value pair.
• In Dictionary, the key must be unique and immutable
• from collections import defaultdict

• # Function to return a default


• # values for keys that is not
• # present
• def def_value():
• return "Not Present"

• # Defining the dict
• d = defaultdict(def_value)
• d["a"] = 1
• d["b"] = 2

• print(d["a"])
• print(d["b"])
• print(d["c"])
User Dict

• Python supports a dictionary like a container called UserDict present


in the collections module.
• This class acts as a wrapper class around the dictionary objects.
• This class is useful when one wants to create a dictionary of their own
with some modified functionality or with some new functionality.
• It can be considered as a way of adding new behaviors to the
dictionary.
• from collections import UserDict

• d = {'a':1,
• 'b': 2,
• 'c': 3}

• # Creating an UserDict
• userD = UserDict(d)
• print(userD.data)

• # Creating an empty UserDict


• userD = UserDict()
• print(userD.data)
Userlist

• Python supports a List like a container called UserList present in


the collections module.
• This class acts as a wrapper class around the List objects
• .This class is useful when one wants to create a list of their own with
some modified functionality or with some new functionality.
• It can be considered as a way of adding new behaviors for the list.
• from collections import UserList

• L = [1, 2, 3, 4]

• # Creating a userlist
• userL = UserList(L)
• print(userL.data)

• # Creating empty userlist


• userL = UserList()
• print(userL.data)
Userstring

• Python supports a String like a container called UserString present in


the collections module.
• This class acts as a wrapper class around the string objects.
• This class is useful when one wants to create a string of their own with
some modified functionality or with some new functionality.
• It can be considered as a way of adding new behaviors for the string.
• from collections import UserString

• d = 12344

• # Creating an UserDict
• userS = UserString(d)
• print(userS.data)

• # Creating an empty UserDict


• userS = UserString("")
• print(userS.data)
GUI in python

• Python offers multiple options for developing GUI (Graphical User


Interface). Out of all the GUI methods, tkinter is the most commonly used
method. It is a standard Python interface to the Tk GUI toolkit shipped
with Python. Python with tkinter is the fastest and easiest way to create
the GUI applications. Creating a GUI using tkinter is an easy task.
To create a tkinter app:
Importing the module – tkinter
Create the main window (container)
Add any number of widgets to the main window
Apply the event Trigger on the widgets.
There are two main methods used which the user needs to remember while
creating the Python application with GUI.

• Tk(screenName=None, baseName=None, className=’Tk’, useTk=1):


• To create a main window, tkinter offers a method
• To change the name of the window, you can change the className to the
desired one.
• The basic code used to create the main window of the application is:

• m=tkinter.Tk() where m is the name of the main window object


• mainloop():
• There is a method known by the name mainloop() is used when your
application is ready to run.
• mainloop() is an infinite loop used to run the application, wait for an event
to occur and process the event as long as the window is not closed.
• m.mainloop()
Geometry manager classes

• There are mainly three geometry manager classes class.

• pack() method:It organizes the widgets in blocks before placing in the parent
widget.
• grid() method:It organizes the widgets in grid (table-like structure) before
placing in the parent widget.
• place() method:It organizes the widgets by placing them on specific positions
directed by the programmer.
• Button:To add a button in your application, this widget is used.
• The general syntax is:
• w=Button(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the Buttons. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

• activebackground: to set the background color when button is under the cursor.
• activeforeground: to set the foreground color when button is under the cursor.
• bg: to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the button.
• width: to set the width of the button.
• height: to set the height of the button.
Button

• import tkinter as tk
• r = tk.Tk()
• r.title('Counting Seconds')
• button = tk.Button(r, text='Stop', width=25, command=r.destroy)
• button.pack()
• r.mainloop()
Canvas
• It is used to draw pictures and other complex layout like graphics, text and widgets.
• The general syntax is:
• w = Canvas(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used in the canvas.
• highlightcolor: to set the color shown in the focus highlight.
• width: to set the width of the widget.
• height: to set the height of the widget.
Canvas
• from tkinter import *
• master = Tk()
• w = Canvas(master, width=40, height=60)
• w.pack()
• canvas_height=20
• canvas_width=200
• y = int(canvas_height / 2)
• w.create_line(0, y, canvas_width, y )
• mainloop()
Check button
• To select any number of options by displaying a number of options to a user as
toggle buttons. The general syntax is:
• w = CheckButton(master, option=value)
• There are number of options which are used to change the format of this
widget. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
• Title: To set the title of the widget.
• activebackground: to set the background color when widget is under the cursor.
• activeforeground: to set the foreground color when widget is under the cursor.
• bg: to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the widget.
Checkbutton

• from tkinter import *


• master = Tk()
• var1 = IntVar()
• Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)
• var2 = IntVar()
• Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)
• mainloop()
Entry
• It is used to input the single line text entry from the user.. For multi-line text input, Text
widget is used.
• The general syntax is:
• w=Entry(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• command: to call a function.
• highlightcolor: to set the color shown in the focus highlight.
• width: to set the width of the button.
• height: to set the height of the button.
Entry
• from tkinter import *
• master = Tk()
• Label(master, text='First Name').grid(row=0)
• Label(master, text='Last Name').grid(row=1)
• e1 = Entry(master)
• e2 = Entry(master)
• e1.grid(row=0, column=1)
• e2.grid(row=1, column=1)
• mainloop()
Frame
• It acts as a container to hold the widgets. It is used for grouping and organizing the
widgets. The general syntax is:
• w = Frame(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• highlightcolor: To set the color of the focus highlight when widget has to be focused.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• width: to set the width of the widget.
• height: to set the height of the widget.
• from tkinter import *
Frame
• root = Tk()
• frame = Frame(root)
• frame.pack()
• bottomframe = Frame(root)
• bottomframe.pack( side = BOTTOM )
• redbutton = Button(frame, text = 'Red', fg ='red')
• redbutton.pack( side = LEFT)
• greenbutton = Button(frame, text = 'Brown', fg='brown')
• greenbutton.pack( side = LEFT )
• bluebutton = Button(frame, text ='Blue', fg ='blue')
• bluebutton.pack( side = LEFT )
• blackbutton = Button(bottomframe, text ='Black', fg ='black')
• blackbutton.pack( side = BOTTOM)
• root.mainloop()
Label
• It refers to the display box where you can put any text or image which can be updated
any time as per the code.
• The general syntax is:
• w=Label(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• bg: to set the normal background color.
• bg to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the button.
• width: to set the width of the button.
• height” to set the height of the button.
Label

• from tkinter import *


• root = Tk()
• w = Label(root, text='GeeksForGeeks.org!')
• w.pack()
• root.mainloop()
List box
• It offers a list to the user from which the user can accept any number of options.
• The general syntax is:
• w = Listbox(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• highlightcolor: To set the color of the focus highlight when widget has to be focused.
• bg: to set the normal background color.
• bd: to set the border width in pixels.
• font: to set the font on the button label.
• image: to set the image on the widget.
• width: to set the width of the widget.
• height: to set the height of the widget.
List box
• from tkinter import *

• top = Tk()
• Lb = Listbox(top)
• Lb.insert(1, 'Python')
• Lb.insert(2, 'Java')
• Lb.insert(3, 'C++')
• Lb.insert(4, 'Any other')
• Lb.pack()
• top.mainloop()
Menu button
It is a part of top-down menu which stays on the window all the time. Every menubutton has its
own functionality. The general syntax is:
• w = MenuButton(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• activebackground: To set the background when mouse is over the widget.
• activeforeground: To set the foreground when mouse is over the widget.
• bg: to set the normal background color.
• bd: to set the size of border around the indicator.
• cursor: To appear the cursor when the mouse over the menubutton.
• image: to set the image on the widget.
• width: to set the width of the widget.
• height: to set the height of the widget.
• highlightcolor: To set the color of the focus highlight when widget has to be focused.
Menu button
• from tkinter import *

• top = Tk()
• mb = Menubutton ( top, text = "GfG")
• mb.grid()
• mb.menu = Menu ( mb, tearoff = 0 )
• mb["menu"] = mb.menu
• cVar = IntVar()
• aVar = IntVar()
• mb.menu.add_checkbutton ( label ='Contact', variable = cVar )
• mb.menu.add_checkbutton ( label = 'About', variable = aVar )
• mb.pack()
• top.mainloop()
Menu
• It is used to create all kinds of menus used by the application.
• The general syntax is:
• w = Menu(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of this widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• title: To set the title of the widget.
• activebackground: to set the background color when widget is under the cursor.
• activeforeground: to set the foreground color when widget is under the cursor.
• bg: to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the widget.
Menu
• from tkinter import *

• root = Tk()
• menu = Menu(root)
• root.config(menu=menu)
• filemenu = Menu(menu)
• menu.add_cascade(label='File', menu=filemenu)
• filemenu.add_command(label='New')
• filemenu.add_command(label='Open...')
• filemenu.add_separator()
• filemenu.add_command(label='Exit', command=root.quit)
• helpmenu = Menu(menu)
• menu.add_cascade(label='Help', menu=helpmenu)
• helpmenu.add_command(label='About')
• mainloop()
Message
• It refers to the multi-line and non-editable text. It works same as that of Label.
• The general syntax is:w = Message(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
• bd: to set the border around the indicator.
• bg: to set the normal background color.
• font: to set the font on the button label.
• image: to set the image on the widget.
• width: to set the width of the widget.
• height: to set the height of the widget.
Message

• from tkinter import *


• main = Tk()
• ourMessage ='This is our Message'
• messageVar = Message(main, text = ourMessage)
• messageVar.config(bg='lightgreen')
• messageVar.pack( )
• main.mainloop( )
Radio button
• It is used to offer multi-choice option to the user. It offers several options to the user and
the user has to choose one option.
• The general syntax is:w = RadioButton(master, option=value)
• There are number of options which are used to change the format of this widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• activebackground: to set the background color when widget is under the cursor.
• activeforeground: to set the foreground color when widget is under the cursor.
• bg: to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the widget.
• width: to set the width of the label in characters.
• height: to set the height of the label in characters.
Radio button

• from tkinter import *


• root = Tk()
• v = IntVar()
• Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)
• Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)
• mainloop()
Scale
• It is used to provide a graphical slider that allows to select any value from that scale.
The general syntax is:
• w = Scale(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• cursor: To change the cursor pattern when the mouse is over the widget.
• activebackground: To set the background of the widget when mouse is over the widget.
• bg: to set the normal background color.
• orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
• from_: To set the value of one end of the scale range.
• to: To set the value of the other end of the scale range.
• image: to set the image on the widget.
• width: to set the width of the widget.
Scale

• from tkinter import *


• master = Tk()
• w = Scale(master, from_=0, to=42)
• w.pack()
• w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
• w.pack()
• mainloop()
Scroll bar
• Scrollbar: It refers to the slide controller which will be used to implement listed widgets.
• The general syntax is:
• w = Scrollbar(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• width: to set the width of the widget.
• activebackground: To set the background when mouse is over the widget.
• bg: to set the normal background color.
• bd: to set the size of border around the indicator.
• cursor: To appear the cursor when the mouse over the menubutton
Scroll bar
• from tkinter import *
• root = Tk()
• scrollbar = Scrollbar(root)
• scrollbar.pack( side = RIGHT, fill = Y )
• mylist = Listbox(root, yscrollcommand = scrollbar.set )
• for line in range(100):
• mylist.insert(END, 'This is line number' + str(line))
• mylist.pack( side = LEFT, fill = BOTH )
• scrollbar.config( command = mylist.yview )
• mainloop()
Text
• Text: To edit a multi-line text and format the way it has to be displayed.
• The general syntax is:
• w =Text(master, option=value)
• There are number of options which are used to change the format of the text. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.
• highlightcolor: To set the color of the focus highlight when widget has to be focused.
• insertbackground: To set the background of the widget.
• bg: to set the normal background color.
• font: to set the font on the button label.
• image: to set the image on the widget.
• width: to set the width of the widget.
• height: to set the height of the widget.
Text

• from tkinter import *


• root = Tk()
• T = Text(root, height=2, width=30)
• T.pack()
• T.insert(END, 'GeeksforGeeks\nBEST WEBSITE\n')
• mainloop()
Top level
• TopLevel: This widget is directly controlled by the window manager. It don’t
need any parent window to work on.The general syntax is:
• w = TopLevel(master, option=value)
• There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.

• bg: to set the normal background color.


• bd: to set the size of border around the indicator.
• cursor: To appear the cursor when the mouse over the menubutton.
• width: to set the width of the widget.
• height: to set the height of the widget.
Top level

• from tkinter import *


• root = Tk()
• root.title('GfG')
• top = Toplevel()
• top.title('Python')
• top.mainloop()
Spin box
• It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of
numbers.The general syntax is:
• w = SpinBox(master, option=value)
• There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• bg: to set the normal background color.
• bd: to set the size of border around the indicator.
• cursor: To appear the cursor when the mouse over the menubutton.
• command: To call a function.
• width: to set the width of the widget.
• activebackground: To set the background when mouse is over the widget.
• disabledbackground: To disable the background when mouse is over the widget.
• from_: To set the value of one end of the range.
• to: To set the value of the other end of the range.
Spin box

• from tkinter import *


• master = Tk()
• w = Spinbox(master, from_ = 0, to = 10)
• w.pack()
• mainloop()
Panned window
• It is a container widget which is used to handle number of panes arranged in it.
The general syntax is:
• w = PannedWindow(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
• bg: to set the normal background color.
• bd: to set the size of border around the indicator.
• cursor: To appear the cursor when the mouse over the menubutton.
• width: to set the width of the widget.
• height: to set the height of the widget.
Panned window
• from tkinter import *
• m1 = PanedWindow()
• m1.pack(fill = BOTH, expand = 1)
• left = Entry(m1, bd = 5)
• m1.add(left)
• m2 = PanedWindow(m1, orient = VERTICAL)
• m1.add(m2)
• top = Scale( m2, orient = HORIZONTAL)
• m2.add(top)
• mainloop()
Python SQL

• Python can be used in database applications.


• One of the most popular databases is MySQL.
• You can download a MySQL database
at https://www.mysql.com/downloads/.
• We recommend that you use PIP to install "MySQL
Connector".
• Pip install mysql-connector
mysql

• import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

print(mydb)
• Creating a Database
• To create a database in MySQL, use the "CREATE DATABASE"
statement:
• mycursor.execute("CREATE DATABASE mydatabase“)

• You can check if a database exist by listing all databases in


your system by using the "SHOW DATABASES" statement:
• mycursor.execute("SHOW DATABASES")

for x in mycursor:
print(x)
Creating a Table
• To create a table in MySQL, use the "CREATE TABLE"
statement.
• Make sure you define the name of the database when you
create the connection
• mycursor.execute("CREATETABLE customers (name
VARCHAR(255), address VARCHAR(255))")
• import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW TABLES")

for x in mycursor:
print(x)
• Insert
• sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)

• Update
• mycursor = mydb.cursor()

sql = "UPDATE customers SET address = 'Canyon 123' WHERE


address = 'Valley 345'"

mycursor.execute(sql)

mydb.commit()
• sql = "DELETE FROM customers WHERE address = 'Mountain
21'"

mycursor.execute(sql)

mydb.commit()
Network Programming
• Python plays an essential role in network programming.
• The standard library of Python has full support for network protocols,
encoding, and decoding of data and other networking concepts, and it
is simpler to write network programs in Python than that of C++.

Low-Level Programming using sockets


• Data encoding
• HTTP and web-programming
• High-Level client modules
• Basic networking terms and their concepts etc.
Socket
• A socket is the end-point in a flow of communication between two programs or
communication channels operating over a network.
• They are created using a set of programming requests called socket API
(Application Programming Interface). Python's socket library offers classes for
handling common transports as a generic interface.
• Sockets use protocols for determining the connection type for port-to-port
communication between client and server machines. The protocols are used for:
• Domain Name Servers (DNS)
• IP addressing
• E-mail
• FTP (File Transfer Protocol) etc...
• s = socket.socket (socket_family, socket_type, protocol=0)
• Here is the description of the parameters −

• socket_family − This is either AF_UNIX or AF_INET, as


explained earlier.

• socket_type − This is either SOCK_STREAM or


SOCK_DGRAM.

• protocol − This is usually left out, defaulting to 0.


• Server Socket Methods
• s.bind()-This method binds address (hostname, port number pair)
to socket.
• s.listen()-This method sets up and start TCP listener.
• s.accept()-This passively accept TCP client connection, waiting
until connection arrives (blocking).

• Client Socket Methods


• s.connect()-This method actively initiates TCP server connection.
General Socket Methods

• s.recv()-This method receives TCP message


• s.send()-This method transmits TCP message
• s.recvfrom()-This method receives UDP message
• s.sendto()-This method transmits UDP message
• s.close()-This method closes socket
• socket.gethostname()-Returns the hostname.
• Server
• import socket # Import socket module

• s = socket.socket() # Create a socket object


• host = socket.gethostname() # Get local machine name
• port = 12345 # Reserve a port for your service.
• s.bind((host, port)) # Bind to the port

• s.listen(5) # Now wait for client connection.


• while True:
• c, addr = s.accept() # Establish connection with client.
• print 'Got connection from', addr
• c.send('Thank you for connecting')
• c.close() # Close the connection
Client

• import socket # Import socket module

• s = socket.socket() # Create a socket object


• host = socket.gethostname() # Get local machine name
• port = 12345 # Reserve a port for your service.

• s.connect((host, port))
• print s.recv(1024)
• s.close() # Close the socket when done
SMTP
• Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending
e-mail and routing e-mail between mail servers.

• Python provides smtplib module, which defines an SMTP client session


object that can be used to send mail to any Internet machine with an
SMTPimport smtplib.

• import smtplib
• smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
• host − This is the host running your SMTP server. You can specify IP address
of the host or a domain name like tutorialspoint.com. This is optional
argument.

• port − If you are providing host argument, then you need to specify a port,
where SMTP server is listening. Usually this port would be 25.

• local_hostname − If your SMTP server is running on your local machine,


then you can specify just localhost as of this option.
• An SMTP object has an instance method called sendmail, which is typically
used to do the work of mailing a message. It takes three parameters −

• The sender − A string with the address of the sender.


• The receivers − A list of strings, one for each recipient.
• The message − A message as a string formatted as specified in the various
RFCs.
• import smtplib
• sender = 'from@fromdomain.com'
• receivers = ['to@todomain.com']

• message = """From: From Person <from@fromdomain.com>


• To: To Person <to@todomain.com>
• Subject: SMTP e-mail test
• This is a test e-mail message.
• """
• try:
• smtpObj = smtplib.SMTP('localhost')
• smtpObj.sendmail(sender, receivers, message)
• print "Successfully sent email"
• except SMTPException:
• print "Error: unable to send email"
Date

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

Import the datetime module and display the current date:


• import datetime
• x = datetime.datetime.now()
• print(x)
Strftime() method

• The datetime object has a method for formatting date objects into readable
strings.
• The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string

• import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))
Functions

• The filter() function returns an iterator where the items are filtered through
a function to test if the item is accepted or not.

• Syntax
• filter(function, iterable)
• ages = [5, 12, 17, 18, 24, 32]

def myFunc(x):
if x < 18:
return False
else:
return True

adults = filter(myFunc, ages)

for x in adults:
print(x)
Reduce
• The reduce(fun,seq) function is used to apply a particular function passed in its
argument to all of the list elements mentioned in the sequence passed along.This
function is defined in “functools” module.

• Working :

• At first step, first two elements of sequence are picked and the result is obtained.

• Next step is to apply the same function to the previously attained result and the
number just succeeding the second element and the result is again stored.

• This process continues till no more elements are left in the container.

• The final returned result is returned and printed on console.


• import functools

• # initializing list
• lis = [1, 3, 5, 6, 2]

• # using reduce to compute sum of list


• print("The sum of the list elements is : ", end="")
• print(functools.reduce(lambda a, b: a+b, lis))

• # using reduce to compute maximum element from list


• print("The maximum element of the list is : ", end="")
• print(functools.reduce(lambda a, b: a if a > b else b, lis))
Decorators

• Decorators are a very powerful and useful tool in Python since it allows
programmers to modify the behaviour of a function or class.

• Decorators allow us to wrap another function in order to extend the


behaviour of the wrapped function, without permanently modifying it
Decorators

• In Python, a decorator is a design pattern that allows you to modify the


functionality of a function by wrapping it in another function.
• The outer function is called the decorator, which takes the original
function as an argument and returns a modified version of it.
• Basically, a decorator takes in a function, adds some functionality and
returns it.
• def make_pretty(func):
• def inner():
• print("I got decorated")
• func()
• return inner
• @make_pretty
• def ordinary():
• print("I am ordinary")
Frozenset

• The frozenset() function returns an unchangeable frozenset object (which is


like a set object, only unchangeable).

• Syntax
• frozenset(iterable)
frozenset

• This will cause an error:


• mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
x[1] = "strawberry"
Split

• The split() method splits a string into a list.

• You can specify the separator, default separator is any whitespace


• Syntax
• string.split(separator, maxsplit)
• txt = "hello, my name is Peter, I am 26 years old"

x = txt.split(", ")

print(x)

• Output:['hello', 'my name is Peter', 'I am 26 years


old']
Reg Ex
• 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.

• Python has a built-in package called re, which can be used to work with Regular
Expressions.

• Import the re module:

• import re
• import re
• #Check if the string starts with "The" and ends with "Spain":
• txt = "The rain in Spain"
• x = re.search("^The.*Spain$", txt)

• if x:
• print("YES! We have a match!")
• else:
• print("No match")
Find_all

• The findall() function returns a list containing all matches.


• Example
• Print a list of all matches:
• import re
• txt = "The rain in Spain"
• x = re.findall("ai", txt)
• Print(x)
• Output:['ai', 'ai']
Match

• A Match Object is an object containing information about the


search and the result
• Print the position (start- and end-position) of the first match
occurrence.
• The regular expression looks for any words that starts with
an upper case "S":
• import re

txt = "The rain in Spain"


x = re.search(r"\bS\w+", txt)
print(x.span())
• The Match object has properties and methods used to retrieve
information about the search, and the result:

• .span() returns a tuple containing the start-, and end positions of the match.
• .string returns the string passed into the function
• .group() returns the part of the string where there was a match
Sub function
• The sub() function replaces the matches with the text of your choice:
• Eg:Replace every white-space character with the number 9:
• import re

• txt = "The rain in Spain"


• x = re.sub("\s", "9", txt)
• Print(x)
• Output:The9rain9in9Spain
• The search() Function
• The search() function searches the string for a match, and returns a Match
object if there is a match.
If there is more than one match, only the first occurrence of the match will be
returned:
• Example-Search for the first white-space character in the string:
• import re

• txt = "The rain in Spain"


• x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
Output:The first white-space character is located in
position: 3
Threads
• A thread is a separate flow of execution. This means that your program will have two things
happening at once. But for most Python 3 implementations the different threads do not actually
execute at the same time: they merely appear to.

• It’s tempting to think of threading as having two (or more) different processors running on
your program, each one doing an independent task at the same time. That’s almost right. The
threads may be running on different processors, but they will only be running one at a time.

• Getting multiple tasks running simultaneously requires a non-standard implementation of


Python, writing some of your code in a different language, or using multiprocessing which
comes with some extra overhead.
• Step 1: Import Module

• First, import the threading module.

• import threading

• Step 2: Create a Thread

• To create a new thread, we create an object of the Thread class. It takes the ‘target’ and ‘args’
as the parameters. The target is the function to be executed by the thread whereas the args is
the arguments to be passed to the target function.

• t1 = threading.Thread(target, args)
• t2 = threading.Thread(target, args)
• Step 3: Start a Thread

• To start a thread, we use the start() method of the Thread class.

• t1.start()
• t2.start()

• Step 4: End the thread Execution

• Once the threads start, the current program (you can think of it like a main thread) also keeps on
executing. In order to stop the execution of the current program until a thread is complete, we use the
join() method.

• t1.join()
• t2.join()
• # Python program to illustrate the concept • t1 = threading.Thread(target=print_square, args=(10,))
• # of threading • t2 = threading.Thread(target=print_cube, args=(10,))
• # importing the threading module
• import threading • # starting thread 1
• t1.start()
• # starting thread 2
• def print_cube(num): • t2.start()
• # function to print cube of given num
• print("Cube: {}" .format(num * num * num)) • # wait until thread 1 is completely executed
• t1.join()
• # wait until thread 2 is completely executed
• def print_square(num): • t2.join()
• # function to print square of given num
• print("Square: {}" .format(num * num)) • # both threads completely executed
• print("Done!")

• if __name__ =="__main__":
• # creating thread
Synchronization
• The threading module provided with Python includes a simple-to-implement locking mechanism
that allows you to synchronize threads. A new lock is created by calling the Lock() method, which
returns the new lock.

• The acquire(blocking) method of the new lock object is used to force threads to run synchronously.
The optional blocking parameter enables you to control whether the thread waits to acquire the
lock.

• If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired
and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock
to be released.

• The release() method of the new lock object is used to release the lock when it is no longer
required.
• import threading • print "%s: %s" % (threadName,
• import time
time.ctime(time.time()))

• class myThread (threading.Thread):


• counter -= 1

• def __init__(self, threadID, name, counter):


• threadLock = threading.Lock()

• threading.Thread.__init__(self)
• threads = []

• self.threadID = threadID
• # Create new threads

• self.name = name
• thread1 = myThread(1, "Thread-1", 1)

• self.counter = counter
• thread2 = myThread(2, "Thread-2", 2)

• def run(self):
• # Start new Threads

• print "Starting " + self.name


• thread1.start()

• # Get lock to synchronize threads


• thread2.start()

• threadLock.acquire()
• # Add threads to thread list

• print_time(self.name, self.counter, 3)
• threads.append(thread1)

• # Free lock to release next thread


• threads.append(thread2)

• threadLock.release()
• # Wait for all threads to complete

• def print_time(threadName, delay, counter):


• for t in threads:

• while counter:
• t.join()

• time.sleep(delay)
• print "Exiting Main Thread"
Thread life cycle
Use cases
• The main advantage of Python threading is that it allows programs to run
simultaneously. Also, when a program is performing multiple tasks independently, this
can be made easier by threading. It also uses the system resources more efficiently,
which increases efficiency, and provides a smoother user experience.

• The most typical use cases of Python threading are:


• I/O-bound programs: The I/O-bound program is any application that reads and writes
data from the input-output system and waits for data from it. If tasks wait too much
from external resources, they are perfect candidates for threading. Examples of these
tasks might be reading/writing files, network interactions, or user input.
• GUI applications: When the user is using Graphical User Interface (GUI), it must
remain responsive (GUI, not the user) despite the tasks being performed in the
background. This is achieved by threading in Python.
• Simulations and modeling: Python threading is typically used in simulations where
several entities are acting independently.
API
• An API, or Application Programming Interface, is a server that you can use to
retrieve and send data to using code. APIs are most commonly used to retrieve
data, and that will be the focus of this beginner tutorial.

• When we want to receive data from an API, we need to make a request.


Requests are used all over the web. For instance, when you visited this blog
post, your web browser made a request to the Dataquest web server, which
responded with the content of this web page.
API Status Codes
• Status codes are returned with every request that is made to a web server. Status codes indicate
information about what happened with a request.

• 200: Everything went okay, and the result has been returned (if any).
• 301: The server is redirecting you to a different endpoint. This can happen when a company
switches domain names, or an endpoint name is changed.
• 400: The server thinks you made a bad request. This can happen when you don’t send along the
right data, among other things.
• 401: The server thinks you’re not authenticated. Many APIs require login ccredentials, so this
happens when you don’t send the right credentials to access an API.
• 403: The resource you’re trying to access is forbidden: you don’t have the right perlessons to see
it.
• 404: The resource you tried to access wasn’t found on the server.
• 503: The server is not ready to handle the request.

You might also like