Question:
What are common syntax errors and exceptions in Python

Common syntax errors and exceptions in Python are issues that can occur when writing or running Python code. These errors and exceptions are typically related to the structure and rules of the Python language. Here are some of the most common ones:

1. SyntaxError:

  • Unclosed Quotes: Forgetting to close a string with a matching quotation mark (single or double).
  • Unclosed Parentheses, Brackets, or Braces: Forgetting to close parentheses, brackets, or curly braces.
  • Incorrect Indentation: Inconsistent or incorrect use of spaces or tabs for indentation.
  • Missing Colon: Forgetting to add a colon after statements that require one, such as in loops or function definitions.
  • Invalid Character: Using characters that are not valid in Python code.

# Examples of SyntaxErrors
print(“Hello) # Unclosed quote
if x > 5 # Missing colon
 print(x)

2. IndentationError:

  • Inconsistent indentation within the same block of code.

# Example of an IndentationError
if x > 5:
 print(x)
 print(“Indented incorrectly”) # Inconsistent indentation

3. NameError:

  • Attempting to use a variable or function that has not been defined.

# Example of a NameError
print(variable_does_not_exist)

4. TypeError:

  • Performing an operation on a data type that is not supported, or passing the wrong number or type of arguments to a function.

# Examples of TypeErrors
result = 10 + “5” # Adding int and str
print(“Hello”, 42, 3, sep=”,”) # Incorrect number of arguments for sep parameter

5. IndexError:

  • Attempting to access an element of a list, tuple, or string using an index that is out of range.

# Example of an IndexError
my_list = [1, 2, 3]
print(my_list[5]) # Index 5 is out of range

6. KeyError:

  • Trying to access a dictionary key that does not exist.

# Example of a KeyError
my_dict = {“name”: “John”, “age”: 30}
print(my_dict[“address”]) # “address” key does not exist

7. ValueError:

  • Occurs when a function receives an argument of the correct data type but an inappropriate value.

# Example of a ValueError
int(“abc”) # Cannot convert “abc” to an integer

8. FileNotFoundError:

  • Trying to open or manipulate a file that does not exist.

# Example of a FileNotFoundError
with open(“nonexistent_file.txt”, “r”) as file:
 content = file.read()

More  Questions

>ASP.Net Core app development with Angular tutorial

>CRUD Operations In ASP.NET Core Using Entity Framework Core Code First with Angularjs-Asp.net

>ChatGPT: Features, advantages & disadvantages

>ASP.Net Core API with Android Studio Code

>Build ASP.NET Core App with Angular

Ritu Singh

Ritu Singh

Submit
0 Answers