book solution : Exception Handling in Python

Table of Content :

       1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement

.
       2. When are the following built-in exceptions raised? Give examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError

3. What is the use of a raise statement? Write a code to accept two numbers and display the quotient. Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).

4. Use assert statement in Question No. 3 to test the division expression in the program.

5. Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exception

6. Explain catching exceptions using try and except block

Q1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement.

Answer : – The statement is true, and it highlights the difference between syntax errors and exceptions in programming.

In programming, syntax errors occur when the code violates the language’s syntax rules. For example, forgetting to close a parenthesis or using an undefined variable. These errors are detected by the compiler or interpreter during the compilation or interpretation phase and prevent the code from running. Thus, every syntax error is an exception because it breaks the normal flow of the program execution.

On the other hand, exceptions are errors that occur during the execution of a program. These errors are not necessarily caused by syntax violations, but rather by unexpected events, such as a division by zero, an invalid file operation, or a network error. Exceptions can be handled by the program to prevent it from crashing, and they may or may not be caused by syntax errors. Therefore, every exception cannot be a syntax error because an exception can be caused by a logical error or an external event that is not related to syntax violations.

In summary, every syntax error is an exception because it interrupts the normal program flow, but every exception cannot be a syntax error because exceptions can be caused by a wide range of unexpected events, not necessarily syntax violations.

Page : 1           2           3           4

Chapter 1 : Exception Handling in Python theory

Syntax Errors in python
Syntax errors in Python are errors that occur when the interpreter encounters code that violates the rules of the Python language syntax. In other words, syntax errors occur when there is a mistake in the way the code is written, such as a missing colon or parentheses.

Here’s an example of a syntax error:

bash
Copy code
print(“Hello, world!”
This code is missing a closing parentheses for the print function, which results in a syntax error. When you run this code, you will see an error message that looks something like this:

arduino
Copy code
File “<stdin>”, line 1
print(“Hello, world!”
^
SyntaxError: unexpected EOF while parsing
The error message indicates that the interpreter encountered an unexpected end of file while trying to parse the code.

Other examples of syntax errors include:

Missing colon after an if statement
Missing parentheses around function arguments
Using an invalid keyword as a variable name
Syntax errors are usually easy to fix once you identify them. The error message will give you a clue as to where the error is located in your code.

Page : 1           2           3           4

12 Class- Exception Handling in Python objective

Q1. What is the purpose of using Exception Handling in Python?

a) To prevent the occurrence of errors in the program
b) To ignore the errors that occur in the program
c) To identify and handle errors that occur in the program
d) To stop the execution of the program when errors occur

Answer: c) To identify and handle errors that occur in the program

Explanation: Exception handling is used to identify and handle errors that occur during the execution of a program. By using exception handling, we can gracefully handle errors and prevent the program from crashing.

Q2. What is an Exception in Python?

a) An error that occurs during the execution of a program
b) A warning message that is displayed during the execution of a program
c) A syntax error that occurs when writing code in Python
d) A logical error that occurs when the program does not produce the expected output

Answer: a) An error that occurs during the execution of a program

Explanation: An exception is an error that occurs during the execution of a program. It is caused by something unexpected happening during the execution of a program, such as a divide by zero error, a file not found error, or a type error.

Q3. What is the syntax for handling exceptions in Python?

a) try-except
b) try-catch
c) try-exception
d) try-finally

Answer: a) try-except

Explanation: The syntax for handling exceptions in Python is try-except. The try block contains the code that might raise an exception, and the except block contains the code that will handle the exception if it occurs.

Q4. Which of the following is NOT a type of built-in exception in Python?

a) ZeroDivisionError
b) TypeError
c) FileNotFoundError
d) DatabaseError

Answer: d) DatabaseError

Explanation: While ZeroDivisionError, TypeError, and FileNotFoundError are all built-in exceptions in Python, DatabaseError is not. DatabaseError is a base class for exceptions that occur when interacting with a database, but it is not a built-in exception in Python.

Q5. What is the purpose of the else block in Python exception handling?

a) To handle the exception that occurred in the try block
b) To execute code if no exception occurred in the try block
c) To execute code after the finally block has executed
d) To ignore the exception that occurred in the try block

Answer: b) To execute code if no exception occurred in the try block

Explanation: The else block in Python exception handling is used to execute code if no exception occurred in the try block. If an exception occurs in the try block, the code in the else block will not be executed. The else block is optional and can be omitted if it is not needed.

Q6. What is the purpose of the finally block in Python exception handling?

a) To handle the exception that occurred in the try block
b) To execute code if no exception occurred in the try block
c) To execute code after the try and except blocks have executed, regardless of whether an exception occurred or not
d) To ignore the exception that occurred in the try block

Answer: c) To execute code after the try and except blocks have executed, regardless of whether an exception occurred or not

Explanation: The finally block in Python exception handling is used to execute code after the try and except blocks have executed, regardless of whether an exception occurred or not. This is useful for cleaning up resources, closing files, and releasing locks. The finally block is optional and can be omitted if it is not needed.

Q7. Can multiple except blocks be used in a single try block in Python?

a) No, only one except block can be used in a try block
b) Yes, multiple except blocks can be used in a try block to handle different types of exceptions
c) Yes, but each except block must be enclosed in its own try block
d) No, each exception must be handled separately in a separate function

Answer: b) Yes, multiple except blocks can be used in a try block to handle different types of exceptions

Explanation: Multiple except blocks can be used in a single try block in Python to handle different types of exceptions. Each except block will catch a specific type of exception, and the code in that block will be executed if that type of exception occurs.

Q8. What is the purpose of the raise statement in Python?

a) To raise an exception manually
b) To handle an exception that occurred in the program
c) To ignore an exception that occurred in the program
d) To exit the program when an exception occurs

Answer: a) To raise an exception manually

Explanation: The raise statement in Python is used to raise an exception manually. This is useful when you want to handle a specific error condition in your program and raise an exception to signal that condition. When a raise statement is executed, it causes the specified exception to be raised, which can then be handled by an except block.

Q9. What is the difference between a try-except block and a try-finally block in Python?

a) A try-except block is used to handle exceptions, while a try-finally block is used for cleanup code
b) A try-except block is used for cleanup code, while a try-finally block is used to handle exceptions
c) A try-except block is used to handle exceptions, while a try-finally block is used to execute code after the try and except blocks have executed
d) There is no difference between a try-except block and a try-finally block in Python

Answer: c) A try-except block is used to handle exceptions, while a try-finally block is used to execute code after the try and except blocks have executed

Explanation: The try-except block in Python is used to handle exceptions that may occur during the execution of a program, while the try-finally block is used to execute code after the try and except blocks have executed, regardless of whether an exception occurred or not. The try-finally block is useful for cleanup code, such as releasing resources or closing files, that needs to be executed regardless of whether an exception occurred.

 

Q10. What is the recommended approach to handling exceptions in Python?

a) Ignoring exceptions and letting the program crash if an error occurs
b) Using try-except blocks to handle exceptions as they occur
c) Using try-finally blocks to handle exceptions as they occur
d) Using if statements to check for potential

Q11. What is the syntax for raising a custom exception in Python?

a) raise Exception(“Custom Exception”)
b) raise custom_exception(“Custom Exception”)
c) raise custom_exception
d) custom_exception(“Custom Exception”)

Answer: b) raise custom_exception(“Custom Exception”)

Explanation: To raise a custom exception in Python, you need to define a new exception class that inherits from the built-in Exception class. You can then raise an instance of your custom exception class using the raise statement, passing a message string as an argument. The syntax for raising a custom exception is: raise custom_exception(“Custom Exception”).

Q12. What is the purpose of the else block in Python exception handling?

a) To handle the exception that occurred in the try block
b) To execute code if no exception occurred in the try block
c) To execute code after the try and except blocks have executed, regardless of whether an exception occurred or not
d) To ignore the exception that occurred in the try block

Answer: b) To execute code if no exception occurred in the try block

Explanation: The else block in Python exception handling is used to execute code if no exception occurred in the try block. This block is optional and follows all the except blocks. If no exception occurred in the try block, the code in the else block will be executed. If an exception occurred, the code in the else block will be skipped.

Q13. What is the purpose of the assert statement in Python?

a) To raise an exception if a condition is not true
b) To handle an exception that occurred in the program
c) To ignore an exception that occurred in the program
d) To exit the program when an exception occurs

Answer: a) To raise an exception if a condition is not true

Explanation: The assert statement in Python is used to raise an exception if a condition is not true. The syntax of the assert statement is: assert condition, message. If the condition is true, the program continues to execute normally. If the condition is false, an AssertionError is raised with the specified error message.

Q14. What is the purpose of the traceback module in Python?

a) To handle exceptions that occur in the program
b) To display a traceback of the current call stack
c) To ignore exceptions that occur in the program
d) To exit the program when an exception occurs

Answer: b) To display a traceback of the current call stack

Explanation: The traceback module in Python is used to display a traceback of the current call stack. A traceback is a report of the function calls that led up to an exception. It shows the line of code that caused the exception and the line of code that called that line, and so on, all the way back to the top-level of the program. The traceback module can be used to display this information in a human-readable format.

Q15. What is the purpose of the finally block in Python exception handling?

a) To handle the exception that occurred in the try block
b) To execute code if no exception occurred in the try block
c) To execute code after the try and except blocks have executed, regardless of whether an exception occurred or not
d) To ignore the exception that occurred in the try block

Answer: c) To execute code after the try and except blocks have executed, regardless of whether an exception occurred or not

Explanation: The finally block in Python exception handling is used to execute code after the try and except blocks have executed, regardless of whether an exception occurred or not. This block is optional and follows all the except blocks. The code in the finally block is executed even if an exception occurred in the try block and was handled by an except block, or if the try block executed successfully with no exceptions. The purpose of the finally block is to ensure that certain cleanup actions, such as closing a file or a network connection, are always performed.

Q16. Which of the following is an example of a built-in exception in Python?

a) FileExistsError
b) FileNotFoundError
c) ZeroDivisionError
d) TypeError

Answer: c) ZeroDivisionError

Explanation: ZeroDivisionError is an example of a built-in exception in Python. It is raised when attempting to divide by zero. The other options are also examples of built-in exceptions in Python, but they are related to file operations and data types, respectively.

Q17. What is the purpose of the except block in Python exception handling?

a) To handle the exception that occurred in the try block
b) To execute code if no exception occurred in the try block
c) To execute code after the try and except blocks have executed, regardless of whether an exception occurred or not
d) To ignore the exception that occurred in the try block

Answer: a) To handle the exception that occurred in the try block

Explanation: The except block in Python exception handling is used to handle the exception that occurred in the try block. This block is optional and follows the try block. It specifies the type of exception to catch and what code to execute when the exception occurs. Multiple except blocks can be used to catch different types of exceptions. If no exception occurred in the try block, the code in the except block will be skipped.

Q18. Which of the following is NOT true about Python exception handling?

a) It is used to handle unexpected errors that occur during program execution
b) It uses try, except, and finally blocks to manage exceptions
c) It is not recommended to catch and handle all exceptions in a single except block
d) It is recommended to use the assert statement to handle expected errors in the program

Answer: d) It is recommended to use the assert statement to handle expected errors in the program

Explanation: The assert statement in Python is used to raise an exception if a condition is not true. It is typically used to check for programming errors, not expected errors. Python exception handling is used to handle unexpected errors that occur during program execution. It uses try, except, and finally blocks to manage exceptions. It is recommended to catch and handle specific exceptions in separate except blocks and to use the assert statement for programming errors.

Q19. How can you raise your own exception in Python?

a) Using the raise keyword followed by the name of the exception class
b) Using the throw keyword followed by the name of the exception class
c) Using the assert keyword followed by the name of the exception class
d) Using the try keyword followed by the name of the exception class

Answer: a) Using the raise keyword followed by the name of the exception class

Explanation: You can raise your own exception in Python using the raise keyword followed by the name of the exception class. For example, if you want to raise an exception when a certain condition is not met, you can write code like this:

code

if x < 0:
raise ValueError(“x cannot be negative”)
This will raise a ValueError with the message “x cannot be negative” if x is less than 0.

Q20. What happens if an exception is not caught in Python?

a) The program will continue running as if nothing happened
b) The program will terminate with an error message
c) The program will enter an infinite loop
d) The program will prompt the user to handle the exception

Answer: b) The program will terminate with an error message

Explanation: If an exception is not caught in Python, the program will terminate with an error message. The error message will typically include information about the type of exception that occurred, as well as the line number where the exception occurred. It is important to handle exceptions in your code to prevent the program from terminating unexpectedly.

Page : 1           2           3           4

12 Class- Exception Handling in Python

What are exceptions?
Exceptions are events that occur during program execution that disrupt the normal flow of the program and can lead to errors. Examples of exceptions include division by zero, invalid input, file not found, etc.

Handling exceptions
In Python, exceptions can be handled using the try-except block. The code that might raise an exception is placed inside the try block, and the code to handle the exception is placed inside the except block.

Types of exceptions
Python has many built-in exceptions, including NameError, TypeError, ValueError, ZeroDivisionError, etc. It is also possible to create custom exceptions using the raise statement.

Raising exceptions
Developers can raise exceptions manually using the raise statement. This is useful when an error occurs that cannot be handled by the program, and it needs to be passed on to a higher-level function or the user.

Finally block
The finally block is a piece of code that is executed whether or not an exception is raised. It is typically used for cleanup code, such as closing files or releasing resources.

Exception hierarchy
Python has a hierarchy of exception classes, with the base class being Exception. This allows developers to catch multiple exceptions at once using a single except block.

Debugging
Exception handling is an essential tool for debugging Python programs. By handling exceptions gracefully, developers can identify and fix errors in their code more easily.

Page : 1           2           3           4

Class 10 Artificial Intelligence Unit 1 Introduction to Artificial Intelligence

Class 10 Artificial Intelligence Unit 1 Introduction to Artificial Intelligence Session 1 : Foundational Concepts of Artificial Intelligence MCQs and Question Answers

Unit 1 Introduction to Artificial Intelligence

Session 1 : Foundational Concepts of Artificial Intelligence

Multipole choice Questions  and Question Answers

1. To make decisions, _________ is necessary.
(a) Information (b) Intelligence (c) Both a and b (d) Programming

Answer: (b) Intelligence

2. What stimulates us to initiate the process of reasoning?
(a) Process (b) Sensing (c) Reasoning (d) Programming

Answer: (b) Sensing

3. The processing of what we sense is called ______?
(a) Process (b) Sensing (c) Reasoning (d) Programming

Answer: (c) Reasoning

4. A man-made thing is called _______?
(a) Artificial (b) Ready Made (c) Intelligence (d) Artificial Intelligence

Answer: (a) Artificial.

5. To be able to learn different languages ________ intelligence is required.
(a) Spatial visual (b) Existential (c) Linguistic (d) Naturalist

Answer: (c) Linguistic

6. To be able to interact and related with the surroundings and environment is _______ intelligence
(a) Naturalist (b) Climate (c) Intrapersonal (d) None

Answer: (c) Naturalist

7. Ability to understand the logic, theories, formulae, and expressions is _______ intelligence
(a) Naturalist (b) Climate (c) Intrapersonal (d) Mathematical and Logical

Answer: (d) Mathematical and Logical

8. Communicating with others with an understanding of ow they feel and perceive is _______ intelligence
(a) Interpersonal (b) Intrapersonal (c) Existential (d) Mathematical and Logical

Answer: (a) Interpersonal

9. Amrit has the ability to create, identify and understand rhymes and patterns. He is having _______ intelligence
(a) Naturalist (b) Climate (c) Intrapersonal (d) Musical

Answer: (d) Musical

10. Intelligence is directly related to ______.
(a) Fact (b) Learning (c) Brain (d) None

Answer: (b) Learning

11. Intelligence can be defined as ______.
(a) Ability to interact with the real-world

(b) Reasoning and Planning

(c) Learning and adaptation

(d) All of the above

Answer: (d) All of the above

Question Answers – 1 Mark & 2 Marks.

1. What is Artificial? (1 Mark)
Answer: Artificial is something that is man-made, which does not occur naturally.

2. What is Intelligence? (1 Mark)
Answer: Intelligence is the ‘ability to perceive or infer information, and to retain it as knowledge to be applied towards adaptive behaviours within an environment or context.’

Intelligence is the ability to observe and understand information, and preserve it as knowledge to apply in various situations or context through suitable adaptive behaviours.

3. What simulates us initiating the process of reasoning? (1 Mark)
Answer: Sensing

4. What is reasoning? (1 Mark)
Answer: The process of sensing (i.e. input – through sense, perceive, receive ) is known as reasoning.

5. How many types of reasoning? (1 Mark)
Answer: There are two types of reasoning – Deductive and Inductive

6. Define:- Deductive and Inductive? (2 Marks)
Answer: Deductive: In deductive reasoning facts are analysed and guarantee a conclusion.

Inductive: In inductive reasoning, facts only support the conclusion without any guarantee.

7. By which organ a human can sense? (1 Mark)
Answer: A human can sense through receptive organs (eye, ear, nose, mouse, skin, etc).

8. How a machine can sense? (1 Mark)
Answer: Machine can sense through the following sensing devices –

Image scanner, Audio sensor, Speech recognition engine, Biometric sensor, motion sensor, thermal sensor, light sensor, Proximity (distance) sensor, etc.

9. What are the different traits/characteristics/types of intelligence? (2 Marks)
Answer: The abilities/traits that are involved in intelligence are: –

Natural Intelligence
Interpersonal Intelligence
Intrapersonal Intelligence
Musical Intelligence
Mathematical Logical Reasoning Intelligence
Linguistics Intelligence
Spatial Visual Intelligence
Kinaesthetic Intelligence
Existential Intelligence
10. What is Mathematical Logical Reasoning intelligence? (1 Mark)
Answer: A person’s ability to regulate, measure, and understand numerical symbols, abstraction, and logic, known as Mathematical Logical Reasoning. Mathematical Logical Reasoning are carried out in the left, back and front of the brains.

11. What is Linguistic intelligence? (1 Mark)
Answer: Linguistic Intelligence means language processing skills both in terms of understanding or implementation in writing or verbally.

12. What is Spatial Visual intelligence? (1 Mark)
Answer: Spatial Visual intelligence is the ability to perceive the visual world and the relationship of one object to another.

13. What is Kineasthetic intelligence? (1 Mark)
Answer: Kinaesthetic Intelligence is the ability that is related to how a person uses his limbs in a skilled
manner.

14. What is Musical intelligence? (1 Mark)
Answer: Musical Intelligence is about a person’s ability to recognize and create sounds, rhythms, and sound patterns

15. What is Intrapersonal intelligence? (1 Mark)
Answer: Intrapersonal Intelligence describes how high the level of self-awareness someone has. Starting from realizing weakness, and strength, to his own feelings

16. What is Interpersonal intelligence? (1 Mark)
Answer: Interpersonal Intelligence is the ability to communicate with others by understanding other people’s feelings & influence the person.

17. What is Existential intelligence? (1 Mark)
Answer: Existential Intelligence is an additional category of intelligence relating to religious and spiritual awareness.

18. What is Naturalist intelligence? (1 Mark)
Answer: Naturalist Intelligence is an additional category of intelligence relating to the ability to process the information of the environment around us.

19. What is the difference between Interpersonal intelligence and Intrapersonal Intelligence? (1 Mark)
Answer: Interpersonal Intelligence involves interpersonal skills, communication skills, and ability to interact with others, while Intrapersonal intelligence involves the skills of self-awareness, self-discipline, self-management, self-evaluation, etc.

20. What is AI? (1 Mark)
Answer: AI is the science and engineering of making Intelligent machines.

21. What do you mean by AI? (1 Mark)
Answer: AI refers to the study of principles, concepts and technology for building such machines and systems that should think, act and learn like humans.

22. What are the AI challenges to making machine intelligence? (2 Marks)
Answer: AI challenges are

Retain the facts as knowledge
Recall the knowledge in a situation.
Think, analyse and apply logic.
Make useful and accurate predictions.
Make decisions and upgrade their intelligence algorithm themselves.

23. How do machines become artificially intelligent? (1 Mark)
Answer: Machine becomes intelligent once they are trained with some information that helps them achieve their tasks.

AI machines also keep updating their knowledge to optimise their output.

24. What is the most important part of intelligence? (1 Mark)
Answer: Decision Making

25. What is decision-making? (1 Mark)
Answer: Decision-making is the capability that helps in taking the right decisions in different situations.

The basis of decision-making depends upon the availability of information and how we experience and understand it.

26. You are locked inside a room with 3 doors to move out of the locked room and you need to find a safe door to get your way out. (2 Mark)
Behind the 1st door is a lake with a deadly shark.
The 2nd door has a mad psychopath ready to kill with a weapon and
The third one has a lion that has not eaten since the last 2 months.?
Answer: Gate number 3.

The reason being that since the lion has not eaten for 2 months, he wouldn’t have survived till now and would already be dead.

27. What is Artificial intelligence? (1 Mark)
Answer: When a machine possesses the ability to mimic human traits, i.e., make decisions, predict the future, learn and improve on its own, it is said to have artificial intelligence.

OR

A machine is artificially intelligent when it can accomplish tasks by itself – collect data, understand it, analyze it, learn from it, and improve it.

28. Write the name of Applications of Artificial Intelligence around us? (2 Marks)
Answer: Articificially Intelligence applications are-

(a) Google Assitant (b) Auto Suggest and auto-corrects (c) Cortana (d) Siri (e) Google Maps (f) Weather forecast (g) Real Time Language Translators (h) Sophia (i) Biometric Security Sensor

29. Give the example of voice assistance? ( 2 Marks)
Answer: Voice Assistants are – (a) Google Assitant (b) Cortana (c) Siri (d) Alexa

30. How do machines become Artificially Intelligent? ( 2 Marks)
Answer: Machines become intelligent once they are trained with some information that helps them achieve their tasks.

AI machines also keep updating their knowledge to optimise their output.

31. How do humans become intelligent? (1 Marks)
Answer: Humans become more and more intelligent with time as they gain experiences during their lives.

32. Give two examples where Google is using the concept of AI? (2 Marks)
Answer: (i) Google Search (ii) Auto suggests & Auto corrects.

33. Give 4 examples of pocket voice assistants. (2 Marks)
Answer: Very common examples of pocket voice assistants are Alexa, Google Assistant, Cortana, and Siri.

34. Give one example which helps in direction. (1 Mark)
Answer: Google Map

35. How AI changes the experiences of Gaming? (1 Marks)
Answer: A lot of games nowadays are backed up with AI which helps in enhancing the graphics, coming up with new difficulty levels, encouraging gamers, etc. For example: EA Sports (FIFA)

36. How AI taking care of our habits, like & dislike ? (2 Marks)
Answer: AI has not only made our lives easier but has also been taking care of our habits, likes, and dislikes. Due to AI following changes are noticed in our daily life: –

Netflix, Amazon, Spotify, YouTube, etc. show us recommendations on the basis of what we like.
Cater to our needs of connecting with friends on social media platforms with apps like Facebook and Instagram.
Send us customized notifications about our online shopping details, auto-create playlists according to our requests, and so on.
Taking selfies was never this fun as Snapchat filters make them look so cool

37. How AI helps in health? (1 Marks)
Answer: AI is also being used to monitor our health. A lot of chatbots and other health apps are available, which continuously monitor the physical and mental health of its users.