This lecture covers files and exception handling in Python. It discusses opening, reading from, and writing to files. The key steps are opening the file, using it (reading or writing data), and closing it. Exceptions allow programs to handle and respond to errors and unexpected situations gracefully using try/except blocks. The case study demonstrates generating math tests randomly and writing the output to a file rather than displaying it on screen. This improves the program by storing the results for later use.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading files line-by-line or as a whole, and modifying the file pointer position using seek(). Key points include opening files returns a file object, reading can be done line-by-line with for loops or using read()/readlines(), and seek() allows changing the file pointer location.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading and writing file contents using methods like read(), readline(), readlines(), seeking to different positions, and closing files. Examples are provided to illustrate reading temperature data from one file and writing converted values to another file. The document also discusses creating, deleting and renaming files and folders using OS module functions.
This document discusses files and exception handling in Python. It begins by defining files and describing different types of files like data, text, and program files. It then covers topics like sequential and random file access, opening and closing files, reading and writing to files, and using file dialogs. The document also discusses retrieving data from the web using functions like urlopen. Finally, it defines exceptions and different types of errors like syntax, runtime, and logical errors. It explains how to handle exceptions in Python using try/except blocks and predefined or user-defined exceptions.
The document discusses Python's built-in functions and methods for reading, writing, and manipulating files and directories. It explains how to open and close files, read and write file contents, check file positions, rename and delete files, create and remove directories, and get the current working directory using functions like open(), close(), read(), write(), tell(), seek(), os.rename(), os.remove(), os.mkdir(), os.chdir(), and os.getcwd(). It also covers the different modes for opening files and lists attributes of file objects.
This document discusses files in Python. It begins by defining what a file is and explaining that files enable persistent storage on disk. It then covers opening, reading from, and writing to files in Python. The main types of files are text and binary, and common file operations are open, close, read, and write. It provides examples of opening files in different modes, reading files line by line or in full, and writing strings or lists of strings to files. It also discusses searching files and handling errors when opening files. In the end, it presents some exercises involving copying files, counting words in a file, and converting decimal to binary.
This document provides an overview of file handling in Python. It begins by outlining learning objectives related to understanding different file types, opening and closing files, and reading from and writing to files. It then discusses the need for data file handling to permanently store program data. Various file types are introduced, including text files, CSV files, and binary files. Methods for opening, reading from, writing to, and closing both text and binary files are described. The pickle module is explained for pickling and unpickling Python objects for storage in binary files. Finally, random access methods like tell() and seek() are briefly covered.
Here are the answers to the quiz questions:
1. def read_file(file_name):
lines = []
with open(file_name, 'r') as f:
for line in f:
lines.append(line)
return lines
2. def input_list():
n = int(input("Enter number of elements : "))
list1 = []
for i in range(0, n):
ele = float(input())
list1.append(ele)
return list1
def output_list(list1):
for i in list1:
print(i)
3. def display_file(filename):
with open(filename
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading files line-by-line or as a whole, and modifying the file pointer position using seek(). Key points include opening files returns a file object, reading can be done line-by-line with for loops or using read()/readlines(), and seek() allows changing the file pointer location.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading and writing file contents using methods like read(), readline(), readlines(), seeking to different positions, and closing files. Examples are provided to illustrate reading temperature data from one file and writing converted values to another file. The document also discusses creating, deleting and renaming files and folders using OS module functions.
This document discusses files and exception handling in Python. It begins by defining files and describing different types of files like data, text, and program files. It then covers topics like sequential and random file access, opening and closing files, reading and writing to files, and using file dialogs. The document also discusses retrieving data from the web using functions like urlopen. Finally, it defines exceptions and different types of errors like syntax, runtime, and logical errors. It explains how to handle exceptions in Python using try/except blocks and predefined or user-defined exceptions.
The document discusses Python's built-in functions and methods for reading, writing, and manipulating files and directories. It explains how to open and close files, read and write file contents, check file positions, rename and delete files, create and remove directories, and get the current working directory using functions like open(), close(), read(), write(), tell(), seek(), os.rename(), os.remove(), os.mkdir(), os.chdir(), and os.getcwd(). It also covers the different modes for opening files and lists attributes of file objects.
This document discusses files in Python. It begins by defining what a file is and explaining that files enable persistent storage on disk. It then covers opening, reading from, and writing to files in Python. The main types of files are text and binary, and common file operations are open, close, read, and write. It provides examples of opening files in different modes, reading files line by line or in full, and writing strings or lists of strings to files. It also discusses searching files and handling errors when opening files. In the end, it presents some exercises involving copying files, counting words in a file, and converting decimal to binary.
This document provides an overview of file handling in Python. It begins by outlining learning objectives related to understanding different file types, opening and closing files, and reading from and writing to files. It then discusses the need for data file handling to permanently store program data. Various file types are introduced, including text files, CSV files, and binary files. Methods for opening, reading from, writing to, and closing both text and binary files are described. The pickle module is explained for pickling and unpickling Python objects for storage in binary files. Finally, random access methods like tell() and seek() are briefly covered.
Here are the answers to the quiz questions:
1. def read_file(file_name):
lines = []
with open(file_name, 'r') as f:
for line in f:
lines.append(line)
return lines
2. def input_list():
n = int(input("Enter number of elements : "))
list1 = []
for i in range(0, n):
ele = float(input())
list1.append(ele)
return list1
def output_list(list1):
for i in list1:
print(i)
3. def display_file(filename):
with open(filename
This document provides an overview of streams and file input/output (I/O) in Java. It discusses the differences between text and binary files, and how to read from and write to both types of files using classes like PrintWriter, FileOutputStream, BufferedReader, and FileReader. Key points covered include opening and closing files, reading/writing text with print/println methods, and handling I/O exceptions. The goal is to learn the basic concepts and mechanisms for saving and loading data from files.
This document discusses Python's built-in functions and methods for performing input/output operations (I/O) and manipulating files and directories. It covers printing to the screen, reading keyboard input, opening and closing files, reading and writing files, file positions, renaming and deleting files, and creating, removing, and changing directories.
This document discusses file handling in Python. File handling allows Python programs to read from and write data to disk files for permanent storage. The open() function is used to open a file and return a file object, which has methods like read(), write(), close() to interact with the file. Files can be opened in different modes like read, write, append. The read() method reads from the file while write() writes to it. Files must be closed using close() after processing to flush buffers and close the file properly.
The document discusses file handling in Python. It begins by explaining the need for files, such as to store data permanently and access it faster. It then covers opening and closing files, different file modes, reading and writing text files, modifying files by replacing strings, and using file attributes and methods like seek, tell, readlines and writelines. The document provides examples to demonstrate basic text file operations in Python.
The document discusses file handling in Python. It begins by explaining the need for file handling such as storing data permanently and accessing it faster. It then defines what a file is and explains the different types of files - text files and binary files. It discusses the three main steps for file handling in Python - opening the file, processing the file by performing read/write operations, and closing the file. It also describes various file opening modes, methods for reading and writing text files, and modifying or appending content to text files.
The document discusses file handling in Python. It explains that files are used to permanently store data on disk. There are two main types of files - text files and binary files. Text files can be opened in a text editor while binary files require specific software. The key steps for file operations in Python are to open the file, perform read/write operations, and close the file. Methods like open(), read(), write(), close() are used to perform various file operations. The document also discusses reading, writing, appending and binary file operations in Python.
File Handling Topic for tech management you know na tho kyuon puch raha hai saleRohitKurdiya1
The document discusses various file handling methods in Python like open(), read(), write(), readline(),readlines() and close(). It explains that open() is used to open a file and return a file object. The different modes of open() like 'r', 'w', 'a' are used to read, write and append files. Methods like read() reads the entire file content, readline() reads one line, readlines() returns a list of lines. write() is used to write content to a file in 'w' or 'a' mode. close() closes the file after operations.
The document discusses file handling and regular expressions in Python programming. It covers opening, reading, and writing files in both text and binary modes. It also describes parsing text files using built-in functions and regular expressions. Regular expressions topics covered include characters, character classes, quantifiers, grouping, capturing, assertions, and flags. The document provides examples of using the re module to search and manipulate strings using regular expression patterns.
This document provides information on file handling and dictionaries in Python. It discusses file paths, opening and closing files, reading from and writing to files. It also covers creating, accessing, adding, updating and deleting elements in dictionaries. Finally, it discusses directory methods like getcwd(), chdir(), listdir(), mkdir(), rmdir() and rename() for working with directories in Python.
Files in Python can be used to permanently store data on disk. There are two main types - text files and binary files. Text files can be opened in a text editor while binary files require specific software. To handle files in Python, they must be opened, have operations performed, and then closed. There are different modes for opening files - read, write, append. The open() function returns a file object that can be used to read, write, close the file using methods like read(), write(), close(). Care must be taken when writing to ensure old data isn't overwritten.
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 file handling in C programming. It begins by explaining why files are useful for storing data permanently and how programs can read from and write to files. It then covers the basic file operations in C like opening, reading from, writing to, and closing files. Different file modes for opening files are described. Functions for reading and writing single characters and formatted data to files like fopen, fclose, getc, putc, fscanf, fprintf are explained with examples. The document also discusses lower level functions for reading and writing blocks of data like fread and fwrite along with an example. It concludes with exercises asking the reader to write programs that read and write data to files.
The document discusses file handling in Python. It explains that a file is used to permanently store data in non-volatile memory. It describes opening, reading, writing, and closing files. It discusses opening files in different modes like read, write, append. It also explains attributes of file objects like name, closed, and mode. The document also covers reading and writing text and binary files, pickle module for serialization, and working with CSV files and the os.path module.
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
FILES
FILES I/O STREAM
TYPES OF FILES
DRAWBACKS OF TRADITIONAL METHOD OF DATA STORAGE
CONCEPT OF BUFFER
MODES OF FILE OPENING
END OF FILE
PROCESSORS DIRECTIVES
MACROS
TYPES OF MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
This document discusses file operations in C++. It defines what a file is and describes basic file operations like opening, writing, reading, and closing files. It explains how to set up a C++ program for file input/output by including the fstream header. Different stream objects like ifstream, ofstream, and fstream are used to represent input/output from files. The document also covers opening files, checking for open errors, writing and reading data from files using insertion and extraction operators, formatting file output, detecting the end of a file, and using getline() and put() functions for character I/O.
File Handling in C Programming for BeginnersVSKAMCSPSGCT
The document discusses file handling in C. It covers opening, reading, writing and closing files. Some key points covered are:
- Files store large volumes of related data on disk and allow flexible data access.
- Files are opened using fopen() by specifying the filename and mode (read/write/append).
- Functions like fprintf(), fscanf(), getc(), putc() are used for file input/output operations.
- Files must be closed using fclose() after all operations are complete.
- Error handling functions like feof() and ferror() check for errors during file operations.
The document discusses files in Python. It describes that files allow storing data permanently on disk that can be accessed by Python programs. There are two main types of files - text files, which store data as characters, and binary files, which store data in the same format as memory. The document outlines various methods for opening, reading, writing, and closing files in Python. It also discusses file paths and different file access modes.
Files in Python can be used to read data from disk files into a Python program and write data from a Python program back to disk files. There are two main types of files: text files, which store data as characters, and binary files, which store data in the same format as memory. Common file operations in Python include opening, reading, writing, and closing files. The open() function is used to open a file and return a file object, and the close() method closes the file and releases it for other applications. The with statement provides a convenient way to ensure files are closed after use.
The document discusses file handling in C programming. It explains that file handling allows programs to store and retrieve data from files for later use, as opposed to just displaying output temporarily. It covers opening, reading from, writing to, and closing files using functions like fopen(), fprintf(), fscanf(), and fclose(). It also differentiates between text files with .txt extensions and binary files for storing different data types permanently in a file.
This lecture covers data structures and iteration. It discusses arrays as ordered collections of values that allow items to be accessed by index. Python offers two array-like data structures: lists, which are mutable, and tuples, which are immutable. Loops allow code to repeatedly execute and come in two main types - while loops, which repeat while a condition is true, and for loops. Break and continue statements can be used in loops to exit or skip iterations under certain conditions.
This lecture covers data types and selection statements in programming. It discusses common data types like integers, floats, strings and booleans. It also explains weak and strong typing, implicit and explicit type conversion. The lecture then covers selection statements like if-then, if-then-else and else-if statements which allow code to execute conditionally based on boolean expressions. It provides examples of comparison operators and logical operators used in boolean expressions.
More Related Content
Similar to ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
This document provides an overview of streams and file input/output (I/O) in Java. It discusses the differences between text and binary files, and how to read from and write to both types of files using classes like PrintWriter, FileOutputStream, BufferedReader, and FileReader. Key points covered include opening and closing files, reading/writing text with print/println methods, and handling I/O exceptions. The goal is to learn the basic concepts and mechanisms for saving and loading data from files.
This document discusses Python's built-in functions and methods for performing input/output operations (I/O) and manipulating files and directories. It covers printing to the screen, reading keyboard input, opening and closing files, reading and writing files, file positions, renaming and deleting files, and creating, removing, and changing directories.
This document discusses file handling in Python. File handling allows Python programs to read from and write data to disk files for permanent storage. The open() function is used to open a file and return a file object, which has methods like read(), write(), close() to interact with the file. Files can be opened in different modes like read, write, append. The read() method reads from the file while write() writes to it. Files must be closed using close() after processing to flush buffers and close the file properly.
The document discusses file handling in Python. It begins by explaining the need for files, such as to store data permanently and access it faster. It then covers opening and closing files, different file modes, reading and writing text files, modifying files by replacing strings, and using file attributes and methods like seek, tell, readlines and writelines. The document provides examples to demonstrate basic text file operations in Python.
The document discusses file handling in Python. It begins by explaining the need for file handling such as storing data permanently and accessing it faster. It then defines what a file is and explains the different types of files - text files and binary files. It discusses the three main steps for file handling in Python - opening the file, processing the file by performing read/write operations, and closing the file. It also describes various file opening modes, methods for reading and writing text files, and modifying or appending content to text files.
The document discusses file handling in Python. It explains that files are used to permanently store data on disk. There are two main types of files - text files and binary files. Text files can be opened in a text editor while binary files require specific software. The key steps for file operations in Python are to open the file, perform read/write operations, and close the file. Methods like open(), read(), write(), close() are used to perform various file operations. The document also discusses reading, writing, appending and binary file operations in Python.
File Handling Topic for tech management you know na tho kyuon puch raha hai saleRohitKurdiya1
The document discusses various file handling methods in Python like open(), read(), write(), readline(),readlines() and close(). It explains that open() is used to open a file and return a file object. The different modes of open() like 'r', 'w', 'a' are used to read, write and append files. Methods like read() reads the entire file content, readline() reads one line, readlines() returns a list of lines. write() is used to write content to a file in 'w' or 'a' mode. close() closes the file after operations.
The document discusses file handling and regular expressions in Python programming. It covers opening, reading, and writing files in both text and binary modes. It also describes parsing text files using built-in functions and regular expressions. Regular expressions topics covered include characters, character classes, quantifiers, grouping, capturing, assertions, and flags. The document provides examples of using the re module to search and manipulate strings using regular expression patterns.
This document provides information on file handling and dictionaries in Python. It discusses file paths, opening and closing files, reading from and writing to files. It also covers creating, accessing, adding, updating and deleting elements in dictionaries. Finally, it discusses directory methods like getcwd(), chdir(), listdir(), mkdir(), rmdir() and rename() for working with directories in Python.
Files in Python can be used to permanently store data on disk. There are two main types - text files and binary files. Text files can be opened in a text editor while binary files require specific software. To handle files in Python, they must be opened, have operations performed, and then closed. There are different modes for opening files - read, write, append. The open() function returns a file object that can be used to read, write, close the file using methods like read(), write(), close(). Care must be taken when writing to ensure old data isn't overwritten.
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 file handling in C programming. It begins by explaining why files are useful for storing data permanently and how programs can read from and write to files. It then covers the basic file operations in C like opening, reading from, writing to, and closing files. Different file modes for opening files are described. Functions for reading and writing single characters and formatted data to files like fopen, fclose, getc, putc, fscanf, fprintf are explained with examples. The document also discusses lower level functions for reading and writing blocks of data like fread and fwrite along with an example. It concludes with exercises asking the reader to write programs that read and write data to files.
The document discusses file handling in Python. It explains that a file is used to permanently store data in non-volatile memory. It describes opening, reading, writing, and closing files. It discusses opening files in different modes like read, write, append. It also explains attributes of file objects like name, closed, and mode. The document also covers reading and writing text and binary files, pickle module for serialization, and working with CSV files and the os.path module.
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
FILES
FILES I/O STREAM
TYPES OF FILES
DRAWBACKS OF TRADITIONAL METHOD OF DATA STORAGE
CONCEPT OF BUFFER
MODES OF FILE OPENING
END OF FILE
PROCESSORS DIRECTIVES
MACROS
TYPES OF MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
This document discusses file operations in C++. It defines what a file is and describes basic file operations like opening, writing, reading, and closing files. It explains how to set up a C++ program for file input/output by including the fstream header. Different stream objects like ifstream, ofstream, and fstream are used to represent input/output from files. The document also covers opening files, checking for open errors, writing and reading data from files using insertion and extraction operators, formatting file output, detecting the end of a file, and using getline() and put() functions for character I/O.
File Handling in C Programming for BeginnersVSKAMCSPSGCT
The document discusses file handling in C. It covers opening, reading, writing and closing files. Some key points covered are:
- Files store large volumes of related data on disk and allow flexible data access.
- Files are opened using fopen() by specifying the filename and mode (read/write/append).
- Functions like fprintf(), fscanf(), getc(), putc() are used for file input/output operations.
- Files must be closed using fclose() after all operations are complete.
- Error handling functions like feof() and ferror() check for errors during file operations.
The document discusses files in Python. It describes that files allow storing data permanently on disk that can be accessed by Python programs. There are two main types of files - text files, which store data as characters, and binary files, which store data in the same format as memory. The document outlines various methods for opening, reading, writing, and closing files in Python. It also discusses file paths and different file access modes.
Files in Python can be used to read data from disk files into a Python program and write data from a Python program back to disk files. There are two main types of files: text files, which store data as characters, and binary files, which store data in the same format as memory. Common file operations in Python include opening, reading, writing, and closing files. The open() function is used to open a file and return a file object, and the close() method closes the file and releases it for other applications. The with statement provides a convenient way to ensure files are closed after use.
The document discusses file handling in C programming. It explains that file handling allows programs to store and retrieve data from files for later use, as opposed to just displaying output temporarily. It covers opening, reading from, writing to, and closing files using functions like fopen(), fprintf(), fscanf(), and fclose(). It also differentiates between text files with .txt extensions and binary files for storing different data types permanently in a file.
Similar to ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf (20)
This lecture covers data structures and iteration. It discusses arrays as ordered collections of values that allow items to be accessed by index. Python offers two array-like data structures: lists, which are mutable, and tuples, which are immutable. Loops allow code to repeatedly execute and come in two main types - while loops, which repeat while a condition is true, and for loops. Break and continue statements can be used in loops to exit or skip iterations under certain conditions.
This lecture covers data types and selection statements in programming. It discusses common data types like integers, floats, strings and booleans. It also explains weak and strong typing, implicit and explicit type conversion. The lecture then covers selection statements like if-then, if-then-else and else-if statements which allow code to execute conditionally based on boolean expressions. It provides examples of comparison operators and logical operators used in boolean expressions.
Programming Fundamentals Lecture 3 covered data structures and iteration. Data structures allow storing multiple pieces of data in an organized way. Arrays are ordered collections of values that can be accessed by index. Python offers lists and tuples, where lists are mutable and tuples are immutable. Loops called iteration allow repeatedly running a block of code. While loops repeat while a condition is true. Break and continue can be used in loops to exit early or skip iterations conditionally.
This lecture covers functions and modules in Python. It discusses built-in functions, writing user-defined functions, function parameters and return values, and scope. It also discusses modules as a way to organize Python code and introduces some of Python's standard library modules like math and random. The key points are:
1) Functions allow for code reuse and abstraction by encapsulating repeatable processes. Built-in functions perform common tasks while user-defined functions can be created for custom tasks.
2) Functions are defined using def and have parameters to pass in inputs and return values to produce outputs. Variables inside functions have local scope while global variables can be accessed everywhere.
3) Modules help structure Python programs and provide
This document provides an introduction to C programming, including:
- A brief history of C and its advantages/disadvantages.
- An explanation of a simple "Hello World" program to demonstrate basic C syntax.
- Guidance on coding style best practices like indentation, spacing, and commenting code to improve readability and understanding.
The lecture recaps programming concepts covered so far like variables, data types, selection statements, and functions. It then presents a "Test Generator" case study to demonstrate designing, coding, and enhancing a program through multiple versions. The case study involves generating random math tests with addition or subtraction problems for students. Pseudocode is developed for each version to plan the program logic before coding.
This lecture introduces programming fundamentals and Python. It discusses what programming is, the process of translating source code into machine-readable instructions, and program design using pseudocode and flowcharts. Program design tools like pseudocode and flowcharts allow programmers to plan programs' logic and structure before writing the actual code. The lecture also provides an overview of Python syntax and variables.
This document provides an introduction to programming fundamentals and algorithms. It defines an algorithm as a well-ordered collection of unambiguous and effectively computable operations that produces a result and halts in a finite amount of time. The document discusses the history and purpose of programming, and defines computer science as the study of algorithms. It explains the three components that make up all algorithms: sequence, selection, and iteration. The document outlines the process for developing an algorithmic solution, including defining the problem, creating a high-level algorithm, defining inputs/outputs, testing the algorithm, and coding it.
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELgerogepatton
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
Comparative analysis between traditional aquaponics and reconstructed aquapon...bijceesjournal
The aquaponic system of planting is a method that does not require soil usage. It is a method that only needs water, fish, lava rocks (a substitute for soil), and plants. Aquaponic systems are sustainable and environmentally friendly. Its use not only helps to plant in small spaces but also helps reduce artificial chemical use and minimizes excess water use, as aquaponics consumes 90% less water than soil-based gardening. The study applied a descriptive and experimental design to assess and compare conventional and reconstructed aquaponic methods for reproducing tomatoes. The researchers created an observation checklist to determine the significant factors of the study. The study aims to determine the significant difference between traditional aquaponics and reconstructed aquaponics systems propagating tomatoes in terms of height, weight, girth, and number of fruits. The reconstructed aquaponics system’s higher growth yield results in a much more nourished crop than the traditional aquaponics system. It is superior in its number of fruits, height, weight, and girth measurement. Moreover, the reconstructed aquaponics system is proven to eliminate all the hindrances present in the traditional aquaponics system, which are overcrowding of fish, algae growth, pest problems, contaminated water, and dead fish.
Embedded machine learning-based road conditions and driving behavior monitoringIJECEIAES
Car accident rates have increased in recent years, resulting in losses in human lives, properties, and other financial costs. An embedded machine learning-based system is developed to address this critical issue. The system can monitor road conditions, detect driving patterns, and identify aggressive driving behaviors. The system is based on neural networks trained on a comprehensive dataset of driving events, driving styles, and road conditions. The system effectively detects potential risks and helps mitigate the frequency and impact of accidents. The primary goal is to ensure the safety of drivers and vehicles. Collecting data involved gathering information on three key road events: normal street and normal drive, speed bumps, circular yellow speed bumps, and three aggressive driving actions: sudden start, sudden stop, and sudden entry. The gathered data is processed and analyzed using a machine learning system designed for limited power and memory devices. The developed system resulted in 91.9% accuracy, 93.6% precision, and 92% recall. The achieved inference time on an Arduino Nano 33 BLE Sense with a 32-bit CPU running at 64 MHz is 34 ms and requires 2.6 kB peak RAM and 139.9 kB program flash memory, making it suitable for resource-constrained embedded systems.
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...IJECEIAES
Climate change's impact on the planet forced the United Nations and governments to promote green energies and electric transportation. The deployments of photovoltaic (PV) and electric vehicle (EV) systems gained stronger momentum due to their numerous advantages over fossil fuel types. The advantages go beyond sustainability to reach financial support and stability. The work in this paper introduces the hybrid system between PV and EV to support industrial and commercial plants. This paper covers the theoretical framework of the proposed hybrid system including the required equation to complete the cost analysis when PV and EV are present. In addition, the proposed design diagram which sets the priorities and requirements of the system is presented. The proposed approach allows setup to advance their power stability, especially during power outages. The presented information supports researchers and plant owners to complete the necessary analysis while promoting the deployment of clean energy. The result of a case study that represents a dairy milk farmer supports the theoretical works and highlights its advanced benefits to existing plants. The short return on investment of the proposed approach supports the paper's novelty approach for the sustainable electrical system. In addition, the proposed system allows for an isolated power setup without the need for a transmission line which enhances the safety of the electrical network
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
2. This Lecture
• Files
– Opening, using and closing files
– File opening modes
– Writing to files
– Reading entire files, reading lines and bytes
• Exception handling
– Exception handlers, termination and continuation
– Exception names
– Try and catch/except
– Else and finally
2
3. Textbook
• Starting Out with Python, 4th Edition (Global)
– Tony Gaddis
• Reading the chapter(s) is required
– Read the indicated chapter(s) before class
• This week covers the following textbook chapter(s):
– Chapter 6 – Files and Exceptions
• Entire chapter
3
5. Files
• So far, our programs have been entirely “self-contained”
– Nothing is stored or kept between each run of the program
– Input we provide to the program is stored in RAM, output is shown on the screen…
Nothing lasts beyond end of program
• To retain data, receive input or store output, programs often use files on the
computer’s hard drive:
– Settings and configuration files of programs
– “Office Suite” files such as word processed documents, spreadsheets and slideshows
– Media files created and used by image, video and music apps
– Cache and cookie files created and used by web browsers
– Assets, save files and replays of games…
5
6. Files
• Files can be used for both input and output
– Reading data from a file allows you to use it as input
– Writing data to a file allows you to store/save output in it
• Files come in two main types:
– Text files simply contain text, encoded in ASCII or Unicode, and can be opened by
programs like Notepad
• Text can be formatted or structured in specific ways to make it more useful, e.g. CSV, JSON
• The extension is not necessarily “.txt” – e.g. Python programs (“.py”) are just text files
– Binary files are not text-based and are designed to only be opened by a program that
can use the data in that format
• Includes everything that isn’t a text file (images, exes, audio files, video files…)
6
7. Files
• Working with files in a program involves the same general process, regardless of
the programming language you are using:
1. Open the file in the program:
• If reading from a file, it must obviously exist
• If writing to a file, it must be created if it doesn’t exist. If it does, you can either overwrite its
contents or modify/append to them
– Opening a file in a program leaves you with a variable representing it (a “file object”),
which you interact with in the following steps
2. Use the file
• Reading data from the file, writing data to the file, or both
3. Close the file
• Once you have finished using the file, closing it severs its connection with the program and
releases the resources. It also ensures that anything you wrote to the file is actually saved
7
8. Opening a File
• Opening a file requires you to specify the filename
– If the file does not exist, it will be created
– If the file is not in the same folder as the program, you must specify the path to the file
• You also typically need to specify the mode to open it in
– This controls what you can do with the file once it is open
– These are the most widely-implemented modes, however modes and their
abbreviations can differ slightly between languages:
• Read (“r”) allows reading only (file must exist)
• Write (“w”) allows writing only (creates or overwrites the file, starting out empty)
• Append (“a”) allows writing only (writes to the end of the file, instead of overwriting it)
• Read/Write (“rw” / “r+” / “w+”…) allows reading and writing (slight differences in each mode)
– Some languages require different modes depending on whether it is a text or binary file
8
9. Opening a File
• In Python, the built-in function “open()” opens a file and returns a file object
– In some languages, a module is needed to interact with files
– These examples open a file named “file.txt”, in “read” mode, into a variable named “f”:
• If the file is in another folder, you must specify the path:
– The “r” at the start of the string makes Python treat it as a “raw” string - treating any
backslashes in the string as literal characters rather than escape characters
• This is useful when the string contains backslashes, which are likely in path names
9
# no module necessary
f = open('file.txt', 'r')
Python
import java.io.FileReader;
FileReader f = new FileReader("file.txt");
Java
// no module necessary
$f = fopen('file.txt', 'r');
PHP
#include <stdio.h>
FILE *f = fopen("file.txt", "r");
C / C++
# no module necessary
f = File.open('file.txt', 'r')
Ruby
f = open(r'D:otherstufffile.txt', 'r') Python
10. Writing to a File
• Once the file is open in a mode that allows writing, you just need to write data to
it using a “write” function
– Similar to using “print()”, but instead of displaying on the screen, it writes to a file
– Most of the time, you will be starting out from a new/blank file, rather than appending
• Writing to a file uses the variable/object created when the file was opened
– Either by using the “write” method (function) of the file object:
– Or by passing the variable to a “write” function as a parameter:
12
f = open('file.txt', 'w')
f.write('This text will be written to the file!')
f.close()
Python
$f = fopen('file.txt', 'w');
fwrite($f, 'This text will be written to the file!');
fclose($f);
PHP (“fwrite()” is a standalone
function that you pass the
file variable and text to)
(“write()” is a function that
you call on the file object
and pass the text to)
11. Writing to a File
• Note that while “print()” automatically adds a line break at the end of your line,
“.write()” does not:
• Use “n” to insert line breaks where you need them:
f = open('joke.txt', 'w')
f.write('What do you call a group of 8 hobbits?')
f.write('A hobbyte.')
f.close()
Python
f = open('joke.txt', 'w')
f.write('What do you call a group of 8 hobbits?n')
f.write('A hobbyte.')
f.close()
Python
13
12. Closing a File
• Once you have finished interacting with the file in your program, you must close it
– Not doing this can result in losing the data you wrote, since the data is often written to
a buffer in memory and only saved to the file on the hard drive when the file is closed
– Not closing a file can also keep it “locked”; Unable to be used by other programs
• This involves using the “close” method on the file object or calling the function to
close a file, depending on language:
• Ideally, minimise the time that a file is open for, e.g.:
– Open it in “read” mode, read the entire text into a variable, close it
– Open/Create it in “write” mode, write everything at once, close it
f = open('file.txt', 'r')
f.close()
Python $f = fopen('file.txt', 'r');
fclose($f);
PHP
14
13. “Test Generator” Case Study – Review of Version 1
• Last week we went over a case study, designing and writing a program to
generate randomised maths tests
Prompt user for + or - and store in 'op' variable.
If op is '+'
Print 'Addition Test'
Else
Print 'Subtraction Test'
Set op to '-'
Print 'Name: __________'
Loop 10 times
Generate random number between 0 and 9 and store it as 'num_one'
Generate random number between 0 and 9 and store it as 'num_two'
If op is '-' and num_one < num_two
Swap num_one and num_two
Print 'num_one op num_two = ____'
Pseudocode
15
14. “Test Generator” Case Study – Review of Version 1
• Last week we went over a case study, designing and writing a program to
generate randomised maths tests
import random
op = input('Addition or subtraction test? [enter "+" or "-"]: ')
if op == '+':
print('Addition Testn')
else:
print('Subtraction Testn')
op = '-'
print('Name: __________nn')
for i in range(10):
num_one = random.randint(0, 9)
num_two = random.randint(0, 9)
if op == '-' and num_one < num_two:
num_one, num_two = num_two, num_one
print(num_one, op, num_two, '= ____n')
Python
Addition Test
Name: ___________
2 + 4 = ____
6 + 5 = ____
1 + 8 = ____
9 + 2 = ____
5 + 4 = ____
6 + 4 = ____
7 + 2 = ____
5 + 3 = ____
2 + 1 = ____
9 + 7 = ____
Note the extra line breaks (“n”) to add extra blank lines in the output
(remember, print() ends with a line break automatically)
16
15. “Test Generator” Case Study – Writing to a File
• Now let’s change the program so that it writes its output to a file named
“output.txt” instead of showing it on the screen
Prompt user for + or - and store in 'op' variable.
Create and open 'output.txt' file in write mode
If op is '+'
Write 'Addition Test' to output file
Else
Write 'Subtraction Test ' to output file
Set op to '-'
Write 'Name: __________' to output file
Loop 10 times
Generate random number between 0 and 9 and store it as 'num_one'
Generate random number between 0 and 9 and store it as 'num_two'
If op is '-' and num_one < num_two
Swap num_one and num_two
Write 'num_one op num_two = ____' to output file
Close the output file
Print message informing user of the file
Pseudocode
17
16. “Test Generator” Case Study – Writing to a File
• Now the code creates/opens “output.txt”, and instead of printing the output, writes
it to the file before closing it
import random
op = input('Addition or subtraction test? [enter "+" or "-"]: ')
output = open('output.txt', 'w')
if op == '+':
output.write('Addition Testn')
else:
output.write('Subtraction Testn')
op = '-'
output.write('Name: __________nn')
for i in range(10):
num_one = random.randint(0, 9)
num_two = random.randint(0, 9)
if op == '-' and num_one < num_two:
num_one, num_two = num_two, num_one
output.write(str(num_one) + ' ' + op + ' ' + str(num_two) + ' = ____n')
output.close()
print('Test saved in output.txt file.')
Python
18
18. “Test Generator” Case Study – Writing to a File
• Remember, since “.write()” doesn’t add a line break to the end like
“print()” does, we need to add them… An extra “n” at the end of each line!:
import random
op = input('Addition or subtraction test? [enter "+" or "-"]: ')
output = open('output.txt', 'w')
if op == '+':
output.write('Addition Testnn')
else:
output.write('Subtraction Testnn')
op = '-'
output.write('Name: __________nnn')
for i in range(10):
num_one = random.randint(0, 9)
num_two = random.randint(0, 9)
if op == '-' and num_one < num_two:
num_one, num_two = num_two, num_one
output.write(str(num_one) + ' ' + op + ' ' + str(num_two) + ' = ____nn')
output.close()
print('Test saved in output.txt file.')
Python
20
20. Reading from a File
• Reading data from a file can be very useful
– Reading data from files previously created and written to by your program allows it to
“remember” things, e.g. Settings for the program, or loading previously saved data
– Programs can also read and use data from files created by other programs
• This relies on the file’s data being in a specific format, so that it can be read correctly by
different programs
– We will continue to work with text files, since they have a simple format that is easy to
understand and work with
• Reading from a file allows your program to have a new source of input;
Something other than the user typing
Be sure to go through Reading 7.1 next week – it goes over some ways of
giving structure to text files and is likely to be relevant to Assignment 2!
22
21. Reading from a File
• Like writing, reading a file uses the variable/object created when the file was
opened. The same two approaches exist…
– Using a “read” method of the file object:
– Passing the file variable to a “read” function as a parameter:
• The “read” methods/functions will return the data they read
– Store it in a variable so that you can then use the data in your program
– Most of the time you will read an entire file and store it in a variable,
and then interact with the variable (rather than reading a file one piece at a time)
23
f = open('file.txt', 'r')
file_data = f.read(10)
f.close()
Python
$f = fopen('file.txt', 'r');
$file_data = fread($f, 10);
fclose($f);
PHP
22. Quickly Reading an Entire File
• The simplest way to read a file is to read the entire thing at once, giving you a
variable containing the entirety of the file’s content
– Some languages can open, read and close a file in a single function
– Other languages have the ability to read all of a file at once, but still require you to
open and close it in separate statements
– Some languages (e.g. C/C++) require you to specify how many bytes or characters to
read. To read the entire file in such languages, can…
1) Use other statements to determine the total size/length of the file, and read that many
2) Use a loop to continually read bytes/characters until you reach end of file
24
$file_string = file_get_contents('file.txt'); //returns a string
$file_array = file('file.txt'); //returns an array (one item per line of text)
PHP
f = open('file.txt', 'r')
file_data = f.read() # not giving read() a number will read the whole file
f.close()
Python
23. Reading Bytes and Reading Lines
• The “.read()” method in Python can be given an integer parameter to specify
how many bytes/characters to read
– Or use the “readline()” method to read a whole line
(all data until the next line break - “n” - or the end of the file)
• “.read()” and “.readline()” read data from the current “position” in the file.
When you open a file in read mode, the position is set to the start of the file
– After you read data, the position moves to the end of that data
– Hence, you can use “.read()” and/or “.readline()” to work your way through a
file from beginning to end
25
f = open('file.txt', 'r')
data = f.read(10) # read 10 bytes
f.close()
Python f = open('file.txt', 'r')
data = f.readline() # read a line
f.close()
Python
24. Reading Through a File
• A “for” loop will work its way through a file line by line:
• The “.readlines()” (note the “s”) method puts all lines of a file into a list:
26
f = open('veg.txt', 'r')
for line in f:
print(line)
f.close()
Python
f = open('veg.txt', 'r')
file_list = f.readlines()
f.close()
Python
Leek
Potato
Carrot
file_list = ['Leekn',
'Potaton',
'Carrot']
25. Reading and Writing Numbers
• “.read()” and “.readline()” will always return a string, even if the data is
numeric (just like the “input()” function)
– Use “int()” or “float()” to convert the data to a number if needed:
– The “.write()” method can only write strings; Use “str()” to convert numbers to
strings, and add a “n” if needed:
f = open('numbers.txt', 'r')
num_one = f.readline()
num_two = int(f.readline())
f.close()
Python
num_one set to '123n' # string
num_two set to 456 # int
f = open('numbers.txt', 'a')
num_three = 789
num_four = 123
f.write(str(num_three) + 'n' + str(num_four))
f.close()
Python
28
26. Files Summary
• Files allow you to store and use data external to a program
– i.e. Files allow for a new source of input and new destination for output
– Files can be either text or binary files
• To use a file, you must first open / create it
– This creates a file object/variable that is used to interact with it
– Files can be opened in various modes, read, write, append…
• Once a file is open, you can:
– Write data to it (from the beginning, or appending to the end)
– Read data from it (all at once, by byte, by line, line-by-line…)
• Once you have finished interacting with a file, close it
29
28. Exception Handling
• An exception is an error or condition that occurs while a program is running,
causing it to “crash” or otherwise end
– You’ve no doubt seen a few during the unit, usually related to input and data types,
e.g. trying to convert letters to integer:
• Exceptions are situations that can occur that the program cannot handle,
despite the code being syntactically valid
– Unlike syntax errors, which occur when the code is not valid and will prevent the
program from running
num = int(input('Type a number: '))
print('You typed:', num)
Python
Type a number: nope
Traceback (most recent call last):
File "H:/PythonCode/exception_example.py", line 1, in <module>
num = int(input('Type a number: '))
ValueError: invalid literal for int() with base 10: 'nope'
31
29. Exception Handling
• Exception handling is, unsurprisingly, the process of responding to exceptions
when they occur – i.e. handling them
– When an exception occurs, it is said to have been “raised”, “thrown” or “triggered”,
depending on the language
– Your response will depend on the nature of the exception:
• The program may be unable to continue, hence the response will be to display an error
message and end in a clean manner – known as “termination”
• The program may be able to continue, e.g. re-prompting for input or performing some other
action to work around the exception – known as “continuation”
– Exception handling is essentially another control structure, like selection and iteration
(loop) statements:
• It allows you to control the flow of execution in a program when an exception occurs,
transferring control to an exception handler
32
30. Exception Handling
• So far in the unit, we have not handled the majority of exceptions that could occur
in the code we have written
– e.g. We’ve assumed that the user enters a number when prompted to enter a number
(which can then be converted to an int/float without an exception occurring…)
– This has been to keep our code simple and understandable, avoiding added
complexity while we are learning the basics
• However we have implemented exception handling on occasion,
e.g. re-prompting for input until a number is typed
– e.g. Tasks 3 and 4 of Workshop 4 used exception handling in the “input_int()”
and “input_float()” functions we wrote
• It is important that you consider (and handle) the exceptions that could potentially
occur in the code that you write
33
31. Basic Exception Handling - Termination
• In this example, the exception handler ends the program:
– If a “ValueError” exception is raised when trying to convert the “num” variable to an
integer, the exception handler runs
• The exception handler prints an error message, then uses “sys.exit()” to end the
program (importing “sys” to do so)
– If the exception is not raised (i.e. the conversion to integer was successful), the
exception handler does not run
• The code continues, printing the “You typed” line…
try: # prompt for a number and try to convert it to an integer
num = int(input('Type a number: '))
except ValueError: # show error message and exit
print('Invalid input. Ending program.')
import sys
sys.exit()
print('You typed:', num)
Python
Type a number: nope
Invalid input. Ending program.
34
32. Basic Exception Handling - Continuation
• This exception handler continues the program:
– If a “ValueError” exception is raised when trying to convert the “num” variable to an
integer, the exception handler runs
• The exception handler just puts an integer of 7 into “num”
• It does not end the program – the code then continues to the “You typed” line after the
exception handler ends
– While this example is quite simplistic, it illustrates the concept of handling an
exception without terminating the program
try: # prompt for a number and try to convert it to an integer
num = int(input('Type a number: '))
except ValueError: # just use 7
num = 7
print('You typed:', num)
Python
Type a number: nope
You typed: 7
35
33. Basic Exception Handling - Continuation
• This exception handler also continues the program:
– This version places the try/except code inside an endless loop
• If a “ValueError” exception is raised, the code does not reach the “break” statement,
instead going immediately to the exception handler
• After printing the error message, the end of the loop body is reached – back to “try:”…
• If the exception is not raised, the code reaches the “break” statement
– This ends the loop, allowing the program to reach the “You typed” line…
36
while True: # endless loop
try: # prompt for a number and convert it to an integer
num = int(input('Type a number: '))
break # break out of the loop
except ValueError: # show error message
print("Invalid input, try again.")
print('You typed:', num)
Python
Type a number: nope
Invalid input, try again.
Type a number: ok, fine
Invalid input, try again.
Type a number: 6
You typed: 6
34. Exception Names
• Different types of exceptions can occur, and each type of exception that the
language recognises is given a name
– The exceptions that different languages recognise and the names they have differ
• Some of the common exceptions in Python are:
– NameError, raised when you try to refer to a variable or function that doesn’t exist
• e.g. spelling its name wrong
– TypeError, raised when you try to use the wrong data type
• e.g. round('this is a string', 2)
– ValueError, raised when you use the right data type, but the value is not appropriate
• e.g. int('not numeric')
– IndexError, raised when you try to refer to an index that doesn’t exist
• e.g. referring to an index of 5 in a list of 3 items
37
35. Try and Catch/Except
• Most languages implement exception handling as follows:
– Code that might cause an exception is placed in a “try” block
– This is followed by a “catch” block, containing the code that will be run if (and only if)
the exception occurs
• In Python, the word “except” is used instead of “catch”
• If the exception occurs, the program immediately goes to the start of the “catch” block
(skipping later lines in the “try” block)
try:
<statement(s) that can cause exceptions>
catch <exception name>:
<statements(s) to run if exception occurs>
This is known as an
“exception handler”
38
36. Try and Catch/Except
• It is optional to specify an exception name after “except”
– If you just write “except:”, that exception handler will catch all exceptions – useful if
various things could go wrong and it is appropriate to handle them all in the same way
• You can specify multiple “except” blocks after a “try” block
– You can specify a different exception name in each one, allowing you specify different
exception handlers for each different exception that can occur in the “try” block…
try:
<statement(s) that can cause exceptions>
except <exception name>:
<exception handler for that exception>
except:
<exception handler for any other exception>
39
37. Try and Catch/Except
• This example demonstrates multiple exceptions/handlers:
40
Try to:
Prompt for a filename and store in 'filename' variable
Open the file named in 'filename' in read mode
Read all lines of the file into 'line_list' list variable
Print the number of lines
Prompt for which line to view and store in 'line_num' int variable
Print line of the file, using 'line_num' - 1 as index of 'line_list'
Except if the file cannot be found:
Print appropriate error message
Except if the user’s input cannot be converted to an integer:
Print appropriate error message
Except if an invalid line number is specified:
Print appropriate error message
Except if any other exception occurs:
Print generic error message
Pseudocode
38. Try and Catch/Except
• This example demonstrates multiple exceptions/handlers:
try:
filename = input('File name to open: ')
f = open(filename, 'r') # FileNotFoundError will occur if the file does not exist
line_list = f.readlines()
f.close()
print('File contains', len(line_list), 'lines.')
line_num = int(input('View which line?: ')) # ValueError will occur if input is not an int
print(line_list[line_num - 1]) # IndexError will occur if the number is not a valid index number
except FileNotFoundError:
print('File not found. Check spelling.')
except ValueError:
print('Invalid input. Int required.')
except IndexError:
print('Invalid line number.')
except:
print('Something went wrong.')
Python
41
39. Try and Catch/Except
• Let’s look at the flow of execution through the program:
①
②
③
④
⑤
try:
filename = input('File name to open: ')
f = open(filename, 'r') # potential FileNotFoundError
line_list = f.readlines()
f.close()
print('File contains', len(line_list), 'lines.')
line_num = int(input('View which line?: ')) # potential ValueError
print(line_list[line_num - 1]) # potential IndexError
except FileNotFoundError:
print('File not found. Check spelling.')
except ValueError:
print('Invalid input. Int required.')
except IndexError:
print('Invalid line number.')
except:
print('Something went wrong.')
Python
File name to open: file.txt
File contains 4 lines.
View which line?: nope
Invalid input. Int required.
42
40. Else and Finally
• After all the “except” blocks, you can optionally include:
– An “else” block, which will only run if no exceptions occurred
– A “finally” block, which will always run
• Runs after the “try” block if no exceptions occur, or after the exception handler if they do
• This is often used for “cleanup” (e.g. closing a file/connection), since it is sure to always run
try:
try statement 1
try statement 2
try statement 3
except <exception name>:
handler statements
else:
else statements
try:
try statement 1
try statement 2
try statement 3
except <exception name>:
handler statements
finally:
finally statements
43
41. Exception Handling Summary
• Exception handling allows you to catch and handle errors or conditions that
would otherwise cause a program to crash
• Statements that can raise an exception are placed in a “try”
– If an exception occurs when run the statements, the program immediately goes to the
exception handler for it
• Exception handlers are “catch”/”except” blocks after a “try” that are triggered
when the exception they name occurs
– Catch all exception handlers are also possible
– Exception handlers may terminate the program or continue it
• “else” and “finally” blocks can expand the capabilities of exception handling
44