Error in Python
Error in Python
In Python, errors are categorized into three main types: syntax errors, runtime errors, and logical errors.
01-11-2023
Exception Handling
Scenario: Temperature Converter
Imagine you are building a temperature converter application. Users can input
temperatures in either Celsius or Fahrenheit, and the application will convert the input to
the other temperature scale. To ensure accurate conversion, you need to handle
scenarios where the user enters invalid input, such as non-numeric characters or out-of-
range temperatures.
01-11-2023
if celsius < -273.15:
raise ValueError("Celsius temperature cannot be below -273.15°C (absolute zero)")
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
except (ValueError, TypeError):
raise ValueError("Invalid input. Please enter a valid number.")
def fahrenheit_to_celsius(fahrenheit):
try:
fahrenheit = float(fahrenheit)
if fahrenheit < -459.67:
raise ValueError("Fahrenheit temperature cannot be below -459.67°F (absolute zero)")
celsius = (fahrenheit - 32) * 5/9
return celsius
except (ValueError, TypeError):
raise ValueError("Invalid input. Please enter a valid number.")
celsius_result = celsius_to_fahrenheit(celsius_input)
print(f"{celsius_input}°C is {celsius_result:.2f}°F")
fahrenheit_result = fahrenheit_to_celsius(fahrenheit_input)
print(f"{fahrenheit_input}°F is {fahrenheit_result:.2f}°C")
invalid_result = celsius_to_fahrenheit(invalid_input)
print(invalid_result) # This should raise a ValueError
except ValueError as e:
print(f"Temperature Conversion Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
01-11-2023
Exception Handling
If you have some suspicious code that may raise an exception, you can defend your program by placing the
suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which
handles the problem as elegantly as possible.
Syntax:
try:
# Code that may raise an exception
else:
# Code to execute if no exceptions were raised (optional)
finally:
# Code to execute regardless of exceptions (optional)
01-11-2023
Exception Handling: Examples
try:
result = 10 / 0 # Attempt to divide by zero try:
except ZeroDivisionError as e: num = int("abc") # Attempt to convert a non-numeric string
print(f"ZeroDivisionError: {e}") to an integer
else: except ValueError as e:
print("Division success ful") print(f"Error: {e}")
finally:
print("Cleaning up resources")
try:
result = 10 + "5" # Attempt to add an integer and a string
except TypeError as e:
try: print(f"Error: {e}")
my_list = [1, 2, 3]
item = my_list[5] # Attempt to access an out-of-range index
except IndexError as e:
print(f"Error: {e}")
01-11-2023
Exceptions Examples
Exception Name Exception Description
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
EOFError Raised when there is no input from either the raw_input() or input()
ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been
assigned to it.
EnvironmentError Base class for all exceptions that occur outside the Python environment.
IOError Raised when an input/ output operation fails, such as the print statement or the open()
function when trying to open a file that does not exist.
01-11-2023
Exceptions Examples
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.
SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the
Python interpreter does not exit.
SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code,
causes the interpreter to exit.
TypeError Raised when an operation or function is attempted that is invalid for the specified data type.
ValueError Raised when the built-in function for a data type has the valid type of arguments, but the
arguments have invalid values specified.
RuntimeError Raised when a generated error does not fall into any category.
NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is
not actually implemented.
01-11-2023
Exception Handling: Examples
a = [2, 3, 4]
try:
print("element_1 = %d" %(a[1]))
print("element_2 = %d" %(a[3]))
except IndexError:
print("out of index occurred")
except ValueError:
print ("The argument does not contain numbers\n")
01-11-2023
Thank You
01-11-2023 9
Modules and Namespaces
Scenario: Calculator cum Unit Converter
01-11-2023
Modules and Namespaces
In Python, a module is a file that contains Python code, including variables, functions, and classes. Modules are used to
organize code into reusable, structured units. These units can be imported and used in other Python scripts or programs,
allowing you to encapsulate and reuse code effectively.
Key Advantages:
•Simplicity: Rather than focusing on the entire problem at hand, a module typically focuses on one relatively small
portion of the problem. If you’re working on a single module, you’ll have a smaller problem domain to wrap your
head around.
•Maintainability: You may even be able to make changes to a module without having any knowledge of the
application outside that module. This makes it more viable for a team of many programmers to work collaboratively
on a large application.
•Reusability: Functionality defined in a single module can be easily reused (through an appropriately defined
interface) by other parts of the application. This eliminates the need to duplicate code.
•Scoping: Modules typically define a separate namespace, which helps avoid collisions between identifiers in
different areas of a program.
01-11-2023
Built-In Modules
Built-in modules in Python are pre-existing modules that are part of the Python standard library. These modules come
included with Python, so you don't need to install them separately. These can be used to perform common operations,
access system resources, handle data, work with the operating system, and more.
Examples:
• math: Provides mathematical functions and constants like trigonometric functions, logarithms, and more.
• os: Offers a way to interact with the operating system, including file and directory operations.
• datetime: Allows you to work with dates and times, providing classes for date and time manipulation.
• re (regular expressions): Supports regular expression pattern matching.
• sqlite3: Allows interaction with SQLite databases.
• sys: Provides access to system-specific parameters and functions, including command-line arguments.
01-11-2023
Built-In Modules Examples
import math import os
# Format a date
formatted_date = current_datetime.strftime("%Y-%m-%d
%H:%M:%S")
print(formatted_date)
01-11-2023
Module & Namespaces
Module 1: Module 2:
• A namespace, is a
mapping that maps def common_function(): def common_function():
variable names to return "Function in module1" return "Function in module2"
their corresponding
objects (values).
• A name clash is when from module1 import *
two otherwise distinct from module2 import *
entities with the same
identifier become part result1 = common_function()
of the same scope. result2 = common_function()
• Namespaces provide a
means for resolving print("Result from module1:", result1)
such problems. print("Result from module2:", result2)
01-11-2023
Modules and Namespaces: Use of Fully Qualified Function Names
• Two instances of identifier double, each defined in their own module, are
distinguished by being fully qualified with the name of the module in which
each is defined: module1.double and module2.double.
• Example:
Example:
Import From Module
• You can choose to import only parts from a module, by using the from keyword.
• Syntax: from modulename import something
• Something can be a list of identifiers, a single renamed identifier, or an asterisk:
person1 = {
"name": "John", Note: When using import modulename, the namespace
"age": 36, of the imported module does not become part of the
"country": "Norway" namespace of the importing module.
}
Note: With the from-import form of import, imported identifiers become part of the importing module’s namespace.
Because of the possibility of name clashes, import modulename is the preferred form of import in Python.
Import From Module: Example
Module Private Variables
• In Python, all the variables in a module are “public,” with the convention that
variables beginning with an two underscores are intended to be private.
• Public is accessible by any other module that imports it, whereas private is not
accessible in form of from modulename import *.
• Python does not provide any means for preventing access to variables or other
entities meant to be private.
• There is a convention that names beginning with two underscores (__) are
intended to be private.
Example: # mymodule
__def greeting(name):
print("Hello, " + name)
Types of Namespaces
Local Namespace (or Function Namespace):
This namespace contains local variables and parameters defined within a function or method.
It is created when a function is called and destroyed when the function exits.
Global Namespace:
This namespace contains global variables and functions defined at the top level of a module.
It is created when a module is imported and exists until the program terminates.
Built-in Namespace:
This namespace contains all the built-in functions, exceptions, and objects provided by Python itself.
It is always available and doesn't need to be imported.
01-11-2023
Accessing Namespaces
>>> type(globals())
>>> dir(__builtins__)
<class 'dict'>
['ArithmeticError', 'AssertionError', 'AttributeError',
'BaseException','BlockingIOError', 'BrokenPipeError',
>>> globals()
'BufferError',
{'__name__': '__main__', '__doc__': None, '__package__':
'BytesWarning', 'ChildProcessError',
None,
'ConnectionAbortedError',
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'ConnectionError', 'ConnectionRefusedError',
'__spec__': None,
'ConnectionResetError',
'__annotations__': {}, '__builtins__': <module 'builtins'
(built-in)>}
01-11-2023 28