The document discusses exception handling in Java. It defines exceptions as abnormal conditions that arise during runtime and disrupt normal program flow. There are three types of exceptions: checked exceptions which must be declared, unchecked exceptions which do not need to be declared, and errors which are rare and cannot be recovered from. The try, catch, and finally blocks are used to handle exceptions, with catch blocks handling specific exception types and finally blocks containing cleanup code.
The document discusses functions, modules, and how to modularize Python programs. It provides examples of defining functions, using parameters, returning values, and function scope. It also discusses creating modules, importing modules, and the difference between running a Python file as a module versus running it as the main script using the __name__ == "__main__" check. The key points are that functions help break programs into reusable and readable components, modules further help organize code, and the __name__ check allows code to run differently depending on how it is imported or run directly.
The document discusses Python exception handling. It describes three types of errors in Python: compile time errors (syntax errors), runtime errors (exceptions), and logical errors. It explains how to handle exceptions using try, except, and finally blocks. Common built-in exceptions like ZeroDivisionError and NameError are also covered. The document concludes with user-defined exceptions and logging exceptions.
This document provides an overview of file handling in Python. It discusses different file types like text files, binary files, and CSV files. It explains how to open, read, write, close, and delete files using functions like open(), read(), write(), close(), and os.remove(). It also covers reading and writing specific parts of a file using readline(), readlines(), seek(), and tell(). The document demonstrates how to handle binary files using pickle for serialization and deserialization. Finally, it shows how the os module can be used for file operations and how the csv module facilitates reading and writing CSV files.
This document discusses inheritance in object-oriented programming. It defines inheritance as establishing a link between classes that allows sharing and accessing properties. There are three types of inheritance: single, multilevel, and hierarchical. Single inheritance involves one parent and one child class, multilevel inheritance adds intermediate classes, and hierarchical inheritance has one parent and multiple child classes. The document provides examples of inheritance code in Java and demonstrates a program using inheritance with interfaces. It notes some limitations of inheritance in Java.
This is the presentation file about inheritance in java. You can learn details about inheritance and method overriding in inheritance in java. I think it's can help your. Thank you.
The document discusses the super keyword, final keyword, and interfaces in Java.
- The super keyword is used to refer to the immediate parent class and can be used with variables, methods, and constructors. It allows accessing members of the parent class from the child class.
- The final keyword can be used with variables, methods, and classes. It makes variables constant and prevents overriding of methods and inheritance of classes.
- Interfaces in Java allow achieving abstraction and multiple inheritance. They can contain only abstract methods and variables declared with default access modifiers. Classes implement interfaces to provide method definitions.
Modules allow grouping of related functions and code into reusable files. Packages are groups of modules that provide related functionality. There are several ways to import modules and their contents using import and from statements. The document provides examples of creating modules and packages in Python and importing from them.
The document provides information about shells in Linux operating systems. It defines what a kernel and shell are, explains why shells are used, describes different types of shells, and provides examples of shell scripting. The key points are:
- The kernel manages system resources and acts as an intermediary between hardware and software. A shell is a program that takes commands and runs them, providing an interface between the user and operating system.
- Shells are useful for automating tasks, combining commands to create new ones, and adding functionality to the operating system. Common shells include Bash, Bourne, C, Korn, and Tcsh.
- Shell scripts allow storing commands in files to automate tasks.
This document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows programs to gracefully handle runtime errors. The key aspects covered include the exception hierarchy, try-catch-finally syntax, checked and unchecked exceptions, and creating user-defined exceptions.
This document discusses implementation of inheritance in Java and C#. It covers key inheritance concepts like simple, multilevel, and hierarchical inheritance. It provides examples of inheritance in Java using keywords like extends, super, this. Interfaces are discussed as a way to achieve multiple inheritance in Java. The document also discusses implementation of inheritance in C# using concepts like calling base class constructors and defining virtual methods.
This document discusses the diamond problem that can occur with multiple inheritance in C++. Specifically, it shows an example where a class "four" inherits from classes "two" and "three", which both inherit from class "one". This results in two copies of the base class "one" being present in objects of class "four", leading to ambiguity when trying to access attributes from the base class. The document presents two ways to resolve this issue: 1) manual selection using scope resolution to specify which attribute to access, and 2) making the inheritance of the base class "one" virtual in classes "two" and "three", which ensures only one copy of the base class exists in class "four" objects. The virtual
This keyword is a reference variable that refer the current object in java.
This keyword can be used for call current class constructor.
http://www.tutorial4us.com/java/java-this-keyword
This presentation introduces Java packages, including system packages that are part of the Java API and user-defined packages. It discusses how packages organize related classes and interfaces, the structure of package names and directories, and how to create and access packages. Packages provide advantages like grouping related code, preventing name collisions, and improving reusability.
This document discusses interfaces in Java. It defines an interface as a blueprint of a class that defines static constants and abstract methods. Interfaces are used to achieve abstraction and multiple inheritance in Java. They represent an "is-a" relationship. There are three main reasons to use interfaces - for abstraction, to support multiple inheritance functionality, and to achieve loose coupling. The document provides examples of interfaces, such as a Printable interface and implementations in different classes. It also demonstrates multiple inheritance using interfaces and interface inheritance.
Templates allow functions and classes to operate on generic types in C++. There are two types of templates: class templates and function templates. Function templates are functions that can operate on generic types, allowing code to be reused for multiple types without rewriting. Template parameters allow types to be passed to templates, similar to how regular parameters pass values. When a class, function or static member is generated from a template, it is called template instantiation.
The document discusses exception handling in Java. It defines exceptions as runtime errors that occur during program execution. It describes different types of exceptions like checked exceptions and unchecked exceptions. It explains how to use try, catch, throw, throws and finally keywords to handle exceptions. The try block contains code that might throw exceptions. The catch block catches and handles specific exceptions. The finally block contains cleanup code that always executes regardless of exceptions. The document provides examples of exception handling code in Java.
The document discusses various concepts related to functions in Python including defining functions, passing arguments, default arguments, arbitrary argument lists, lambda expressions, function annotations, and documentation strings. Functions provide modularity and code reusability. Arguments can be passed by value or reference and default values are evaluated once. Keyword, arbitrary and unpacked arguments allow flexible calling. Lambda expressions define small anonymous functions. Annotations provide type metadata and docstrings document functions.
The document discusses inheritance in C++. It defines inheritance as deriving a class from another class, allowing code reuse and fast development. There are different types of inheritance in C++: single inheritance where a class inherits from one base class; multiple inheritance where a class inherits from more than one base class; multilevel inheritance where a derived class inherits from another derived class; hierarchical inheritance where multiple subclasses inherit from a single base class; and hybrid inheritance which combines different inheritance types. Examples of each inheritance type are provided in C++ code snippets.
Python modules allow code reuse and organization. A module is a Python file with a .py extension that contains functions and other objects. Modules can be imported and their contents accessed using dot notation. Modules have a __name__ variable that is set to the module name when imported but is set to "__main__" when the file is executed as a script. Packages are collections of modules organized into directories, with each directory being a package. The Python path defines locations where modules can be found during imports.
This document provides an overview of object-oriented programming concepts using C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. It also covers C++ specific topics like functions, arrays, strings, modular programming, and classes and objects in C++. The document is intended to introduce the reader to the fundamentals of OOP using C++.
This is presentation, that covers all the important topics related to strings in python. It covers storing, slicing, format, concatenation, modification, escape characters and string methods.
The file attatched also includes examples related to the slides shown.
Python modules allow for code reusability and organization. There are three main components of a Python program: libraries/packages, modules, and functions/sub-modules. Modules can be imported using import, from, or from * statements. Namespaces and name resolution determine how names are looked up and associated with objects. Packages are collections of related modules and use an __init__.py file to be recognized as packages by Python.
The document discusses the different types of operators in Java. It defines operators as symbols that operate on arguments to produce a result. It describes the different types of operands that operators can act on, such as numeric variables, primitive types, reference variables, and array elements. The document then lists and provides examples of the main types of operators in Java, including assignment, increment/decrement, arithmetic, bitwise, relational, logical, ternary, comma, and instanceof operators. It explains how each operator is used and provides simple code examples to illustrate their functionality.
Modules in Python allow organizing classes into files to make them available and easy to find. Modules are simply Python files that can import classes from other modules in the same folder. Packages allow further organizing modules into subfolders, with an __init__.py file making each subfolder a package. Modules can import classes from other modules or packages using either absolute or relative imports, and the __init__.py can simplify imports from its package. Modules can also contain global variables and classes to share resources across a program.
Functions allow programmers to organize and structure their code by splitting it into reusable blocks. There are two types of functions: built-in functions that are predefined in Python, and user-defined functions that programmers create. Functions make code easier to debug, test and maintain by dividing programs into separate, reusable parts. Functions can take arguments as input and return values. Function definitions do not alter the normal flow of a program's execution, but calling a function causes the program flow to jump to the function code and then return to pick up where it left off.
Python is an open source, general-purpose programming language that is easy to use and learn. It supports object-oriented programming and has extensive libraries for tasks like working with arrays and matrices. Python code is written in plain text and uses whitespace indentation to denote code blocks rather than curly braces. It supports common data types like integers, floats, and strings. Functions are defined using the def keyword and can take arguments. Conditionals, loops, exceptions, and other control flow structures allow Python code to respond dynamically to different situations.
Modules allow grouping of related functions and code into reusable files. Packages are groups of modules that provide related functionality. There are several ways to import modules and their contents using import and from statements. The document provides examples of creating modules and packages in Python and importing from them.
The document provides information about shells in Linux operating systems. It defines what a kernel and shell are, explains why shells are used, describes different types of shells, and provides examples of shell scripting. The key points are:
- The kernel manages system resources and acts as an intermediary between hardware and software. A shell is a program that takes commands and runs them, providing an interface between the user and operating system.
- Shells are useful for automating tasks, combining commands to create new ones, and adding functionality to the operating system. Common shells include Bash, Bourne, C, Korn, and Tcsh.
- Shell scripts allow storing commands in files to automate tasks.
This document discusses exception handling in Java. It defines exceptions as abnormal conditions that disrupt normal program flow. Exception handling allows programs to gracefully handle runtime errors. The key aspects covered include the exception hierarchy, try-catch-finally syntax, checked and unchecked exceptions, and creating user-defined exceptions.
This document discusses implementation of inheritance in Java and C#. It covers key inheritance concepts like simple, multilevel, and hierarchical inheritance. It provides examples of inheritance in Java using keywords like extends, super, this. Interfaces are discussed as a way to achieve multiple inheritance in Java. The document also discusses implementation of inheritance in C# using concepts like calling base class constructors and defining virtual methods.
This document discusses the diamond problem that can occur with multiple inheritance in C++. Specifically, it shows an example where a class "four" inherits from classes "two" and "three", which both inherit from class "one". This results in two copies of the base class "one" being present in objects of class "four", leading to ambiguity when trying to access attributes from the base class. The document presents two ways to resolve this issue: 1) manual selection using scope resolution to specify which attribute to access, and 2) making the inheritance of the base class "one" virtual in classes "two" and "three", which ensures only one copy of the base class exists in class "four" objects. The virtual
This keyword is a reference variable that refer the current object in java.
This keyword can be used for call current class constructor.
http://www.tutorial4us.com/java/java-this-keyword
This presentation introduces Java packages, including system packages that are part of the Java API and user-defined packages. It discusses how packages organize related classes and interfaces, the structure of package names and directories, and how to create and access packages. Packages provide advantages like grouping related code, preventing name collisions, and improving reusability.
This document discusses interfaces in Java. It defines an interface as a blueprint of a class that defines static constants and abstract methods. Interfaces are used to achieve abstraction and multiple inheritance in Java. They represent an "is-a" relationship. There are three main reasons to use interfaces - for abstraction, to support multiple inheritance functionality, and to achieve loose coupling. The document provides examples of interfaces, such as a Printable interface and implementations in different classes. It also demonstrates multiple inheritance using interfaces and interface inheritance.
Templates allow functions and classes to operate on generic types in C++. There are two types of templates: class templates and function templates. Function templates are functions that can operate on generic types, allowing code to be reused for multiple types without rewriting. Template parameters allow types to be passed to templates, similar to how regular parameters pass values. When a class, function or static member is generated from a template, it is called template instantiation.
The document discusses exception handling in Java. It defines exceptions as runtime errors that occur during program execution. It describes different types of exceptions like checked exceptions and unchecked exceptions. It explains how to use try, catch, throw, throws and finally keywords to handle exceptions. The try block contains code that might throw exceptions. The catch block catches and handles specific exceptions. The finally block contains cleanup code that always executes regardless of exceptions. The document provides examples of exception handling code in Java.
The document discusses various concepts related to functions in Python including defining functions, passing arguments, default arguments, arbitrary argument lists, lambda expressions, function annotations, and documentation strings. Functions provide modularity and code reusability. Arguments can be passed by value or reference and default values are evaluated once. Keyword, arbitrary and unpacked arguments allow flexible calling. Lambda expressions define small anonymous functions. Annotations provide type metadata and docstrings document functions.
The document discusses inheritance in C++. It defines inheritance as deriving a class from another class, allowing code reuse and fast development. There are different types of inheritance in C++: single inheritance where a class inherits from one base class; multiple inheritance where a class inherits from more than one base class; multilevel inheritance where a derived class inherits from another derived class; hierarchical inheritance where multiple subclasses inherit from a single base class; and hybrid inheritance which combines different inheritance types. Examples of each inheritance type are provided in C++ code snippets.
Python modules allow code reuse and organization. A module is a Python file with a .py extension that contains functions and other objects. Modules can be imported and their contents accessed using dot notation. Modules have a __name__ variable that is set to the module name when imported but is set to "__main__" when the file is executed as a script. Packages are collections of modules organized into directories, with each directory being a package. The Python path defines locations where modules can be found during imports.
This document provides an overview of object-oriented programming concepts using C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. It also covers C++ specific topics like functions, arrays, strings, modular programming, and classes and objects in C++. The document is intended to introduce the reader to the fundamentals of OOP using C++.
This is presentation, that covers all the important topics related to strings in python. It covers storing, slicing, format, concatenation, modification, escape characters and string methods.
The file attatched also includes examples related to the slides shown.
Python modules allow for code reusability and organization. There are three main components of a Python program: libraries/packages, modules, and functions/sub-modules. Modules can be imported using import, from, or from * statements. Namespaces and name resolution determine how names are looked up and associated with objects. Packages are collections of related modules and use an __init__.py file to be recognized as packages by Python.
The document discusses the different types of operators in Java. It defines operators as symbols that operate on arguments to produce a result. It describes the different types of operands that operators can act on, such as numeric variables, primitive types, reference variables, and array elements. The document then lists and provides examples of the main types of operators in Java, including assignment, increment/decrement, arithmetic, bitwise, relational, logical, ternary, comma, and instanceof operators. It explains how each operator is used and provides simple code examples to illustrate their functionality.
Modules in Python allow organizing classes into files to make them available and easy to find. Modules are simply Python files that can import classes from other modules in the same folder. Packages allow further organizing modules into subfolders, with an __init__.py file making each subfolder a package. Modules can import classes from other modules or packages using either absolute or relative imports, and the __init__.py can simplify imports from its package. Modules can also contain global variables and classes to share resources across a program.
Functions allow programmers to organize and structure their code by splitting it into reusable blocks. There are two types of functions: built-in functions that are predefined in Python, and user-defined functions that programmers create. Functions make code easier to debug, test and maintain by dividing programs into separate, reusable parts. Functions can take arguments as input and return values. Function definitions do not alter the normal flow of a program's execution, but calling a function causes the program flow to jump to the function code and then return to pick up where it left off.
Python is an open source, general-purpose programming language that is easy to use and learn. It supports object-oriented programming and has extensive libraries for tasks like working with arrays and matrices. Python code is written in plain text and uses whitespace indentation to denote code blocks rather than curly braces. It supports common data types like integers, floats, and strings. Functions are defined using the def keyword and can take arguments. Conditionals, loops, exceptions, and other control flow structures allow Python code to respond dynamically to different situations.
Types of errors include syntax errors, logical errors, and runtime errors. Exceptions are errors that occur during program execution. When an exception occurs, Python generates an exception object that can be handled to avoid crashing the program. Exceptions allow errors to be handled gracefully. The try and except blocks are used to catch and handle exceptions. Python has a hierarchy of built-in exceptions like ZeroDivisionError, NameError, and IOError.
This document discusses Python conditional statements, loops, functions, and lambda functions. It covers:
- If/else statements and conditional operators like ==, !=, <, > for comparisons
- While and for loops
- Defining functions with def and passing arguments, returning values
- Built-in functions like map() and filter()
- Anonymous lambda functions
- Nesting of if statements and for loops
Control structures functions and modules in python programmingSrinivas Narasegouda
The document discusses control structures, functions, modules, and Python's standard library. It covers topics like conditional branching, looping, functions, modules, packages, exceptions, strings, and more. Custom functions in Python include global functions, local functions, lambda functions, and methods. Modules allow packaging functionality and importing it into other code.
Dreamer Infotech offers the best python programming course in Faridabad, We offer an exceptional learning experience with expert faculty, Comprehensive Curriculum, Hands-on Projects, and 100% Placement Assistance. We also organize recruitment drives and connect you with leading companies seeking data science professionals. So Don’t miss out on the opportunity to upscale your skills with the best Python Training Institute in Faridabad.
This document provides information on Python code structures, including if/else statements, loops (while and for), functions, and arguments. It explains the basic syntax and usage of these structures. Key points covered include:
- How to write if/else statements and the use of conditions like ==, !=, <, >, etc.
- The syntax of while and for loops, and how to use break, continue, else blocks
- What functions are in Python and how to define them with def, pass arguments, and return values
- The basics of calling functions, optional arguments, and nested structures like if/else in loops
This document outlines the objectives and units of study for the course GE3151 Problem Solving and Python Programming. The course aims to teach algorithmic problem solving using Python conditionals, loops, functions, and data structures like lists, tuples and dictionaries. Students will learn to do input/output with files in Python. The 5 units cover computational thinking and problem solving, Python data types and statements, control flow and functions, lists, tuples and dictionaries, and files, modules and packages. Key concepts covered include algorithms, conditionals, iteration, functions, strings, lists, files operations like reading, writing and closing files, and exception handling.
Functions, Exception, Modules and Files
Functions: Difference between a Function and a Method, Defining a Function, Calling a Function, Returning Results from a Function, Returning Multiple Values from a Function, Functions are First Class Objects, Pass by Object Reference, Formal and Actual Arguments, Positional Arguments, Keyword Arguments, Default Arguments, Variable Length Arguments, Local and Global Variables, The Global Keyword, Passing a Group of Elements to a Function, Recursive Functions, Anonymous Functions or Lambdas (Using Lambdas with filter() Function, Using Lambdas with map() Function, Using Lambdas with reduce() Function), Function Decorators, Generators, Structured Programming, Creating our Own Modules in Python, The Special Variable __name__
Exceptions: Errors in a Python Program (Compile-Time Errors, Runtime Errors, Logical Errors),Exceptions, Exception Handling, Types of Exceptions, The Except Block, The assert Statement, UserDefined Exceptions, Logging the Exceptions
20%
Files: Files, Types of Files in Python, Opening a File, Closing a File, Working with Text Files Containing Strings, Knowing Whether a File Exists or Not, Working with Binary Files, The with Statement, Pickle in Python, The seek() and tell() Methods, Random Accessing of Binary Files, Random Accessing of Binary Files using mmap, Zipping and Unzipping Files, Working with Directories, Running Other Programs from Python Program
Python is an interpreted, general-purpose, high-level programming language. It allows programmers to define functions for reusing code and scoping variables within functions. Key concepts covered include objects, expressions, conditionals, loops, modules, files, and recursion. Functions can call other functions, allowing for modular and reusable code.
Python is a versatile, object-oriented programming language that can be used for web development, data analysis, and more. It has a simple syntax and is easy to read and learn. Key features include being interpreted, dynamically typed, supporting functional and object-oriented programming. Common data types include numbers, strings, lists, dictionaries, tuples, and files. Functions and classes can be defined to organize and reuse code. Regular expressions provide powerful string manipulation. Python has a large standard library and is used widely in areas like GUIs, web scripting, AI, and scientific computing.
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...ijscai
International Journal on Soft Computing, Artificial Intelligence and Applications (IJSCAI) is an open access peer-reviewed journal that provides an excellent international forum for sharing knowledge and results in theory, methodology and applications of Artificial Intelligence, Soft Computing. The Journal looks for significant contributions to all major fields of the Artificial Intelligence, Soft Computing in theoretical and practical aspects. The aim of the Journal is to provide a platform to the researchers and practitioners from both academia as well as industry to meet and share cutting-edge development in the field.
Impurities of Water and their Significance.pptxdhanashree78
Impart Taste, Odour, Colour, and Turbidity to water.
Presence of organic matter or industrial wastes or microorganisms (algae) imparts taste and odour to water.
Presence of suspended and colloidal matter imparts turbidity to water.
How Binning Affects LED Performance & Consistency.pdfMina Anis
🔍 What’s Inside:
📦 What Is LED Binning?
• The process of sorting LEDs by color temperature, brightness, voltage, and CRI
• Ensures visual and performance consistency across large installations
🎨 Why It Matters:
• Inconsistent binning leads to uneven color and brightness
• Impacts brand perception, customer satisfaction, and warranty claims
📊 Key Concepts Explained:
• SDCM (Standard Deviation of Color Matching)
• Recommended bin tolerances by application (e.g., 1–3 SDCM for retail/museums)
• How to read bin codes from LED datasheets
• The difference between ANSI/NEMA standards and proprietary bin maps
🧠 Advanced Practices:
• AI-assisted bin prediction
• Color blending and dynamic calibration
• Customized binning for high-end or global projects
Rearchitecturing a 9-year-old legacy Laravel application.pdfTakumi Amitani
An initiative to re-architect a Laravel legacy application that had been running for 9 years using the following approaches, with the goal of improving the system’s modifiability:
・Event Storming
・Use Case Driven Object Modeling
・Domain Driven Design
・Modular Monolith
・Clean Architecture
This slide was used in PHPxTKY June 2025.
https://phpxtky.connpass.com/event/352685/
David Boutry - Mentors Junior DevelopersDavid Boutry
David Boutry is a Senior Software Engineer in New York with expertise in high-performance data processing and cloud technologies like AWS and Kubernetes. With over eight years in the field, he has led projects that improved system scalability and reduced processing times by 40%. He actively mentors aspiring developers and holds certifications in AWS, Scrum, and Azure.
Third Review PPT that consists of the project d etails like abstract.Sowndarya6
CyberShieldX is an AI-driven cybersecurity SaaS web application designed to provide automated security analysis and proactive threat mitigation for business websites. As cyber threats continue to evolve, traditional security tools like OpenVAS and Nessus require manual configurations and lack real-time automation. CyberShieldX addresses these limitations by integrating AI-powered vulnerability assessment, intrusion detection, and security maintenance services. Users can analyze their websites by simply submitting a URL, after which CyberShieldX conducts an in-depth vulnerability scan using advanced security tools such as OpenVAS, Nessus, and Metasploit. The system then generates a detailed report highlighting security risks, potential exploits, and recommended fixes. Premium users receive continuous security monitoring, automatic patching, and expert assistance to fortify their digital infrastructure against emerging threats. Built on a robust cloud infrastructure using AWS, Docker, and Kubernetes, CyberShieldX ensures scalability, high availability, and efficient security enforcement. Its AI-driven approach enhances detection accuracy, minimizes false positives, and provides real-time security insights. This project will cover the system's architecture, implementation, and its advantages over existing security solutions, demonstrating how CyberShieldX revolutionizes cybersecurity by offering businesses a smarter, automated, and proactive defense mechanism against ever-evolving cyber threats.
May 2025: Top 10 Read Articles Advanced Information Technologyijait
International journal of advanced Information technology (IJAIT) is a bi monthly open access peer-reviewed journal, will act as a major forum for the presentation of innovative ideas, approaches, developments, and research projects in the area advanced information technology applications and services. It will also serve to facilitate the exchange of information between researchers and industry professionals to discuss the latest issues and advancement in the area of advanced IT. Core areas of advanced IT and multi-disciplinary and its applications will be covered during the conferences.
Strength of materials (Thermal stress and strain relationships)pelumiadigun2006
Ad
Exception handling and function in python
1. Exception Handling in Python
A Python program terminates as soon
as it encounters an error. In Python, an
error can be a syntax error or an
exception
Dr.T.Maragatham
Kongu Engineering College,
Erode
2. Error – Syntax Error
• Syntax Error:
• Syntax errors occur when the parser detects an incorrect statement.
• Most syntax errors are typographical , incorrect indentation, or incorrect
arguments.
• Example:
• i=1
• while i<5
• print(i)
• i=i+1
• Shows:
• File "<string>", line 2
• while i<5 # : missing
• ^
• SyntaxError: invalid syntax
3. Error - Exception
• Exception: Even if a statement or expression is
syntactically in-correct, it may cause an error when an
attempt is made to execute it. Errors detected during
execution are called exceptions .
• Example:
• x=(10/0) or x=(10%0)
• print(x)
• Shows:
• Traceback (most recent call last):
• File "<string>", line 1, in <module>
• ZeroDivisionError: division by zero
4. • Exceptions come in different types, and the type
is printed as part of the message:
• the types in the example are ZeroDivisionError,
NameError and TypeError.
• The string printed as the exception type is the
name of the built-in name for the exception that
occurred.
6. The try block will generate an
exception, because x is not defined:
• try:
• print(x)
• except:
• print("An exception occurred")
• Since the try block raises an error, the except
block will be executed.
• Without the try block, the program will crash and
raise an error:
7. Many Exceptions
• You can define as many exception blocks as you want.
• Example
• Print one message if the try block raises a NameError and another
for other errors:
• #The try block will generate a NameError, because x is not defined:
• try:
• print(x)
• except NameError:
• print("Variable x is not defined")
• except:
• print("Something else went wrong")
8. Else
• You can use the else keyword to define a block of code to
be executed if no errors were raised:
• Example:
• #The try block does not raise any errors, so the else block is
executed:
• try:
• print("Hello")
• except:
• print("Something went wrong")
• else:
• print("Nothing went wrong")
9. Finally
• The finally block, if specified, will be executed regardless if
the try block raises an error or not.
• Example:
• #The finally block gets executed no matter if the try block
raises any errors or not:
• try:
• print(x)
• except:
• print("Something went wrong")
• finally:
• print("The 'try except' is finished")
10. • Here is an example of an incorrect use:
• d={}
• try:
• x = d[5]
• except LookupError:
• # WRONG ORDER
• print("Lookup error occurred")
• except KeyError:
• print("Invalid key used")
11. • #The try block will raise an error when trying to write
to a read-only file:
• try:
• f = open("demofile.txt")
• f.write("Lorum Ipsum")
• except:
• print("Something went wrong when writing to the
file")
• finally:
• f.close()
12. • Raise an exception
• As a Python developer you can choose to throw an
exception if a condition occurs.
• To throw (or raise) an exception, use the raise keyword.
• Example
• Raise an error and stop the program if x is lower than
0:
• x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
13. • raise SomeException: throws an exception (a
specific type of ball, like throwing only tennis
balls).
• except: catches all exceptions (regardless of
type).
14. The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print
to the user.
• Example
• Raise a TypeError if x is not an integer:
• x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
15. Python Custom Exceptions
• Python has numerous built-in exceptions that
force your program to output an error when
something in the program goes wrong.
• However, sometimes you may need to create
your own custom exceptions that serve your
purpose.
16. Creating Custom Exceptions
• Users can define custom exceptions by
creating a new class.
• This exception class has to be derived, either
directly or indirectly, from the built-in
Exception class.
• Most of the built-in exceptions are also
derived from this class.
17. Throw an Exception using “raise”
• name="Malar"
• age = 15
• print(name)
• print(age)
• if int(age)>17:
• print("You can vote")
• else:
• print("You can't vote")
• raise ValueError("Vote when you tern 18 year old")
18. Throw a Custom Exception
• class Age_Restriction(ValueError):
• pass
• name="Malar"
• age = 15
• print(name)
• print(age)
• if int(age)>17:
• print("You can vote")
• else:
• print("You can't vote")
• raise Age_Restriction("Vote when you tern 18 year old")
•
19. class exceptionName(baseException):
pass
• One use of custom exceptions is to break out
of deeply nested loops.
• For example, if we have a table object that
holds records (rows),
• which hold fields (columns),
• which have multiple values (items),
• we could search for a particular value
20. • found = False
• for row, record in enumerate(table):
• for column, field in enumerate(record):
• for index, item in enumerate(field):
• if item == target:
• found = True
• break
• if found:
• break
• if found:
• break
• if found:
• print("found at ({0}, {1}, {2})".format(row, column, index))
• else:
• print("not found")
21. • from prettytable import PrettyTable
list1=[“Anu",”18",“98"]
list2=[“Siva",“19",“96"]
table=PrettyTable([‘Name',’Age‘,’Mark’])
for x in range(0,3):
table.add_row(list1[x],list2[x])
print(table)
23. • class FoundException(Exception):
• pass
• found = False
• try:
• for row, record in enumerate(table):
• for column, field in enumerate(record):
• for index, item in enumerate(field):
• if item == target:
• raise FoundException()
• except FoundException:
• print("found at ({0}, {1}, {2})".format(row, column, index))
• else:
• print("not found")
24. Functions
• A function is a block of code which only runs
when it is called.
• You can pass data, known as parameters, into
a function.
• A function can return data as a result.
25. • Creating a Function
• In Python a function is defined using
the def keyword:
• Calling a Function
• To call a function, use the function name
followed by parenthesis:
• Arguments
• Information can be passed into functions as
arguments.
28. Arbitrary Arguments, *args
• If you do not know how many arguments that
will be passed into your function,
• add a * before the parameter name in the
function definition.
• def my_function(*kids):
• print("The youngest child is " + kids[2])
• my_function(“Aradhana", “Diya", “Roshan")
29. Keyword Arguments
• You can also send arguments with
the key = value syntax.
• This way the order of the arguments does not
matter.
• def my_function(child3, child2, child1):
• print("The youngest child is " + child3)
• my_function(child1 = “Aradhana", child2 =
“Diya", child3 = “Roshan")
30. Default Parameter Value
• The following example shows how to use a default parameter
value.
• If we call the function without argument, it uses the default
value:
• def my_function(country = "Norway"):
• print("I am from " + country)
• my_function("Sweden")
• my_function("India")
• my_function()
• my_function("Brazil")
31. Passing a List as an Argument
• You can send any data types of argument to a
function (string, number, list, dictionary etc.),
and it will be treated as the same data type
inside the function.
• def my_function(food):
• for x in food:
• print(x)
• fruits = ["apple", "banana", "cherry"]
• my_function(fruits)
32. Return Values
• To let a function return a value, use
the return statement:
• def my_function(x):
• return 5 * x
• print(my_function(3))
• print(my_function(5))
• print(my_function(9))
33. The pass Statement
• function definitions cannot be empty, but if
you for some reason have
a function definition with no content, put in
the pass statement to avoid getting an error.
• def myfunction():
pass
34. Recursion
• Python also accepts function recursion, which
means a defined function can call itself.
• def tri_recursion(k):
• if(k > 0):
• result = k + tri_recursion(k - 1)
• else:
• result = 0
• return result
• print("nnRecursion Example Results")
• print(tri_recursion(6))
35. Pass by reference vs value
• All parameters (arguments) in the Python
language are passed by reference.
• It means if you change what a parameter
refers to within a function, the change also
reflects back in the calling function.
36. • def changeme( mylist ):
• #"This changes a passed list into this function"
• mylist.append([1,2,3,4])
• print("Values inside the function: ", mylist)
• return
• # Now you can call changeme function
• mylist = [10,20,30]
• changeme( mylist )
• print("Values outside the function: ", mylist)
37. • # Function definition is here
• def changeme( mylist ):
• mylist = [1,2,3,4]; # This would assign new
reference in mylist
• print "Values inside the function: ", mylist
• # Now you can call changeme function
• mylist = [10,20,30];
• changeme( mylist );
• print "Values outside the function: ", mylist
38. Scope of Variables
• The scope of a variable determines the
portion of the program where you can access
a particular identifier.
• There are two basic scopes of variables in
Python −
• Global variables
• Local variables
39. Global vs. Local variables
• Variables that are defined inside a function
body have a local scope, and those defined
outside have a global scope.
• local variables can be accessed only inside the
function in which they are declared, whereas
global variables can be accessed throughout
the program body by all functions.
40. • total = 0; # This is global variable.
• # Function definition is here
• def sum( arg1, arg2 ):
• # Add both the parameters and return them."
• total = arg1 + arg2; # Here total is local variable.
• print("Inside the function local total : ", total)
• return total
• # Now you can call sum function
• sum( 10, 20 )
• print("Outside the function global total : ", total)
41. Lambda Forms:
• In Python, small anonymous (unnamed)
functions can be created with lambda
keyword.
• A lambda function in python has the following
syntax.
• lambda arguments: expression
• Lambda functions can have any number of
arguments but only one expression.
• The expression is evaluated and returned
43. • def average(x, y):
• return (x + y)/2
• print(average(4, 3))
• may also be defined using lambda
• print((lambda x, y: (x + y)/2)(4, 3))
• double = lambda x,y:((x+y /2))
• print(double(4,3))
44. Python Documentation Strings
• a string literal is used for
documenting a module, function, class, or m
ethod.
• You can access string literals by __doc__
(notice the double underscores)
• (e.g. my_function.__doc__)
45. Docstring Rules :
• String literal literals must be enclosed with a
triple quote. Docstring should be informative
• The first line may briefly describe the object's
purpose. The line should begin with a capital
letter and ends with a dot.
• If a documentation string is a muti-line string
then the second line should be blank followed
by any detailed explanation starting from the
third line.
46. • def avg_number(x, y):
• """Calculate and Print Average of two
Numbers.
•
• Created on 29/12/2012. python-docstring-
example.py
• """
• print("Average of ",x," and ",y, " is ",(x+y)/2)
• print(avg_number.__doc__)