Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common Python runtime errors made by novices?

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What are the common Python runtime errors for beginners? I believe many inexperienced people don't know what to do about it. Therefore, this article summarizes the causes and solutions of the problems. Through this article, I hope you can solve this problem.

When you are new to Python, it can be a bit complicated to understand the meaning of Python's error message. Here are some common runtime errors that make your program crash.

1) forgot to add: (causes "SyntaxError: invalid syntax") at the end of the if, elif, else, for, while, class, def declaration

The error will occur in code similar to the following:

If spam = = 42 print ('hellograms')

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

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

If spam = 42: print ('hellograms')

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 increments are used only after statements that end with:, and then you must revert to the previous indentation format. The error occurs in the following code:

Print ('Hellobirds') Print ('howdyboy')

Or:

If spam = = 42: print ('hellograms') Print ('howdyboy')

Or:

If spam = = 42: print ('hellograms')

4) forgot 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 an list or string element through an index, which requires a call to the range () function. Remember to return the len value instead of the list.

The error occurs in the following code:

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

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

String is an immutable data type, and the error occurs in the following code:

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

And here's what you actually want to do:

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

6) attempt to connect non-string values to strings (resulting in "TypeError: Can't convert 'int' object to str implicitly")

The error occurs in the following code:

NumEggs = 12 print ('I have'+ numEggs + 'eggs.')

And here's what you actually want to do:

NumEggs = 12 print ('I have'+ str (numEggs) + 'eggs.')

Or:

NumEggs = 12 print ('I have% s eggs.'% (numEggs))

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

The error occurs in the following code:

Print (hellograms')

Or:

Print ('Hello!)

Or:

MyName = 'Al' print (' My name is'+ myName +. How are you?')

8) variable or function name misspelled (resulting in "NameError: name 'fooba' is not defined")

The error occurs in the following code:

Foobar = 'Al' print (' My name is'+ fooba)

Or:

Spam = ruond (4.2)

Or:

Spam = Round (4.2)

9) method name misspelled (resulting in "AttributeError: 'str' object has no attribute' lowerr'")

The error occurs in the following code:

Spam = 'THIS IS IN LOWERCASE.' Spam = spam.lowerr ()

10) reference exceeds the list*** index (resulting in "IndexError: list index out of range")

The error occurs in the following code:

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

11) use dictionary keys that do not exist (resulting in "KeyError:'spam'")

The error occurs in the following code:

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

12) try using the Python keyword as the variable name (resulting in "SyntaxError:invalid syntax")

The Python key cannot be used as a variable name, and the error occurs in the following code:

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) use the value-added operator in a new variable definition (resulting in "NameError: name 'foobar' is not defined")

Do not use 0 or an empty string as the initial value when declaring variables, so a sentence using the self-increment operator spam + = 1 equals spam = spam + 1, which means that spam needs to specify a valid initial value.

The error occurs in the following code:

Spam = 0 spam + = 42 eggs + = 42

14) use local variables in the function before defining local variables (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 while there is a global variable of the same name. The rule is: if anything is defined in the function, if it is only used in the function, it is local, and vice versa.

This means that you cannot use it as a global variable in a function before defining it.

The error occurs in the following code:

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

15) try to create a list of integers using 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 "range object", not the actual list value.

The error occurs in the following code:

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

Maybe that's what you want to do:

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

(note: spam = range (10) works in Python 2, because range () returns a list value in Python 2, but the above error occurs in Python 3.)

16) not bad in the + + or-self-increasing and self-subtracting operators. (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-add and minus a variable. There is no such operator in Python.

The error occurs in the following code:

Spam = 1 spam++

Maybe that's what you want to do:

Spam = 1 spam + = 1

17) forgot to add self parameters to the * parameters of the method (resulting in "TypeError: myMethod () takes no arguments (1 given)")

The error occurs in the following code:

Class Foo (): def myMethod (): print ('hellograms') A = Foo () a.myMethod () after reading the above, have you mastered the methods of common Python runtime errors for beginners? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report