This article is a mirror article of machine translation, please click here to jump to the original article.

View: 13564|Reply: 1

[Communication] 17 common Python runtime errors for newbies

[Copy link]
Posted on 12/5/2015 1:08:56 PM | | |

When learning Python, it can be a bit complicated to understand the meaning of Python's error messages. Here is a list of some common runtime errors that cause your program to crash.


1) Forgot to add :( at the end of if, elif, else, for, while, class, def def def.

        The error will occur in code like this:

if spam == 42
    print("Hello!")

2) Use = instead of == (resulting in "SyntaxError: invalid syntax")

        = is the assignment operator and == is equal to the comparison operation.The error occurs in code like this:

if spam = 42:
    print("Hello!")

3) Incorrect use of indentation. (Resulting in "IndentationError:unexpected indent", "IndentationError:unindent does not match any outer indetation level", and "IndentationError:expected an indented block")

        Remember that indentation is only used after statements ending with: after which the indentation format must be reverted to the previous indentation format. The error occurs in code like this:

print("Hello!")
    print("Howdy!")
Or:
if spam == 42:
    print("Hello!")
  print("Howdy!")
Or:
if spam == 42:
print("Hello!")

4) Forgetting to call len() in the for loop statement (resulting in "TypeError: "list" object cannot be interpreted as an integer")

Usually you want to iterate over a list or string element through an index, which requires calling the range() function. Remember to return the len value instead of returning this list.

        The error occurs in code like this:

spam = ["cat", "dog", "mouse"]
for i in range(spam):
    print(spam)

5) Try to modify the value of the string (resulting in "TypeError: "str" object does not support item assignment")

        string is an immutable data type, and the error occurs in code like this:

spam = "I have a pet cat."
spam[13] = "r"
print(spam)

And you actually want to do this:

spam = "I have a pet cat."
spam = spam[:13] + "r" + spam[14:]
print(spam)

6) Trying to concatenate non-string values with strings (resulting in "TypeError: Can"t convert "int" object to str implicitly")

        The error occurs in code like this:

numEggs = 12
print("I have " + numEggs + " eggs.")

And you actually want to do this:

numEggs = 12
print("I have " + str(numEggs) + " eggs.")
Or:
numEggs = 12
print("I have %s eggs." % (numEggs))

7) Forgetting to put quotation marks at the beginning and end of the string (resulting in "SyntaxError: EOL while scanning string literal")

        The error occurs in code like this:

print(Hello!")
Or:
print("Hello!)
Or:
myName = "Al"
print("My name is " + myName + . How are you?")

8) Misspelling of variable or function names (resulting in "NameError: name "fooba" is not defined")

        The error occurs in code like this:

foobar = "Al"
print("My name is " + fooba)
Or:
spam = ruond(4.2)
Or:
spam = Round(4.2)

9) Misspelling of method names (resulting in "AttributeError: "str" object has no attribute "lowerr"")

        The error occurs in code like this:

spam = "THIS IS IN LOWERCASE."
spam = spam.lowerr()

10) References exceed list maximum index (resulting in "IndexError: list index out of range")

        The error occurs in code like this:

spam = ["cat", "dog", "mouse"]
print(spam[6])

11) Using a dictionary key value that doesn't exist (resulting in "KeyError: 'spam'")

        The error occurs in code like this:

spam = {"cat": "Zophie", "dog": "Basil", "mouse": "Whiskers"}
print("The name of my pet zebra is " + spam["zebra"])

12) Trying to use Python keyword as variable name (resulting in "SyntaxError: invalid syntax")

        Python key cannot be used as a variable name, the error occurs in code like this:

class = "algebra"

Python3 keywords are: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield


13) Using value-added operators in a defined new variable (resulting in "NameError: name "foobar" is not defined")

        Don't use 0 or null strings as initial values when declaring variables, so that a sentence spam += 1 using the self-incrementing operator is equal to spam = spam + 1, which means that spam needs to specify a valid initial value.

        The error occurs in code like this:

spam = 0
spam += 42
eggs += 42

14) Use local variables in functions before defining local variables (in this case, there is a global variable with the same name as the local variable) (resulting in "UnboundLocalError: local variable "foobar" referenced before assignment")

        It is complicated to use a local variable in a function with the same name as a global variable, and the rules of use are: if anything is defined in a function, if it is only used in the function, it is local, and vice versa.

        This means that you can't use it in a function as a global variable before defining it.

        The error occurs in code like this:

someVar = 42
def myFunction():
    print(someVar)
    someVar = 100
myFunction()

15) Trying to create an integer list with range() (resulting in "TypeError: "range" object does not support item assignment")

        Sometimes you want to get an ordered list of integers, so range() seems like a good way to generate this list. However, you need to remember that range() returns a "range object", not the actual list value.

        The error occurs in code like this:

spam = range(10)
spam[4] = -1

Maybe this is what you want to do:

spam = list(range(10))
spam[4] = -1
(Note: spam = range(10) works in Python 2, because in Python 2 range() returns a list value, but in Python 3 the above error is generated)

16) Nice in ++ or -- self-increment operator. (Resulting in "SyntaxError: invalid syntax")

        If you are used to other languages such as C++, Java, PHP, etc., you may want to try using ++ or -- increment and subtract a variable. There is no such operator in Python.

        The error occurs in code like this:

spam = 1
spam++

Maybe that's what you want to do:

spam = 1
spam += 1

17) Forgot to add the self parameter to the first argument of the method (resulting in "TypeError: myMethod() takes no arguments (1 given)")

        The error occurs in code like this:

class Foo():
    def myMethod():
        print("Hello!")
a = Foo()
a.myMethod()





Previous:WiFi Wireless Cracking Software + Tutorial (Water Droplet)
Next:【iOS Development Series Tutorial Released in the Summer】IOS project source code
Posted on 12/5/2015 1:34:16 PM |
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com