Python
Python
By Malathi.K
Python
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• 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 downloads
• https://www.python.org/downloads/
Print statement
• print("Hello, World!")
• 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
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
• print("Tuple slicing")
• print(T[slice_obj1])
• print(T[slice_obj2])
String
• # Output
• print("Hello, " + name)
• print(type(name))
Simple Output formating
• 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))
+ 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
== Equal x == y
!= Not equal x != y
in Returns True if a x in y
sequence with the
specified value is
present in the object
• 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 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
my_function()
Variable arguments
my_function("Emil")
my_function("Tobias")
my_function("Linus")
2 Argumnets
• 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])
• 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("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
• 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))
• The try block lets you test a block of code for errors.
• 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
• "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
• 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
• 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.
• 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
• try:
• raise CustomException("This is a custom exception")
• except CustomException as e:
• print(e)
Iterators
• An iterator is an object that can be iterated upon, meaning that you can
traverse through all the values.
print(next(myit))
print(next(myit))
print(next(myit))
Generators
• # A generator function
• def simpleGeneratorFun():
• yield 1
• yield 2
• yield 3
• # x is a generator object
• x = simpleGeneratorFun()
• # 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))
• Output :
• 43
• 49
Specialized sorts
• # Declaring namedtuple()
• Student = namedtuple('Student', ['name', 'age', 'DOB'])
• # Adding values
• S = Student('Nandini', '19', '2541997')
• # initializing deque
• de = collections.deque([1, 2, 3])
• print("deque: ", de)
• 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
• print(d["a"])
• print(d["b"])
• print(d["c"])
User Dict
• d = {'a':1,
• 'b': 2,
• 'c': 3}
• # Creating an UserDict
• userD = UserDict(d)
• print(userD.data)
• L = [1, 2, 3, 4]
• # Creating a userlist
• userL = UserList(L)
• print(userL.data)
• d = 12344
• # Creating an UserDict
• userS = UserString(d)
• print(userS.data)
• 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
• 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
• 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“)
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()
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++.
• 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.
• 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.
• 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.
• 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
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.
• # initializing list
• lis = [1, 3, 5, 6, 2]
• Decorators are a very powerful and useful tool in Python since it allows
programmers to modify the behaviour of a function or class.
• Syntax
• frozenset(iterable)
frozenset
x = txt.split(", ")
print(x)
• 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 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
• .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
• 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.
• import threading
• 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
• t1.start()
• t2.start()
• 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()))
• 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
• threadLock.acquire()
• # Add threads to thread list
• print_time(self.name, self.counter, 3)
• threads.append(thread1)
• threadLock.release()
• # Wait for all threads to complete
• 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.
• 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.