You are on page 1of 69

Python Programming

concepts
Subject Code: 8FC22

B. Tech-ECE
II Year II Semester
Dr G. Prasad Acharya,
Associate Professor & Associate HoD, ECE Dept,
Sreenidhi Institute of Science and Technology, Hyderabad.
Course Objectives:-
 Use Python interactively, execute a Python script at the shell
prompt, use Python types, expressions, and None, use string
literals and string type, use Python statements (if...elif..else,
for, pass, continue, . . . ), understand the difference between
expressions and statements, understand assignment semantics,
write and call a simple function., utilize high-level data types
such as lists and dictionaries, understand the difference
between mutable and immutable types, write a simple class and
access methods and attributes, import and utilize a module,
read from and write to a text file.
 Learn the basic concepts and the ability to understand
and design algorithms using greedy strategy, divide and
conquer approach and dynamic programming.
Course Outcomes:-
 CO1: Gains exposure towards Python versions and their specifications and
build programs
 using primitive data types.
 CO2: Write applications that include functions, modules, packages along
with respective exceptional handling mechanism.
 CO3: Writes applications using features of Python and applications using
Files.
 CO4: Hands on exposure on NumPy/Tkinter/Plotpy modules
 CO5: Analyze worst-case running times of algorithms using asymptotic
analysis. Describe the divide-and-conquer paradigm and explain when an
algorithmic design situation calls for it. Recite algorithms that employ this
paradigm. Synthesize divide and-conquer algorithms.
 CO6: Describe the dynamic-programming paradigm and the greedy paradigm
and explain when an algorithmic design situation calls for it. Synthesize
dynamic programming and greedy algorithms and analyze them.
Detailed syllabus:-
 UNIT I: Introduction to Python:
History, Features, Modes of Execution, Setting up path, working with Python Basic
Syntax, Variable and Data Types, Operators. Conditional Statements (If, If- else, Nested
if-else) Looping (for, While Nested loops) Control Statements (Break, Continue, Pass).
Functions: Defining a function, calling a function, Types of functions, Function
Arguments
 UNIT II: String Manipulation:
Accessing Strings, Basic Operations, String slices, Lists: Accessing list, Operations,
Tuple: Accessing tuples, Operations, Dictionaries: Accessing values in dictionaries,
Modules: Importing module, Math module, Random module, Packages Exception
Handling:Exception, Exception Handling, Except clause, Try? Finally clause User
Defined Exceptions
 UNIT III: Python- OOPs concept:
Class and object, Attributes, Inheritance, Overloading Overriding, Data hiding, Regular
expressions: Match function, Search function, Matching VS Searching, Modifiers
Patterns.
 UNIT IV: Case Study with NumPy/PlotPy/SciPy/GUI Programming, Introduction,
Tkinter programming, Tkinter widgets
Detailed syllabus:-
 UNIT V:
Introduction: Algorithm,  Performance Analysis-Space complexity, Time complexity,
Asymptotic Notation- Big oh notation, Omega notation, Theta notations, Divide and
conquer: General method, applications-Binary search, Merge sort, Applications:
Implementing Algorithms ,performance analysis and sorting techniques using Python
 UNIT VI:
Greedy method: General method, applications- 0/1 knapsack problem, Minimum cost
spanning trees. Dynamic Programming: General method, applications- Travelling sales
person problem, Reliability design. Applications: Implementing some Greedy method and
Dynamic programming techniques using Python
 Text books:
 1. Think Python: How to Think Like a Computer Scientist Allen B. Downey, O'Relly
publications.
 2. Learning with Python by Jeffrey Elkner, Chris Meyers Allen Downey, Dreamtech Press.
 3. Fundamentals of Computer Algorithms, Ellis Horowitz,Satraj Sahni and
Rajasekharam,Galgotia publications pvt. Ltd.
Unit-II
o String Manipulation: Accessing Strings, Basic Operations, String slices,
o Lists: Accessing list, Operations,
o Tuple: Accessing tuples, Operations,
o Dictionaries: Accessing values in dictionaries,
o Modules: Importing module, Math module, Random module, Packages
o Exception Handling:Exception, Exception Handling, Except clause, Try?
Finally clause User Defined Exceptions
String
 Strings in python are surrounded by either single
quotation marks, or double quotation marks.
 'hello' is the same as "hello“
 print() function is used to display a string
 Example
 print("Hello")
 A multiline string to a variable by using three quotes:
 a=‘’’hello!
how
are Python does not have a character data type, a single
you’’’ character is simply a string with a length of 1.
 print(a)
Strings are Arrays
 Square brackets can be used to access elements of
the string
 a="Hello, World!"
 print(a[1]) -- e

 Looping Through a String


 for x in "banana":
  print(x)
  len() function computes the length of the string
 a = "Hello, World!"
print(len(a)) -- 13
Strings contd…
 Check String: To check if a certain phrase or character is present in
a string, we can use the keyword in
 txt = "The best things in life are free!"
print("free" in txt)  True
 Check if NOT: Check if "expensive" is NOT present
 txt="The best things in life are free!"
 print("expensive“ not in txt)  True
 Accessing characters in Python String
 Individual characters of a String can be accessed by using the method of
Indexing (like in lists). 
 Indexing allows negative address references to access characters from the back
of the String, e.g. -1 refers to the last character, -2 refers to the second last
character, and so on.
 While accessing an index out of the range will cause an IndexError. 
 Only Integers are allowed to be passed as an index, float or other types that will
cause a TypeError.
Basic String Operations
 Python provides many built-in string operations that can be
used to manipulate and process strings.
 Here are some common operations:
o Concatenation: To concatenate two strings, we
use the + operator. Here's an example:
string1 = "Hello"
string2 = "World"
concatenated_string = string1 + " " + string2
print(concatenated_string)

# Output: Hello World


o Repetition: We can repeat a string multiple times
using the * operator. Here's an example:
string = "Hello“
repeated_string = string * 3
print(repeated_string) # Output: HelloHelloHello

o Membership: We can check if a character or


substring is present in a string using the in
keyword. Here's an example:
string = "Hello World“
print('H' in string) # Output: True
print('Hello' in string) # Output: True
print('Hi' in string) # Output: False
print('Hi' not in string) # Output: True
Reversing a string
 We can Reverse a string by writing [::-1]
 Example:
 gfg = "geeksforgeeks"
 print(gfg[::-1])
 We can also reverse a string by using built-in join
 and reversed function.
 gfg="geeksforgeeks"
 gfg = "".join(reversed(gfg))
 print(gfg)  skeegrofskeeg
String Slicing
 To access a range of characters in the String, the
method of slicing is used.
 Slicing in a String is done by using a Slicing operator
(colon).
 String1 = "GeeksForGeeks"
 print("Initial String: ")
 print(String1)
 print("Slicing characters from 3-12: ")
 print(String1[3:12])
 print("Slicing characters between " + "3rd and 2nd last
character: ")
 print(String1[3:-2])
Deleting/Updating from a String
 Strings are immutable, hence elements of a String cannot
be changed once it has been assigned.
 Although deletion of the entire String is possible with the use
of a built-in del keyword.
 However, strings can be updated using the following two
ways:
 By creating a list from strings and then updating the list. Example:
 String1 = "GeeksForGeeks"
 list1 = list(String1)
 list1[2] = 'p'
 String2 = ''.join(list1)
 print(“Updating character at 2nd Index: ")
 print(String2)
 String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
Deleting/Updating from a String

 Python Program to Delete characters from a String


 String1 = "Hello, I'm a Geek“
 String2 = String1[0:2] + String1[3:]
 print("Deleting character at 2nd Index: ")
 print(String2)
 Deleting Entire String:
 String1="Hello, I'm a Geek"
 del String1
 print("Deleting entire String:")
 print(String1)
Escape Sequences in Python
 An attempt of printing Strings with apostrophe, single/double quotes in it
causes SyntaxError.
 To print such Strings either Triple quotes or Escape sequence (\) are used.
 Printing a string with apostrophe using Escape sequence
o String1 = 'I\'m a "Geek"‘
print(“Escaping Single Quote: ")
print(String1)

 Printing a string with apostrophe using triple quotes


o String1 = ‘’'I\'m a "Geek"‘’’
print(“Escaping Triple Quote: ")
print(String1)
# Printing hello in octal ASCII Code
String1 = "\110\145\154\154\157"
print("Printing in Octal with the use of Escape Sequences: ")
print(String1)
Dec Oct Hex bin ASCII
# Using raw String to ignore Escape Sequences
String1 = r"\110\145\154\154\157"
print("Printing Raw String in Octal Format: ")
print(String1)

# Printing Geeks in HEX


String1 = "\x48\x65\x6C\x6C\x6F"
print("Printing in HEX with the use of Escape Sequences: ")
print(String1)
# Using raw String to ignore Escape Sequences
String1 = r"\x48\x65\x6C\x6C\x6F"
print("Printing Raw String in HEX Format: ")
print(String1)
Print ASCII Value of a character
using Using ord() function
 It converts the given string of length one to an integer representing
the Unicode code point of the character
c = 'e'
d='&'
# print the ASCII value of assigned character in c and d
print("The ASCII value of " + c + " is", ord(c))
print("The ASCII value of " + d + " is", ord(d))
Formatting of Strings
 format() is used to format the strings in Python
 very versatile and powerful tool for formatting Strings.
 Format method in String contains curly braces {} as placeholders which can
hold arguments according to position or keyword to specify the order.
 Program
# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)
In Python
 Python Collections: There are four collection data types in the
Python programming language.

o List is a collection which is ordered and


changeable. Allows duplicate members.

o Tuple is a collection which is ordered and


unchangeable. Allows duplicate members.

o Dictionary is a collection which is ordered (In


Python 3.6 and earlier, dictionaries are unordered)
and changeable. No duplicate members.
Lists
 Lists are used to store a collection of data.
 Lists are used to store multiple items in a single variable.
 In Python, you can create a list by enclosing the elements in
square brackets [] separated by commas.
 A list can contain elements of different data types.
 len() function returns the number of items in the list.
 List items are ordered, changeable, and allow duplicate values.
o the items have a defined order, and that order will
not change; if you add new items to a list, the new
items will be placed at the end of the list.
o change, add, and remove items in a list is possible
after it has been created.
o lists can have items with the same value.
Creating a List
 Examples:
o my_list = [1, 2, 3, ‘apple’, "orange"]
o list() Constructor creates a new list.
 thislist = list(("apple", "banana", "cherry")) 
print(thislist)

 From Python's perspective, lists are defined as objects with the data type 'list‘ and
the same can be obtained using type() function.
o mylist = [‘apple’, ’banana’, ’cherry’]
print(type(mylist))
Accessing Elements in a List
 You can access individual elements in a list using indexing.
 Python uses zero-based indexing, which means the first element
is at position 0, the second element is at position 1, and so on.
 To access the nth element in a list, use the indexing operator []
with the index n-1.
 For example:
o my_list = [1, 2, 3, "apple", "orange"]
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: apple
Basic Operations
 Python provides several basic operations that can be performed on lists.
 These include concatenation (+), repetition (*), and membership testing (in).
 For example:
o list1 = [1, 2, 3]
list2 = ["apple", "orange"]
list3 = list1 + list2 Concatenation
print(list3) # Output: [1, 2, 3, ‘apple’, ‘orange’]

o list4 = list1 * 3 Repetition


print(list4) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

o print('apple' in list2) Membership testing


# Output: True
List Slices
 You can also access a range of elements in a list using slicing.
 To slice a list, use the slicing operator [start:end].
 The start index is inclusive, and the end index is exclusive.
 For example:
o my_list = [1, 2, 3, "apple", "orange"]
print(my_list[0:3]) # Output: [1, 2, 3]
print(my_list[3:]) # Output: [‘apple’,
‘orange’]
print(my_list[2:3]) # Output: [3, ‘apple’]

 You can also use negative indexing to slice a list from the end. For example:
o my_list = [1, 2, 3, "apple", "orange"]
print(my_list[-2:]) # Output: [‘apple’, ‘orange’]
 You can specify a step value in the slicing operator to select
alternate elements. The syntax for step value is [start:end:step].
For example:
o my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[::2]) # Output: [0, 2, 4, 6, 8]

Modifying Lists
 In Python, lists are mutable, which means you can modify them
directly.
 You can modify the elements in a list by accessing them using
indexing or slicing, and then assigning new values.
 For example:
o my_list = [1, 2, 3, "apple", "orange"]
my_list[3] = "banana"
print(my_list) # [1, 2, 3, ‘banana’, ‘orange’]
Loops for Lists
 for loop
a = ["apple","banana","cherry"]
for x in a:
print(x, end=' ')

 for loop through the Index Numbers


o Use the range() and len() functions to create a suitable
iterable
o Example:
a = ["apple","banana","cherry"]
for i in range(len(a)):
print(a[i], end=' ')
 While Loop
 Use the len() function to determine the length of the
list, then start at 0 and loop your way through the list
items by referring to their indices.
 Remember to increase the index by 1 after each
iteration.
 Example:
a = ["apple","banana","cherry"]
i=0
while (i<len(a)):
print(a[i], end=' ')
i = i+1
List Comprehension
 List comprehension offers a shorter syntax when you want to create
a new list based on the values of an existing list.
 Let’s make a new list, containing only the fruits with the letter "a" in
the name.
 fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
  if "a" in x: Without list comprehension
    newlist.append(x)
print(newlist)
Acts as data filter
With list comprehension
Syntax: newlist = [expression for item in iterable if condition == True]
 fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
What is the output for the following code?

 fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


 newlist = [x for x in fruits if x != "apple"]
 print(newlist)

newlist = [x for x in range(10) if x < 5]


print(newlist)
Python has a set of built-in methods that you can use on lists.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
insert() Adds an element at the specified position
extend() Add the elements of a list (or any iterable), to the end of the
current list
remove() Removes the item with the specified value
pop() Removes the element at the specified position
index() Returns the index of the first element with the specified value
count() Returns the number of elements with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
 To append an item to the end of the list, use
the append() method.
o a = ["apple", "banana", "cherry"]
a.append("orange")
print(a)
 clear() - Removes all the elements from the list
o a = ['a', 'b', 'c', 'd', 'e', 'f']
a.clear()
print(a)
 copy() - Returns a copy of the list
o list1 = ['a', 'b', 'c', 'd', 'e', 'f']
o list2=list1.copy()
o print(list2)
 insert() method inserts an item at the specified index
o a = ["apple", "banana", "cherry"]
a.insert(1, "orange")
print(a)

 To append elements from another list to the current list,


use the extend() method. It can append a tuple also.
oa = ["apple", "banana", "cherry"]
b = ["mango", "pineapple", "papaya"]
a.extend(b)
print(a)
 The remove() method removes the specified item.
o a = ["apple", "banana", "cherry"]
a.remove("banana")
print(a)
 The pop() method removes the specified index. If you do not specify the
index, the pop() method removes the last item.
o a = ["apple", "banana", "cherry"]
a.pop(1)
print(a)
 The del keyword removes the specified index and can also delete the list
completely.
 a = ["apple", "banana", "cherry"]
del a[1]
print(a)
 The index() method returns the position at the first occurrence of
the specified value.
o a = ['a', 'b', 'c', 'd', 'e', 'f'] Output: 1
print(a.index('b'))
 The count() method returns the number of elements with the
specified value.
o a = ['a', 'b', 'a', 'd', 'a', 'f']
Output: 3
print(a.count('a'))
 The reverse() method reverses the sorting order of the elements.
o a = ['a', 'b', 'a', 'd', 'a', 'f']
a.reverse()
print(a)
Sorting lists
 sort() method that will sort the list alphanumerically, ascending,
by default.
 sort() method is case sensitive, resulting in all capital letters
being sorted before lower case letters:
 a = ["orange", "mango", "kiwi", "pineapple", "banana"]
a.sort()
print(a)
 a = [100, 50, 65, 82, 23]
a.sort()
print(a)
 To sort descending, use the keyword argument reverse = True
 a=["orange","mango","kiwi","pineapple","banana"]
 a.sort(reverse=True)
 print(a)
Sorting lists
 You can also customize your own function by using the keyword
argument key = function
 def myfun(n):
 return abs(n-50)
 a=[100,50,65,82,23]
 a.sort(key=myfun)
 print(a)
 For a case-insensitive sort function, use str.lower as a key
function.
 thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
Sorting lists
 The reverse() method reverses the current sorting order of the
elements.
 a = ["banana", "Orange", "Kiwi", "cherry"]
a.reverse()
print(a)
 The copy() method makes a copy
 a = ["apple", "banana", "cherry"]
b = a.copy()
print(b)
 list() makes a copy of a list:
 a = ["apple", "banana", "cherry"]
b = list(a)
print(b)
Python Tuples
 A tuple in Python is similar to a list.
 The difference between the two is that we cannot change the elements of a tuple once it is
assigned whereas we can change the elements of a list.
 In tuples, elements are placed inside parenthesis () seperated by commas, whereas the
elements are placed inside square brackets [] in case of lists.
 Creating tuples:
 # Empty tuple
 my_tuple = ()
 print(my_tuple)
 # Tuple having integers
 my_tuple = (1, 2, 3)
 print(my_tuple)
 # tuple with mixed datatypes
 my_tuple = (1, "Hello", 3.4)
 print(my_tuple)
 # nested tuple
 my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
 print(my_tuple)
Access Python Tuple Elements
 Tuples are immutable, and usually, they contain a
sequence of heterogeneous elements that are
accessed via unpacking or indexing
 Indexing- similar to lists
 Negative indexing- similar to lists
 Slicing – using slicing operator(:) – similar to lists
 Example: my_tuple = ('a', 'p', 'p', 'l', 'e',)
 Tuple methods
 my_tuple.count('p') - counts total number of 'p' in my_tuple
- 2
 my_tuple.index('l') - returns the first occurrence
of 'l' in my_tuple - 3
 Iterating through a Tuple in Python- similar to
lists
 Tuple unpacking
 Tuple1 = ("Geeks", "For", "Geeks")
  # This line unpack the values of Tuple1
 a, b, c = Tuple1
 print("Values after unpacking: ")
 print(a)
 print(b)
 print(c)
 Concatenation of Tuples
 Concatenation is done by the use of ‘+’ operator.
 Concatenation of tuples is done always from the end
of the original tuple.

Tuple3 = Tuple1 + Tuple2


Python Tuples vs Lists
Python Dictionaries
 Dictionaries are used to store data values in key:value pairs; can be
referred to by using the key name
 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.
 Example:
 thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)
 Duplicate values will overwrite existing values.
 thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "year": 2020
}
print(thisdict)
 len() function returns the number of elements
Python Dictionaries
 The values in dictionary items can be of any data type.
 type() returns the data type of the dictionary item as dict.
 dict() constructor to used to make a dictionary.
 thisdict = dict(name = "John", age = 36, country = "Norway")

 You can access the items of a dictionary by referring to its key


name, inside square brackets.
 thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"]
 get() will also give the same result
 x = thisdict.get("model")
 keys() method will return a list of all the keys in the dictionary.
 x = thisdict.keys()
 values() method will return a list of all the values in the dictionary.
 x = thisdict.values()
Python Dictionaries
 items() method will return each item in a dictionary, as tuples in a
list.
 x = thisdict.items()
 To determine if a specified key is present in a dictionary use
the in keyword
 thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")
 You can change the value of a specific item by referring to its key
name.
 thisdict["year"] = 2018 # Change the "year" to 2018
 update() method will update the dictionary with the items from the
given argument.
 thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020})
Python Dictionaries
 An item can be added to the dictionary by using a new index key
and assigning a value to it.
 thisdict = {   "brand": "Ford",
  "model": "Mustang",
  "year": 1964 }
thisdict["color"] = "red"
print(thisdict)
 pop() method removes the item with the specified key name.
 thisdict.pop("model")
 popitem() method removes the last inserted item
 thisdict = {  "brand": "Ford",
  "model": "Mustang",
  "year": 1964 }
thisdict.popitem()
print(thisdict)
 del keyword removes the item with the specified key name.
del keyword can also delete the dictionary completely.
 del thisdict["model"]
 Del thisdict
 clear() method empties the dictionary
 thisdict.clear()
Python Modules

 Example:
 def greeting(name): Save this code in a file
  print("Hello, " + name) named mymodule.py
 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")
def fib_rec(n): Save the entire program with a name fib.py
"recursive fibonacci"
if (n<=1):
return n
else:
return fib_rec(n-1)+fib_rec(n-2)

def fib_iter(n):
"iterative fibonacci"
cur,nxt=0,1
for k in range(n):
cur,nxt=nxt,cur+nxt
return cur

def fib_upto(n):
"given n, return list of fibonacci numbers <=n" Within a module, the module’s name is
cur, nxt=0,1 available as the value of the global
lst=[] variable __name__
while (cur<n):
lst.append(cur)
cur,nxt=nxt,cur+nxt
return lst
Variables in Module
 The module can contain functions but also variables of all
types (arrays, dictionaries, objects etc)
 Example:
 person1 = {
  "name": "John",
  "age": 36, Save this code in the file mymodule.py
  "country": "Norway"
}
 Import the module named mymodule, and access the person1 dictionary
 Example:
 import mymodule
a = mymodule.person1["age"]
print(a)
 You can name the module file whatever you like, but it must have the file
extension .py
 import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
Module Use
import platform Platform module is used to retrieve as much possible information about
the platform on which the program is being currently executed.
import datetime Datetime module provides a module to work with dates as date objects
import math Math module facilitates the use of various mathematical functions

x = platform.system()
print(x)
datetime.now()
function has the
import datetime following attributes:
x = datetime.datetime.now() •Year
print(x) •month
•day
•hour
import math •minute
x = math.ceil(1.4) •second
y = math.floor(1.4) •microsecond
print("value of x:", x)
print("value of y:",y)
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"))
Built-in Math Functions
 min() and max() functions can be used to find the lowest or
highest value in an iterable
 The abs() function returns the absolute (positive) value of the
specified number.
 import math
x=abs(-7.25)
print(x)
 pow(x, y) function returns the value of x to the power of y (x y).
 math.sqrt() method for example, returns the square root of a
number.
 import math
x = math.sqrt(64)
print(x)
 math.ceil() method rounds a number upwards to its nearest
integer, and the math.floor() method rounds a number
downwards to its nearest integer.
 math.pi constant, returns the value of PI (3.14...)
Built-in Math Functions
Built-in Math Functions
Built-in Math Functions
Built-in Math Constants
Random module
 In Python, random numbers are not generated
implicitly; it provides a random module in order to
generate random numbers explicitly.
 Applications
 Creating pseudo-random numbers on Lottery scratch cards
 reCAPTCHA on login forms (numbers and images)
 Picking a number, flipping a coin, and throwing of a dice
related games required random numbers
 Shuffling deck of playing cards
 A random module is imported using the command:
 import random
 Some of Built-in functions in Random module
(1) random() # Generate a random floating number between 0 and 1
Syntax:
random.random()
(2) randrange() # generate random numbers from a specified range
Syntax:
random.randrange(start(opt),stop,step(opt))
Raises ValueError if stop <= start and number is non- integral.
(3) randint() # Generate a random integer from a specified range
Syntax:
random.randint(start, end)
Returns a ValueError when floating point values are passed as parameters.
Returns a TypeError when anything other than numeric values are passed as parameters.
(4) seed() # generate pseudo-random numbers
Syntax:
random.seed(l) # l is a seed value used to produce a random number.
(5) choices() # Generate a random element from a sequence
Syntax:
random.choices(sequence, weights=None, k=1)
(6) shuffle() # Shuffling a list of objects
Syntax:
random.shuffle(sequence, function)
import random
#random() function
print(random.random())
print ("Random number from 0-100 is : ",end="")
#randrange() function
print (random.randrange(100))
#randint() function
r1 = random.randint(0, 10)
print("Random number between 0 and 10 is % s" % (r1))
#seed() function
random.seed(0)
print(random.randint(1, 1000))
#choices() function
mylist = ["geeks", "for", "python"]
print(random.choices(mylist, weights = [10, 1, 1], k = 5))
#shuffle() function
sample_list = ['A', 'B', 'C', 'D', 'E']
print("Original list : ")
print(sample_list)
random.shuffle(sample_list)
print("\nshuffled list : ")
print(sample_list)
Packages
 A package is a collection of modules that are
organized in a hierarchical directory structure.
 To use a module from a package, you first need
to import the package, followed by the module.
Creating Package
 Create a folder named mypckg.
 Inside this folder create an empty
Python file i.e. __init__.py
 Then create two modules mod1 and
mod2 in this folder.

All the functions of the modules will be imported in


the __init__.py python file.

How to access the package, module and function


o import my_package.my_module
oimport my_package.my_module.my_function()
Exceptions in Python
 In Python, There are two distinguishable kinds of
errors: syntax errors and exceptions.
 Syntax errors, also known as parsing errors, are perhaps
the most common kind of complaint you get while you are
still learning Python:

 The parser repeats the offending line and displays a little


‘arrow’ pointing at the earliest point in the line where the
error was detected.
Difference between Syntax Error and Exceptions

 Syntax Error
 As the name suggests this error is caused by the wrong syntax in the code.
 It leads to the termination of the program. 
 Example:
 amount = 10000
  if(amount > 2999)
 print("You are eligible to purchase Dsa Self Paced")

 Exceptions
 Exceptions are raised when the program is syntactically correct, but the code results in
an error.
 This error does not stop the execution of the program, however, it changes the normal
flow of the program.
 Example:
 marks = 10000
  a = marks / 0
 print(a)
Different types of exceptions in python
 SyntaxError: This exception is raised when the interpreter encounters a syntax error in
the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
 TypeError: This exception is raised when an operation or function is applied to an object
of the wrong type, such as adding a string to an integer.
 NameError: This exception is raised when a variable or function name is not found in the
current scope.
 IndexError: This exception is raised when an index is out of range for a list, tuple, or
other sequence types.
 KeyError: This exception is raised when a key is not found in a dictionary.
 ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does
not represent a valid integer.
 AttributeError: This exception is raised when an attribute or method is not found on an
object, such as trying to access a non-existent attribute of a class instance.
 IOError: This exception is raised when an I/O operation, such as reading or writing a file,
fails due to an input/output error.
 ZeroDivisionError: This exception is raised when an attempt is made to divide a number
by zero.
 ImportError: This exception is raised when an import statement fails to find or load a
module.
Exception handling
 Try and Except Statement – Catching Exceptions

 Example
 a = [1, 2, 3]
 try:
 print ("Second element = %d" %(a[1]))
 # Throws error since there are only 3 elements in array
 print ("Fourth element = %d" %(a[3]))
 except IndexError:
 print (“array Out of Index (IndexError) error occurred")
Exception handling
 Try with Else Clause
 “else” clause can be used on the try-except block which must be present after all the
except clauses.
 The code enters the else block only if the try clause does not raise an exception.
 Example:
 def AbyB(a , b):
 try:
 c = ((a+b) / (a-b))
 except ZeroDivisionError:
 print ("a/b result in 0")
 else:
 print (c)
 # function calls to test above function
 AbyB(2.0, 3.0)
 AbyB(3.0, 3.0)
Exception handling
 Try with Else and finally Clause
 The final block always executes after the normal termination of the try block or after
the try block terminates due to some exception.

try: Example:
k = 5//0 # raises divide by zero
exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
User defined exceptions
 We can also define our own exceptions by sub classing the built-in
Exception class. Here's an example:
class MyError(Exception):
pass
def my_function(x):
if x < 0:
raise MyError("x must be non-negative")
return x**2
try:
result = my_function(-1)
except MyError as error:
print(error)
 The MyError class is defined by sub classing Exception. The
my_function function raises a MyError exception if the input value x is
negative. The try statement catches the exception and prints the
error message.

You might also like