SlideShare una empresa de Scribd logo
1 de 29
Faculty of Engineering Science & Technology(FEST)
Hamdard Institute of Engineering Technology(HIET)
HAMDARD UNIVERSITY
Instructor
ABDUL HASEEB
HANDS-ON WORKSHOP ON PYTHON
PROGRAMMING LANGUAGE
Faculty Development Program (Session-10)
DAY-3
The Python Programming Language
Day 2 Workshop Contents
• Error handling
• List (Array)
• Random Number
Error Handling
Exception is an ambiguity or error which occur during the execution
of the program. The Exception must be handle in code other wise it
effect the flow of program execution.
Syntax try except/else and finally
try:
..........operation
except Exception_1:
..........if there is Exception, then execute this block
except Exception_2:
..........if there is Exception, then execute this block
else:
..........if there is no exception then execute this block
finally:
..........this would always be executed
Program 1 (No Error Handling statement)
Enter a = 5
Enter b = 2
Result 2.5
Enter a = 3.6
Enter b = 4.2
ValueError: invalid literal for int() with base 10: '3.6'
Enter a = A
Enter b = B
ValueError: invalid literal for int() with base 10: 'A'
Enter a = 7
Enter b = 0
ZeroDivisionError: division by zero
num1 = input("Enter a = ")
num2 = input("Enter b = ")
result = int(num1)/int(num2)
print('Result',result)
Program
Output 2
Output 3
Output 4
Output 1
Program 1 (No type of Exception use)
num1 = input("Enter a = ")
num2 = input("Enter b = ")
try:
result = int(num1)/int(num2)
except:
print('error')
else:
print('Result',result)
finally:
print('Thank you')
Result 1
Enter a = 5
Enter b = 2
Result 2.5
Thank you
Result 2
Enter a = 3.6
Enter b = 4.2
error
Thank you
Result 3
Enter a = 7
Enter b = 0
error
Thank you
Program 2 (with type of Exception)
num1 = input("Enter a = ")
num2 = input("Enter b = ")
try:
result = int(num1)/int(num2)
except ZeroDivisionError:
print('Number cannot divisibly by 0')
except ValueError:
print('Please enter integer number')
else:
print('Result',result)
finally:
print('Thank you')
Result 1
Enter a = 5
Enter b = 2
Result 2.5
Thank you
Result 2
Enter a = 3.6
Enter b = 4.2
Please enter integer number
Thank you
Result 3
Enter a = 7
Enter b = 0
Number cannot divisibly by 0
Thank you
Exercise
Insert Exception in the following Infinite loop
Program
while True:
print("Hamdard University")
Note: To break Infinite loop use Ctrl + c
Output
Hamdard University
Hamdard University
Hamdard University
Traceback (most recent call last):
File "C:UsersHomeDesktoptemp.py", line 132, in <module>
print("Hamdard University")
KeyboardInterrupt print("Hamdard University")
Exercise Solution
Program
try:
while True:
print("Hamdard University")
except KeyboardInterrupt:
print("Thank you“)
Output
Hamdard University
Hamdard University
Hamdard University
Hamdard University
Thank you
Example
The following program ask user to enter his height in cm that is integer
value, if user enter in feet (floating value) then program will take his height
in feet and proceed further program
try:
num = int(input("Enter your height in cm = "))
print('Your height in cm is =',num)
except ValueError:
num = float(input("Ok! you want to enter in feet = "))
print('Your height in feet is =',num)
finally:
print('Thank you')
Output:
Enter your height in cm = 36.45
Ok! you want to enter in feet = 36.45
Your height in feet is = 36.45
Thank you
Exception with while loop
The following program take Integer value from user. If user enter an Integer value then program proceed
but if user enter non-integer value then it will ask again until enter correct value
Program
key_check = True
while(key_check == True):
try:
key = int(input("Enter a number ="))
except:
print('You have press an invalid digit')
key_check = True
else:
key_check = False
print('You have enter number',key)
Output
Enter a number =a
You have press an invalid digit
Enter a number =b
You have press an invalid digit
Enter a number =c
You have press an invalid digit
Enter a number =3
You have enter number 3
LIST (Array)
• Two types of Array
• Static Array (in C)
• Dynamic Array( in Python)
Example in C (static Array)
float balance[5] = {10.0, 2.0, 3.4, 7.0, 50.0};
balance[4] = 50.0; //Update array value
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
char greeting[] = "Hello"; // Or it can be written as
Example of Array in Python (Dynamic Array)
My_data = ['physics', 'chemistry', 1997, 2000]
Example
Example:
a=[0,0,0] #creating list of 3 elements
a[0] = input(“Enter name 1= ”)
a[1] = input(“Enter name 2= ”)
a[2] = input(“Enter name 3= ”)
print(‘Name 1 is’, a[0] , ‘ Name 2 is’, a[1] , ‘ Name 3 is’, a[2])
LIST Example
a = [0,1,2,3,4,5,6,7,8,9] #Making list
a[2] = 2 # Value of index 2
a[4] = 4 # Value of index 4
a[3:] = [3, 4, 5, 6, 7, 8, 9] # All values from(after) index 3
a[:7] = [0, 1, 2, 3, 4, 5, 6] # All values before index 7
a[3:7] = [3, 4, 5, 6] # All values from index 3 to index 7
Forward and Backward Indexing
a = [1,2,3,4,5]
a[0]
1
a[1]
2
a[2]
3
a[3]
4
a[4]
5
a = [1,2,3,4,5]
a[-1]
5
a[-2]
4
a[-3]
3
a[-4]
2
a[-5]
1
Forward Indexing Reverse Indexing
List-append
a = []
[]
a.append(2)
[2]
a.append(3.5)
[2, 3.5]
a.append('xyz')
[2, 3.5, 'xyz']
2 2
2 3.5 3.5
2 3.5 xyz ‘xyz’
list.append(object): Append object to end
list - clear
a = [0,1,2,3,4,5]
[0, 1, 2, 3, 4, 5]
a.clear()
[]
list - index
a = [2,4,6,4]
a.index(2)
0
a.index(4)
1
a.index(6)
2
a.index(8)
Traceback (most recent call last):
ValueError: 8 is not in list
list.clear() : Remove all items from list
list.index(value): Return first index of value.
Raises ValueError if the value
is not present.
a = [1,2,3,4,5,6]
b = ['a','b']
a = [0,1,2,3,4,5,6]
b = ['a','b']
a = b.copy()
a
['a', 'b']
a = [0, 1, 2, 3, 4, 5]
b = []
b = a.copy()
b = [0, 1, 2, 3, 4, 5]
list - copy
a = [0,1,2,3,4,5,6]
b = ['a','b']
a[3:] = b.copy()
a
[0, 1, 2, 'a', 'b']
a = [0,1,2,3,4,5,6]
b = ['a','b']
a[3:4] = b.copy()
a = [0, 1, 2, 'a', 'b', 4, 5, 6]
Example
Example
Example Example
list.copy(): A shallow copy of list to another list
list - extend
a = [0,1,2]
b = ['a','b','c']
b.extend(a)
b = ['a', 'b', 'c', 0, 1, 2]
b.extend(a)
b = ['a', 'b', 'c', 0, 1, 2, 0, 1, 2]
list.extend(iterable): extend list by appending elements from the iterable
list-count
a = [0,1,1,2,2,2]
a.count(0)
1
a.count(1)
2
a.count(2)
3
a.count(3)
0
a =['A','B','B','C','C','C']
a.count('A')
1
a.count('B')
2
a.count('C')
3
list.count(value): Return number of occurrences of value
list-pop
a = [0,1,2,3,4,5]
b = a.pop()
b = 5
a = [0, 1, 2, 3, 4]
a.pop()
a = [0,1,2,3]
c= a.pop()
c = 3
a = [0,1,2]
0 1 2 3 4
0 1 2 3 4
0 1 2 3
5
5
0 1 2 3
4
list.pop([index]): Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
list append and pop example
a = [2,4,6,8]
b = []
b.append(a.pop())
a =[2, 4, 6]
b =[8]
b.append(a.pop())
a = [2, 4]
b = [8, 6]
b.append(a.pop())
a = [2]
b =[8, 6, 4]
b.append(a.pop())
a = []
b = [8, 6, 4, 2]
2 4 6 8
2 4 6
2 4
2
8
8 6
8 6 4
8 6 4 2
Move the elements from list-a to list-b
list sort and reverse
a = [1,5,9,7,0,3,6,4,2,8]
a.reverse()
a = [8, 2, 4, 6, 3, 0, 7, 9, 5, 1]
a.sort()
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a.reverse()
a = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
a = ['h','a','m','d','a','r','d']
a.sort()
a = ['a', 'a', 'd', 'd', 'h', 'm', 'r']
a.reverse()
a = ['r', 'm', 'h', 'd', 'd', 'a', 'a']
reverse(): Reverse the Array element
sort(): Place element in ascending order
list -remove
a = [1,2,2,3,3]
a.remove(1)
a = [2, 2, 3, 3]
a.remove(2)
a = [2, 3, 3]
a.remove(3)
a = [2, 3]
1 2 2 3 3
remove(value): Remove first occurrence of value.
Return ValueError if the value is not present.
1 2 2 3 3
2 2 3 3
2 3 3
list - insert
a = [0,1,2,3,4]
a.insert(2,5)
a = [0, 1, 5, 2, 3, 4]
a.insert(4,9)
a = [0, 1, 5, 2, 9, 3, 4]
a.insert(9,7)
a = [0, 1, 5, 2, 9, 3, 4, 7]
Insert( index position , value ): Insert object before index position
0 1 2 3 4
1 5 2 3 4
2 9 3 4 7
5 2 9 3 4
0
10
510
5
9
7
Exercise
• First generate 20 Random number
• Separate the Random number in two different
list that are
– Even[]
– Odd
Example Solution
import random
from random import randint
a = []
even = []
odd = []
for i in range(20):
a.append(randint(2,10))
print(a)
a.reverse()
print(a)
for i in range(20):
b = a.pop()
if(b%2 == 0):
even.append(b)
else:
odd.append(b)
print(even)
print(odd)
20 Random Number:
[8, 2, 4, 3, 4, 9, 4, 8, 8, 10, 9, 6, 3, 7, 7,
7, 3, 4, 4, 3]
Reverse the List:
[3, 4, 4, 3, 7, 7, 7, 3, 6, 9, 10, 8, 8, 4, 9,
4, 3, 4, 2, 8]
List of Even Number:
[8, 2, 4, 4, 4, 8, 8, 10, 6, 4, 4]
List of Odd Number:
[3, 9, 9, 3, 7, 7, 7, 3, 3]
Program
Comparing Python with C/C++
Programming Parameter Python Language C/C++ Language
Programming type Interpreter Compiler
Programming Language High level Language Middle level Language
Header file import #include
Code block Whitespace Indentation
Code within curly bracket
{ code}
Single line statement
termination
Nothing Semicolon ;
Control flow (Multi line)
statement termination
Colon : Nothing
Single line comments # comments //comments
Multi-line comments
‘’’
Comments lines
‘’’
/*
Comments lines
*/
If error code found Partial run code until find error
Did not run until error is
present
Program length Take fewer lines Take relatively more lines
Python Programming code comparison with C
programming code
Python program C/C++ program
Multi-line comments
Including library
Declaring variable
Multi-line statement
Code Block
Single-line statement
Single line comments
‘’’ The Python Language
Example code ’’’
Import time
a=10 #integer value
name = 'karachi' #String
for i in range (a):
print("Hamdard")
print('University')
print(name)
#program end
/* The C/C++ language
Example code */
#include <iostream>
using namespace std;
int main()
{
int a = 10;
char name[10] = "Karachi";
for(int i =0 ; i <a ; i ++ )
{
cout<<"Hamdard ";
cout<<"University"<<endl;
}
cout<<name;
return 0;
}
//program end
THANK YOU

Más contenido relacionado

La actualidad más candente

Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
INTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHONINTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHONvikram mahendra
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONvikram mahendra
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output Intro C# Book
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]vikram mahendra
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to KleisliHermann Hueck
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!Hermann Hueck
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]vikram mahendra
 
OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2vikram mahendra
 
OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1vikram mahendra
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings imtiazalijoono
 
Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Naveen Kumar
 

La actualidad más candente (20)

09. Methods
09. Methods09. Methods
09. Methods
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
INTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHONINTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHON
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
 
Cbse marking scheme 2006 2011
Cbse marking scheme 2006  2011Cbse marking scheme 2006  2011
Cbse marking scheme 2006 2011
 
OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2
 
OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3
 
OOP v3
OOP v3OOP v3
OOP v3
 

Similar a Python programming workshop session 3

8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...Yashpatel821746
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Yashpatel821746
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...Yashpatel821746
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
python lab programs.pdf
python lab programs.pdfpython lab programs.pdf
python lab programs.pdfCBJWorld
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptAnishaJ7
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdfsimenehanmut
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
Data structures KTU chapter2.PPT
Data structures KTU chapter2.PPTData structures KTU chapter2.PPT
Data structures KTU chapter2.PPTAlbin562191
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.pptssuserd64918
 
Computer science ms
Computer science msComputer science ms
Computer science msB Bhuvanesh
 
programs on arrays.pdf
programs on arrays.pdfprograms on arrays.pdf
programs on arrays.pdfsowmya koneru
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersKimikazu Kato
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a ElixirSvet Ivantchev
 

Similar a Python programming workshop session 3 (20)

Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
python lab programs.pdf
python lab programs.pdfpython lab programs.pdf
python lab programs.pdf
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Mcq cpup
Mcq cpupMcq cpup
Mcq cpup
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
Data Handling
Data Handling Data Handling
Data Handling
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Data structures KTU chapter2.PPT
Data structures KTU chapter2.PPTData structures KTU chapter2.PPT
Data structures KTU chapter2.PPT
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.ppt
 
Computer science ms
Computer science msComputer science ms
Computer science ms
 
programs on arrays.pdf
programs on arrays.pdfprograms on arrays.pdf
programs on arrays.pdf
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 

Último

How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 

Último (20)

How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 

Python programming workshop session 3

  • 1. Faculty of Engineering Science & Technology(FEST) Hamdard Institute of Engineering Technology(HIET) HAMDARD UNIVERSITY Instructor ABDUL HASEEB HANDS-ON WORKSHOP ON PYTHON PROGRAMMING LANGUAGE Faculty Development Program (Session-10) DAY-3
  • 2. The Python Programming Language Day 2 Workshop Contents • Error handling • List (Array) • Random Number
  • 3. Error Handling Exception is an ambiguity or error which occur during the execution of the program. The Exception must be handle in code other wise it effect the flow of program execution. Syntax try except/else and finally try: ..........operation except Exception_1: ..........if there is Exception, then execute this block except Exception_2: ..........if there is Exception, then execute this block else: ..........if there is no exception then execute this block finally: ..........this would always be executed
  • 4. Program 1 (No Error Handling statement) Enter a = 5 Enter b = 2 Result 2.5 Enter a = 3.6 Enter b = 4.2 ValueError: invalid literal for int() with base 10: '3.6' Enter a = A Enter b = B ValueError: invalid literal for int() with base 10: 'A' Enter a = 7 Enter b = 0 ZeroDivisionError: division by zero num1 = input("Enter a = ") num2 = input("Enter b = ") result = int(num1)/int(num2) print('Result',result) Program Output 2 Output 3 Output 4 Output 1
  • 5. Program 1 (No type of Exception use) num1 = input("Enter a = ") num2 = input("Enter b = ") try: result = int(num1)/int(num2) except: print('error') else: print('Result',result) finally: print('Thank you') Result 1 Enter a = 5 Enter b = 2 Result 2.5 Thank you Result 2 Enter a = 3.6 Enter b = 4.2 error Thank you Result 3 Enter a = 7 Enter b = 0 error Thank you
  • 6. Program 2 (with type of Exception) num1 = input("Enter a = ") num2 = input("Enter b = ") try: result = int(num1)/int(num2) except ZeroDivisionError: print('Number cannot divisibly by 0') except ValueError: print('Please enter integer number') else: print('Result',result) finally: print('Thank you') Result 1 Enter a = 5 Enter b = 2 Result 2.5 Thank you Result 2 Enter a = 3.6 Enter b = 4.2 Please enter integer number Thank you Result 3 Enter a = 7 Enter b = 0 Number cannot divisibly by 0 Thank you
  • 7. Exercise Insert Exception in the following Infinite loop Program while True: print("Hamdard University") Note: To break Infinite loop use Ctrl + c Output Hamdard University Hamdard University Hamdard University Traceback (most recent call last): File "C:UsersHomeDesktoptemp.py", line 132, in <module> print("Hamdard University") KeyboardInterrupt print("Hamdard University")
  • 8. Exercise Solution Program try: while True: print("Hamdard University") except KeyboardInterrupt: print("Thank you“) Output Hamdard University Hamdard University Hamdard University Hamdard University Thank you
  • 9. Example The following program ask user to enter his height in cm that is integer value, if user enter in feet (floating value) then program will take his height in feet and proceed further program try: num = int(input("Enter your height in cm = ")) print('Your height in cm is =',num) except ValueError: num = float(input("Ok! you want to enter in feet = ")) print('Your height in feet is =',num) finally: print('Thank you') Output: Enter your height in cm = 36.45 Ok! you want to enter in feet = 36.45 Your height in feet is = 36.45 Thank you
  • 10. Exception with while loop The following program take Integer value from user. If user enter an Integer value then program proceed but if user enter non-integer value then it will ask again until enter correct value Program key_check = True while(key_check == True): try: key = int(input("Enter a number =")) except: print('You have press an invalid digit') key_check = True else: key_check = False print('You have enter number',key) Output Enter a number =a You have press an invalid digit Enter a number =b You have press an invalid digit Enter a number =c You have press an invalid digit Enter a number =3 You have enter number 3
  • 11. LIST (Array) • Two types of Array • Static Array (in C) • Dynamic Array( in Python) Example in C (static Array) float balance[5] = {10.0, 2.0, 3.4, 7.0, 50.0}; balance[4] = 50.0; //Update array value char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'}; char greeting[] = "Hello"; // Or it can be written as Example of Array in Python (Dynamic Array) My_data = ['physics', 'chemistry', 1997, 2000]
  • 12. Example Example: a=[0,0,0] #creating list of 3 elements a[0] = input(“Enter name 1= ”) a[1] = input(“Enter name 2= ”) a[2] = input(“Enter name 3= ”) print(‘Name 1 is’, a[0] , ‘ Name 2 is’, a[1] , ‘ Name 3 is’, a[2])
  • 13. LIST Example a = [0,1,2,3,4,5,6,7,8,9] #Making list a[2] = 2 # Value of index 2 a[4] = 4 # Value of index 4 a[3:] = [3, 4, 5, 6, 7, 8, 9] # All values from(after) index 3 a[:7] = [0, 1, 2, 3, 4, 5, 6] # All values before index 7 a[3:7] = [3, 4, 5, 6] # All values from index 3 to index 7
  • 14. Forward and Backward Indexing a = [1,2,3,4,5] a[0] 1 a[1] 2 a[2] 3 a[3] 4 a[4] 5 a = [1,2,3,4,5] a[-1] 5 a[-2] 4 a[-3] 3 a[-4] 2 a[-5] 1 Forward Indexing Reverse Indexing
  • 15. List-append a = [] [] a.append(2) [2] a.append(3.5) [2, 3.5] a.append('xyz') [2, 3.5, 'xyz'] 2 2 2 3.5 3.5 2 3.5 xyz ‘xyz’ list.append(object): Append object to end
  • 16. list - clear a = [0,1,2,3,4,5] [0, 1, 2, 3, 4, 5] a.clear() [] list - index a = [2,4,6,4] a.index(2) 0 a.index(4) 1 a.index(6) 2 a.index(8) Traceback (most recent call last): ValueError: 8 is not in list list.clear() : Remove all items from list list.index(value): Return first index of value. Raises ValueError if the value is not present.
  • 17. a = [1,2,3,4,5,6] b = ['a','b'] a = [0,1,2,3,4,5,6] b = ['a','b'] a = b.copy() a ['a', 'b'] a = [0, 1, 2, 3, 4, 5] b = [] b = a.copy() b = [0, 1, 2, 3, 4, 5] list - copy a = [0,1,2,3,4,5,6] b = ['a','b'] a[3:] = b.copy() a [0, 1, 2, 'a', 'b'] a = [0,1,2,3,4,5,6] b = ['a','b'] a[3:4] = b.copy() a = [0, 1, 2, 'a', 'b', 4, 5, 6] Example Example Example Example list.copy(): A shallow copy of list to another list
  • 18. list - extend a = [0,1,2] b = ['a','b','c'] b.extend(a) b = ['a', 'b', 'c', 0, 1, 2] b.extend(a) b = ['a', 'b', 'c', 0, 1, 2, 0, 1, 2] list.extend(iterable): extend list by appending elements from the iterable
  • 19. list-count a = [0,1,1,2,2,2] a.count(0) 1 a.count(1) 2 a.count(2) 3 a.count(3) 0 a =['A','B','B','C','C','C'] a.count('A') 1 a.count('B') 2 a.count('C') 3 list.count(value): Return number of occurrences of value
  • 20. list-pop a = [0,1,2,3,4,5] b = a.pop() b = 5 a = [0, 1, 2, 3, 4] a.pop() a = [0,1,2,3] c= a.pop() c = 3 a = [0,1,2] 0 1 2 3 4 0 1 2 3 4 0 1 2 3 5 5 0 1 2 3 4 list.pop([index]): Remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.
  • 21. list append and pop example a = [2,4,6,8] b = [] b.append(a.pop()) a =[2, 4, 6] b =[8] b.append(a.pop()) a = [2, 4] b = [8, 6] b.append(a.pop()) a = [2] b =[8, 6, 4] b.append(a.pop()) a = [] b = [8, 6, 4, 2] 2 4 6 8 2 4 6 2 4 2 8 8 6 8 6 4 8 6 4 2 Move the elements from list-a to list-b
  • 22. list sort and reverse a = [1,5,9,7,0,3,6,4,2,8] a.reverse() a = [8, 2, 4, 6, 3, 0, 7, 9, 5, 1] a.sort() a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] a.reverse() a = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] a = ['h','a','m','d','a','r','d'] a.sort() a = ['a', 'a', 'd', 'd', 'h', 'm', 'r'] a.reverse() a = ['r', 'm', 'h', 'd', 'd', 'a', 'a'] reverse(): Reverse the Array element sort(): Place element in ascending order
  • 23. list -remove a = [1,2,2,3,3] a.remove(1) a = [2, 2, 3, 3] a.remove(2) a = [2, 3, 3] a.remove(3) a = [2, 3] 1 2 2 3 3 remove(value): Remove first occurrence of value. Return ValueError if the value is not present. 1 2 2 3 3 2 2 3 3 2 3 3
  • 24. list - insert a = [0,1,2,3,4] a.insert(2,5) a = [0, 1, 5, 2, 3, 4] a.insert(4,9) a = [0, 1, 5, 2, 9, 3, 4] a.insert(9,7) a = [0, 1, 5, 2, 9, 3, 4, 7] Insert( index position , value ): Insert object before index position 0 1 2 3 4 1 5 2 3 4 2 9 3 4 7 5 2 9 3 4 0 10 510 5 9 7
  • 25. Exercise • First generate 20 Random number • Separate the Random number in two different list that are – Even[] – Odd
  • 26. Example Solution import random from random import randint a = [] even = [] odd = [] for i in range(20): a.append(randint(2,10)) print(a) a.reverse() print(a) for i in range(20): b = a.pop() if(b%2 == 0): even.append(b) else: odd.append(b) print(even) print(odd) 20 Random Number: [8, 2, 4, 3, 4, 9, 4, 8, 8, 10, 9, 6, 3, 7, 7, 7, 3, 4, 4, 3] Reverse the List: [3, 4, 4, 3, 7, 7, 7, 3, 6, 9, 10, 8, 8, 4, 9, 4, 3, 4, 2, 8] List of Even Number: [8, 2, 4, 4, 4, 8, 8, 10, 6, 4, 4] List of Odd Number: [3, 9, 9, 3, 7, 7, 7, 3, 3] Program
  • 27. Comparing Python with C/C++ Programming Parameter Python Language C/C++ Language Programming type Interpreter Compiler Programming Language High level Language Middle level Language Header file import #include Code block Whitespace Indentation Code within curly bracket { code} Single line statement termination Nothing Semicolon ; Control flow (Multi line) statement termination Colon : Nothing Single line comments # comments //comments Multi-line comments ‘’’ Comments lines ‘’’ /* Comments lines */ If error code found Partial run code until find error Did not run until error is present Program length Take fewer lines Take relatively more lines
  • 28. Python Programming code comparison with C programming code Python program C/C++ program Multi-line comments Including library Declaring variable Multi-line statement Code Block Single-line statement Single line comments ‘’’ The Python Language Example code ’’’ Import time a=10 #integer value name = 'karachi' #String for i in range (a): print("Hamdard") print('University') print(name) #program end /* The C/C++ language Example code */ #include <iostream> using namespace std; int main() { int a = 10; char name[10] = "Karachi"; for(int i =0 ; i <a ; i ++ ) { cout<<"Hamdard "; cout<<"University"<<endl; } cout<<name; return 0; } //program end