Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
Now Reading
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
Python is an object-oriented, interpreted, high-level, dynamically semantic programming language. It is particularly desirable for quick application development and for usage as a glue language or scripting language to tie existing components together due to its high-level built-in data structures, dynamic typing, and dynamic binding. Python's straightforward syntax emphasizes readability and makes it simple to learn, lowering the program's maintenance cost.
A circumstance that develops while a program is being run is referred to as an exception. It serves as a warning that something unanticipated occurred. In Python, exceptions are represented by an object of a certain type.
All built-in exception handling in Python that does not cause the system to quit derives from the Exception class. Exceptions have descriptive names of their own. For instance, you will get a Zero Division Error exception, which is a subclass of the Exception class, if you attempt to divide a number by zero.
Exceptions can be handled with the try-except statement. The execution of a program could result in exceptions. Exceptions are mistakes that occur while the program is running. Python will immediately stop if it encounters issues such as syntax errors (grammar faults). The end user and developer both suffer from a sudden exit. You can effectively address the issue by using a try-except statement rather than an emergency halt. If you don't handle exceptions correctly, an emergency halt will occur.
We can raise an exception in Python when an unexpected occurrence happens. Python halts execution when an exception is raised and begins looking for an exception handler that can handle it. An exception handler is what, then? The try-except clauses are useful in this situation.
It's crucial to develop programs that can gracefully handle particular mistakes or exceptions. Furthermore, the error or exceptions must not result in a fatal error that forces your program to crash. A code block known as a Python try-except exception statement enables your program to execute several actions in the event of an error.
Here is how you construct a try-except statement:
try:
code block 1
except ExceptionName:
code block 2
Syntax of a try-except statement in Python
try:
# Some Code
except:
# Executed if error in the
# try block
Python will first try to run the try statement's (code block 1) code. If no exception arises, the try statement is completed and the except statement is not executed. The remainder of the clause is omitted in the case of any exception. The code in the except statement will then be run (code block 2) if the exception type satisfies the exception defined following the except keyword (ExceptionName). The program will continue to run the remaining lines of code beyond the try-except code blocks if nothing in this block stops it. The exception is forwarded to outer try statements if it does not match the ExceptionName. If no other handler is discovered, the execution terminates with an error.
The try-except block's principle is as follows:
It is possible to combine it with the finally and else keywords.
Example 1 - Capturing the exception.
x = '6'
try:
if x > 3:
print('X is larger than 3')
except TypeError:
print("Oops! x was not a valid number. Try again...")
Oops! x was not a valid number. Try again...
Example 2 – Handling exceptions using try and except
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
# Output: Error: Denominator cannot be 0.
In the above illustration, we're attempting to divide an integer by zero. This code causes an exception in this case. The try block contains the code result = numerator/denominator, which is used to handle exceptions. The remaining code in the try block is now skipped when an exception occurs.
Statements contained within the except block are carried out after the exception is caught. The except block is skipped if none of the statements in the try block raise an exception.
First, the code between try, or the try clause, is performed. Only the try clause will be executed if there doesn't exist an exception, unless when the clause is finished. The try clause shall be skipped and the except clause will take effect if any exception occurs. Any exception that arises but isn't handled by the codes except the clause is passed on to the outermost try statements. The execution halts if the exception is not handled. There can be more than one unless clause in a try statement.
Python will throw an exception error when syntactically correct code encounters a problem. If this exception error is not handled, the program will crash. Using the except clause, you can control how your program handles exceptions.
You may better understand the try and except block by using the following function:
def linux_interaction():
assert ('linux' in sys.platform), "Function can only run on Linux systems."
print('Doing something.')
Only a Linux machine is capable of running the linux_interaction(). If you call the assert in this function on a platform other than Linux, an AssertionError exception will be raised.
The following code can be used to test the function:
try:
linux_interaction()
except:
pass
You corrected the mistake here by issuing a pass. If this code were executed on a Windows computer you will get a blank code. The fact that the program didn't crash is a plus in this situation. However, it would be useful to know if an exception of any kind was thrown each time your code was executed. To do this, you can modify the pass so that it produces an educational message as follows:
try:
linux_interaction()
except:
print('Linux function was not executed')
Run the following code on a Windows computer:
Linux function was not executed
When a program calling this function encounters an exception, the program will still run and let you know that the function call was unsuccessful. The kind of error that was thrown because of the function call was not visible to you. In Python catch all exceptions and the errors that the program threw to determine precisely what went wrong.
In real life, there are times when we must make choices, and based on those choices, we determine what to do next. Programming encounters similar scenarios where we must make choices and then carry out the following block of code following those choices. Programming languages use decision-making statements to control the direction (or Control Flow) of program execution. The conditional statements that Python try except continue offers are listed below.
In conditional statements (if statements), the else keyword determines what to execute if the condition is False. You can tell a program in Python to run a particular block of code only if there are no exceptions by using the else statement.
In addition to blocks, the else keyword can be used in try; an example is provided below.
Example 1 –
To specify what to do in a try...except block, if no errors were raised, use the else keyword:
x = 5
try:
x > 10
except:
print("Something went wrong")
else:
print("The 'Try' code was executed without raising any errors!")
Example 2 –
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Output – If we pass a number
Enter a number: 1
Not an even number!
If an even number is passed, the reciprocal is calculated and shown.
Enter a number: 4
0.25
If we do so, we receive a ZeroDivisionError since the previous exception does not handle the code block inside else.
Enter a number: 0
Traceback (most recent call last):
File "<string>", line 7, in <module>
reciprocal = 1/num
ZeroDivisionError: division by zero
There may be instances in programming where the current approach fails to handle some exceptions. However, the procedure could need a few further steps before it is finished, such as closing a file or a network. Python offers a keyword finally to address these circumstances, and it is always performed after try and except blocks. The finally block is always executed after the try block has ended normally or after the try block has ended unexpectedly.
Syntax –
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
finally:
# Some code .....(always executed)
The final statement is always carried out following the try statement. After the finally block has been executed, any exceptions that were not handled by the except block are raised again. To deallocate the system resources, the block is used. Finally can be used directly after a try without requiring an except block, no exception handling is done in that scenario.
Let’s look at some examples:
Example 1 –
# Python program to demonstrate finally
# No exception Exception raised in try block
try:
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')
Output:
Can't divide by zero
This is always executed
Example 2 –
# Python program to demonstrate finally
try:
k = 5//1 # No exception raised
print(k)
# intends to handle 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')
Output:
5
This is always executed
Python frequently causes programmers to fall in love due to the enhanced productivity it offers. The edit-test-debug cycle is extraordinarily quick because there is no compilation step. Python programs are simple to debug because a segmentation failure is never caused by a bug or incorrect input. Instead, the interpreter raises an exception when it finds a mistake. The interpreter generates a stack trace if the program doesn't catch the exception. Setting breakpoints, evaluating arbitrary expressions, inspecting local and global variables, stepping through the code one line at a time, and other features are all possible with a source-level debugger.
1. What does a try-except statement aim to achieve?
With the help of the try-except statement, a feature added by Microsoft to the C language, programs can take over an execution-ending program when certain circumstances arise.
2. What are the two try types used outside of Python?
In Python, there are two different sorts of errors: syntax errors and exceptions.
3. What is the “finally” keyword in Python?
No matter if there is an exception or not, the finally keyword is used to run code (used with exceptions - try.. catch statements).
4. Is Python's else a command?
The block of code that runs if the conditional phrase in the if statement evaluates to 0 or a FALSE value is included in an else statement. Following if, there can only be one possible else statement, which is an optional statement.
5. In Python, can an except block be empty?
A programmer may have intended to deal with the exception but never created the necessary code if the except block is empty.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...