prof-rossetti / intro-to-python

An Introduction to Programming in Python
Other
97 stars 244 forks source link

Common Errors #47

Open s2t2 opened 4 years ago

s2t2 commented 4 years ago

Some students were asking for a list of common errors, like what do I do when I see "TypeError: list indices must be integers or slices, not str"

s2t2 commented 4 years ago
s2t2 commented 4 years ago

See also: https://docs.python.org/3/library/exceptions.html#base-classes

s2t2 commented 4 years ago

TypeError: ... object is not subscriptable

setup code:

x = None
x["message"] #> TypeError: ______ object is not subscriptable
x[0] #> TypeError: ______ object is not subscriptable
s2t2 commented 4 years ago

SyntaxError: invalid syntax

stack trace:

  File "/Users/mjr/projects/s2t2/tweet-analysis-py/app/retweet_graphs_v2/k_days_grapher.py", line 18
    def get_daily_periods(start_date=START_DATE, k_days=K_DAYS, n_periods=N_PERIODS)
                                                                                   ^
SyntaxError: invalid syntax

Reason: forgot a colon (can happen during function definition, for loop, if statement, etc.)

s2t2 commented 4 years ago

Practice Problem

Can you spot the solution for this SyntaxError?


    print(logstamp(), "|", fmt_n(self.counter), "|", fmt_n(edge_count) "EDGES")
                                                                             ^
SyntaxError: invalid syntax

Your answer here:

s2t2 commented 4 years ago

The interpreter says there's an error with code ABC on line X. You update the code its talking about. Then you run the script but it gives the same error message (reflecting the original code, not the updated code.

Lesson: remember to save your .py file before executing it 😸

s2t2 commented 4 years ago

The given code:

# web_app/routes/home_routes.py

from flask import Blueprint, render_template

home_routes = Blueprint("home_routes", __name__)

@home_routes.route("/")
def index():
    print("VISITED THE HOME PAGE")
    return render_template("home.html")

@home_routes.route("/about")
def about():
    print("VISITED THE ABOUT PAGE")
    return render_template("about.html")

@home_routes.route("/register")
def register():
    print("VISITED THE REGISTRATION PAGE")
    return render_template("register.html")

@home_routes.route("/topics")
def register():
    print("VISITED THE TOPICS PAGE")
    return render_template("topics.html", event_name="impeachment")

... produces the following Flask error:

AssertionError: View function mapping is overwriting an existing endpoint function: home_routes.register

Can you fix?

Answer:

There are two "register" functions. Need to rename the last one.

s2t2 commented 4 years ago

Error:

IndentationError: unindent does not match any outer indentation level

Cause: look at the beginning of the line it's talking about. And indent it properly.