From 759b3181a7dd8c9bc1a56b79a2a0513f27b95549 Mon Sep 17 00:00:00 2001 From: Stephanmaina Date: Tue, 29 Aug 2023 09:50:45 +0300 Subject: [PATCH 1/2] first commit --- README.md | 260 ++++++++++-------------------------------------------- 1 file changed, 46 insertions(+), 214 deletions(-) diff --git a/README.md b/README.md index c5c779c66..02da61cfa 100644 --- a/README.md +++ b/README.md @@ -1,242 +1,74 @@ # Reading Python Error Messages -## Learning Goals - -- Read the different parts of an error message. -- Identify common types of errors. - -*** - -## Key Vocab - -- **Interpreter**: a program that executes other programs. Python programs -require the Python interpreter to be installed on your computer so that they -can be run. -- **Python Shell**: an interactive interpreter that can be accessed from the -command line. -- **Data Type**: a specific kind of data. The Python interpreter uses these -types to determine which actions can be performed on different data items. -- **Exception**: a type of error that can be predicted and handled without -causing a program to crash. -- **Code Block**: a collection of code that is interpreted together. Python -groups code blocks by indentation level. -- **Function**: a named code block that performs a sequence of actions when it -is called. -- **Scope**: the area in your program where a specific variable can be called. - -*** - ## Introduction -In this lab, you'll be reading error messages from tests. This lab is designed -so that both running the files _and_ running the test suite via the `pytest` -command will show the error messages for you to decode. Moving forward though, -you'll be reading error messages mainly through running the test suite. - -*** - -## Reading Error Messages - -Let's start by running some of the Python code in the `lib/` folder to produce an -error message. Run this in your terminal: - -```console -$ python lib/a_name_error.py -``` - -Error messages have 3 parts: - -```console -File "lib/a_name_error.py", -line 3, in - print(hello_world) -NameError: name 'hello_world' is not defined -``` - -The location of the error, the "where": - - ```console - "lib/a_name_error.py", line 3, in : - ``` - - - `"lib/a_name_error.py"` is the file the error occurred in. - - `line 3` is the line of code with the error. - - `` is the scope of the error. - -The type of error, the "who": - - ```console - NameError: - ``` - - This is a [Python Error Type](https://docs.python.org/3/tutorial/errors.html). - -The description, the "why": - - ```console - name 'hello_world' is not defined - ``` - - The interpreter does the best job it can to tell you what it thinks went wrong. - -You've solved games of _Clue_ with less information. This is one of the best -parts of programming: debugging and fixing errors. It's like you're a detective -solving a crime. The only bad thing is that more often than not, you're also the -criminal that caused the error in the first place. - -Errors are clues, and reading them is the interpreter telling you what to do to -fix the program and move on. - -*** - -## Three Common Error Types - -### Syntax Errors - -Syntax errors are pretty self-explanatory: they're the result of incorrect -syntax. Thankfully, they're usually followed by a guess about the location of -the error. For instance: - -```py -2 * # -``` - -Will result in: - -```console -File "", line 1 - 2 * # - ^ -SyntaxError: invalid syntax -``` - -Here, Python is saying that on line 1, there is a missing number (every `*` -operator must be preceded and followed by a number or variable with a numerical -value). Always read the full details of syntax errors and look for line numbers, -which usually appear at the beginning of the error message. - -### Logic Errors - -Logic errors are often difficult to find because they are not perceived as -errors by the Python interpreter itself. To find a logic error, a programmer -will often need to comb through their code line by line. Debugging tools such -as `pdb` (which we will cover later on in Phase 3) are very helpful for -locating and fixing logic errors. - -```py -count = 1 -while count < 100: - print("%i" % count) -``` - -Will produce the following output: - -```console -1 -1 -1 -1 -1 -1 -1 -... -``` - -The programmer here forgot to increase the count during each iteration of the -`while` loop. This is perfectly valid Python code, so the interpreter will not -throw an error, but the loop will continue forever until it is manually -stopped by the user. (The easiest way to do this in the terminal is `ctrl + c`) - -### Exceptions - -[Exceptions](https://docs.python.org/3/library/exceptions.html) cover a wide -variety of errors that you may see when running Python code. Our `NameError` -from earlier is one example of a Python exception. +This guide aims to help you understand and interpret Python error messages effectively. Error messages are valuable sources of information that can aid you in identifying issues within your code and guiding you toward resolving them. By comprehending error messages, you'll streamline your debugging process and enhance your coding skills. -Exceptions pop up when the interpreter knows what to do with a piece of code -but is unable to complete the action. A key difference between the other types -of errors and exceptions is that the Python interpreter can continue reading -your application after an exception- you just need to tell it what to expect. +## Table of Contents -There are many types of exceptions in Python; here are a few of the most -common: +- **Common Types of Errors** +- **Key Vocabulary** +- **Interpreting Error Messages** +- **Practical Examples** +- **Tips for Debugging** -#### AssertionError +## Common Types of Errors -An `assert()` statement tells the interpreter that the code inside of it must -proceed without error or exception. If an assertion fails, an AssertionError is -raised. +1. Syntax Errors: Violations of Python syntax rules leading to issues on specific lines. -```console -assert(1 == 2) -Traceback (most recent call last): - File "", line 1, in -AssertionError -``` +2. Indentation Errors: Incorrect indentation disrupting code block structure. -#### IndexError and KeyError +3. NameErrors: Referencing undefined names or variables. -IndexErrors arise when you try to access an element at an index past the end of -a list. Key errors relate to `dict` objects in Python (similar to JSON -objects). If a key is referenced but does not exist, this exception is thrown. +4. TypeErrors: Performing operations on incompatible data types. -```console -> list = [0, 1, 2, 3, 4] -> dict = {'a':1, 'b':2, 'c':3} +5. IndexErrors: Accessing lists or sequences with invalid indices. -> list[10] -Traceback (most recent call last): - File "", line 1, in -IndexError: list index out of range +6. KeyErrors: Trying to access non-existent keys in dictionaries. -> dict['d'] -Traceback (most recent call last): - File "", line 1, in -KeyError: 'd' -``` +7. ValueErrors: Passing inappropriate values to functions. -#### NameError +8. AssertionErrors: `assert` statements failing due to programming errors. -A NameError arises when a name is referenced before it has been defined. +## Key Vocabulary -```console -> flatiron_school -Traceback (most recent call last): - File "", line 1, in -NameError: name 'flatiron_school' is not defined -``` +- **Interpreter:** Program executing other programs; Python programs require it. +- **Python Shell:** Interactive interpreter accessible from command line. +- **Data Type:** Specific data categories determining valid operations. +- **Exception:** Anticipatable error handled to prevent program crash. +- **Code Block:** Group of indented code lines forming a unit. +- **Function:** Named code block performing actions when called. -#### TypeError +## Interpreting Error Messages -TypeErrors arise when an operation or function is applied to an object of the -wrong type. +1. **Error Type:** Identifies error type (e.g., SyntaxError, NameError). +2. **Error Message:** Briefly describes the issue. +3. **Line Number:** Shows error detection line. +4. **Context:** Displays surrounding code snippet. -```console -> wrong_type = 'abc' + 123 -Traceback (most recent call last): - File "", line 1, in -TypeError: can only concatenate str (not "int") to str -``` +## Practical Examples -*** +Explore real-world error scenarios and their interpretation using practical examples. -## Instructions +## Tips for Debugging -To get started, run `pytest -x` to run the first test in the test suite. -Use the error messages to guide your work: +1. **Read Carefully:** Examine error messages thoroughly. +2. **Check Line Numbers:** Focus on indicated line numbers. +3. **Review Context:** Study context around the error line. +4. **Google It:** Search for solutions online. +5. **Use Print Statements:** Track variable values and flow. +6. **Isolate Code:** Test problematic code separately. -- Read the errors. Scroll through the entire output to get a sense of what the - failures are trying to tell you. What does the error mean? How can we fix it? +# Contributing -- Each error prints out a **stack trace**, which points to where the code failed - and attempts to follow it _up the stack_ — that is, through the bits of - code that ran leading up to the failure. You can use these stack traces to - pinpoint which line(s) of code need your attention. +Explain how other developers can contribute to your project if you're open to contributions. -- These stack traces can also point you to which files you should run to get a - better sense of the errors. +Fork the repository. +Create a new branch. +Make your changes. +Submit a pull request. -Fix the errors in each of the files in `lib/`. Then confirm the fix by running -`pytest` again. +# License +This project is licensed under the [License Name] -Commit and push your work using `git` when all of your tests have passed! +Mastering Python error message interpretation enhances debugging skills, aiding in problem-solving and code improvement. Happy coding! From 5dbf3a00f3a7f99879db44ffa8dc19b513249557 Mon Sep 17 00:00:00 2001 From: "Mr.Perfect 092" <135037455+stephan-maina@users.noreply.github.com> Date: Fri, 1 Sep 2023 22:27:36 +0300 Subject: [PATCH 2/2] Add files via upload --- FileNotFoundError.py | 2 ++ a_Indentation_Error.py | 2 ++ a_key_error.py | 2 ++ a_name_error.py | 4 ++++ a_syntax_error.py | 4 ++++ a_type_error.py | 5 +++++ an_assertion_error.py | 8 ++++++++ an_index_error.py | 2 ++ 8 files changed, 29 insertions(+) create mode 100644 FileNotFoundError.py create mode 100644 a_Indentation_Error.py create mode 100644 a_key_error.py create mode 100644 a_name_error.py create mode 100644 a_syntax_error.py create mode 100644 a_type_error.py create mode 100644 an_assertion_error.py create mode 100644 an_index_error.py diff --git a/FileNotFoundError.py b/FileNotFoundError.py new file mode 100644 index 000000000..ca514217b --- /dev/null +++ b/FileNotFoundError.py @@ -0,0 +1,2 @@ +with open("nonexistent_file.txt", "r") as f: + content = f.read() diff --git a/a_Indentation_Error.py b/a_Indentation_Error.py new file mode 100644 index 000000000..4462e29db --- /dev/null +++ b/a_Indentation_Error.py @@ -0,0 +1,2 @@ +def greet(name): + print("Hello, " + name) diff --git a/a_key_error.py b/a_key_error.py new file mode 100644 index 000000000..9aff7157d --- /dev/null +++ b/a_key_error.py @@ -0,0 +1,2 @@ +my_dict = {'a': 1, 'b': 2} +value = my_dict['c'] diff --git a/a_name_error.py b/a_name_error.py new file mode 100644 index 000000000..b128ade1f --- /dev/null +++ b/a_name_error.py @@ -0,0 +1,4 @@ +print("Hello, World!") + + + diff --git a/a_syntax_error.py b/a_syntax_error.py new file mode 100644 index 000000000..c3549014b --- /dev/null +++ b/a_syntax_error.py @@ -0,0 +1,4 @@ +#!/usr/bin/env python3print("Hello, World!' + + +print("Hello, World!") diff --git a/a_type_error.py b/a_type_error.py new file mode 100644 index 000000000..a3e3efb24 --- /dev/null +++ b/a_type_error.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python3 +x = "5" +y = 2 +print(x + y) + diff --git a/an_assertion_error.py b/an_assertion_error.py new file mode 100644 index 000000000..16c597612 --- /dev/null +++ b/an_assertion_error.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +def divide(a, b): + assert b != 0, "Division by zero is not allowed" + return a / b + +result = divide(10, 0) +print(result) diff --git a/an_index_error.py b/an_index_error.py new file mode 100644 index 000000000..abc5c276e --- /dev/null +++ b/an_index_error.py @@ -0,0 +1,2 @@ +my_list = [1, 2, 3] +print(my_list[5])