6 common python errors and solutions for beginners and 6 python reports for beginners

Source: Internet
Author: User

6 common python errors and solutions for beginners and 6 python reports for beginners

This article lists some common errors for new users to write code. Some errors are careless. However, for new users, it takes a long time to solve them. So I will summarize some of the problems I encountered here. I hope to help my new friends.

1. The NameError variable name is incorrect.

Error:

>>> print aTraceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'a' is not defined

Solution:

Assign a value to a first. To use it. When a NameError error is reported during actual code writing, check whether the variable is assigned a value, whether there is a case-insensitive error, or if the variable name is accidentally written incorrectly.

Note: In Python, you do not need to display the variable declaration statement. The variable is automatically declared when it is assigned a value for the first time.

>>> a=1>>> print a1

2. IndentationError code indent Error

Click return directory

Code:

a=1b=2if a<b:print a

Error:

IndentationError: expected an indented block

Cause:

Incorrect indentation. The indentation in python is very strict. If there are multiple spaces at the beginning of the line, an error will be reported if there are only one space. This is a common mistake for beginners because they are not familiar with python coding rules. Code blocks such as def, class, if, for, and while must be indented.

Indent to four spaces. Note that tabs (tab key) in different text editors indicate different spaces. If the Code requires cross-platform or cross-editor read/write, it is recommended that you do not use tabs.

Solution:

a=1b=2if a<b: print a

3. The AttributeError object property is incorrect.

Error:

>>> import sys>>> sys.PathTraceback (most recent call last):File "<stdin>", line 1, in <module>AttributeError: 'module' object has no attribute 'Path'

Cause:

The sys module does not have the Path attribute.

Solution:

Python is case sensitive. Path and path indicate different variables. Change Path to path.

>>> sys.path['', '/usr/lib/python2.6/site-packages']

Python knowledge development:

Use the dir function to view the attributes of a module

Copy codeThe Code is as follows: >>> dir (sys)
['_ Displayhook _', '_ doc _', '_ egginsert', '_ thook _', '_ name __', '_ package _', '_ plen', '_ stderr _', '_ stdin _', '_ stdout __', '_ clear_type_cache', '_ current_frames', '_ getframe', 'api _ version', 'argv', 'builtin _ lele_names ', 'byteorder ', 'Call _ tracing', 'callstats', 'copyright', 'displayhook', 'dont _ write_bytecode', 'exc _ clear', 'exc _ info ', 'exc _ type', 'mongothook', 'exec _ prefix', 'executable', 'exit ', 'flags', 'float _ info', 'getcheckinterval ', 'getdefaultencoding', 'signature', 'getfilesystemencoding', 'getprofile ', 'getrecursionlimit', 'getrefercount', 'getsize', 'gettrack', 'hversion', 'maxint ', 'maxsize', 'maxunicode ', 'meta _ path', 'modules', 'path', 'path _ hooks', 'path _ importer_cache ', 'platform ', 'prefix', 'ps1', 'ps2 ', 'py3kwarning', 'setcheckinterval', 'setdlopenflags ', 'setprofile', 'setrecursionlimit ', 'settrack', 'stderr ', 'stdin ', 'stdout', 'subversion', 'version', 'version _ info', 'warnopexception']

4. Incorrect TypeError type

4.1 The input parameter type is incorrect.

Code:

t=('a','b','c')for i in range(t): print a[i]

Error:

TypeError: range () integer end argument expected, got tuple.

Cause:

The range () function expects integer input parameters, but the input parameters are tuples (tuple)

Solution:

Change input parameter t to number of tuples integer len (t)

Change range (t) to range (len (t ))

4.2 The number of input parameters is incorrect.

4.2.1 using tuples as input parameters

Code:

# Coding = UTF-8 ''' Created on 2016-7-21 @ author: assumerproject: explicitly waits for ''' from selenium import webdriverfrom selenium. webdriver. common. by import Byfrom selenium. webdriver. support. ui import WebDriverWaitfrom selenium. webdriver. support import expected_conditions as ECfrom time import ctimedriver = webdriver. firefox () driver. get (r 'HTTP: // www.baidu.com/') loc = (. ID, 'kw ') print ctime () element = WebDriverWait (driver, 5, 0.5 ). until (EC. visibility_of_element_located (* loc) element. send_keys ('selenium ') print ctime () driver. quit ()

Error:

Traceback (most recent call last): File "D:\system files\workspace\selenium\autotestcombat\test_4_7_1_webdriverwait.py", line 18, in <module> element=WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(*loc))TypeError: __init__() takes exactly 2 arguments (3 given)

Cause:

The _ init _ () function of the class requires two parameters, but three parameters are actually provided.
The input parameters of the EC. visibility_of_element_located class should be two input parameters: self and metadata. However, two elements in the three parameters self and * loc are given as input parameters.

Solution:

Change EC. visibility_of_element_located (* loc) to EC. visibility_of_element_located (loc). The input parameter is a tuples, rather than two values in the tuples.

Python knowledge development:

Usage of input parameter *
Using tuples as function input parameters. If the asterisk (*) is added before the tuples, the input parameters passed are all elements in the tuples. If the asterisk (*) is not added before the tuples, the input parameter passed is the tuples themselves.

Example:
Loc = (By. NAME, 'email ')
Element1 = WebDriverWait (driver, 5, 0.5 ). until (EC. visibility_of_element_located (loc) # As long as one parameter (without considering self), The tuples loc, namely: (. NAME, 'email '). Directly transfer loc.
Element2 = driver. find_element (* loc) # requires two parameters: the element of the tuples loc, that is, By. NAME, 'email '. Directly transfer * loc

4.2.2 others

Error:

>>> import os>>> os.listdir()Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: listdir() takes exactly 1 argument (0 given)

Cause:

The listdir () function requires an input parameter, but only 0 input parameters are given.

Solution:

Add an input parameter

>>> os.listdir('/home/autotest')['hello.py', 'email126pro']

Python knowledge development:

You can use help to view how to use a function.

>>> help(os.listdir)Help on built-in function listdir in module posix:listdir(...)listdir(path) -> list_of_stringsReturn a list containing the names of the entries in the directory.path: path of directory to list

Note: The OS. listdir () function requires a path input parameter. The return value of the function result is a list composed of strings.

4.3 non-functions are called by functions

Error:

>>> t=('a','b','c')>>> t()Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'tuple' object is not callable

Cause:

T is a tuple, which cannot be called and cannot be added (). When writing code for beginners, they occasionally use variables as methods for calling (accidentally adding brackets ). Therefore, you must carefully check whether the variable is enclosed by brackets or the method is left empty.

Solution:

Remove the brackets.

>>> t('a', 'b', 'c')

5. IOError Input/Output Error

5.1 file does not exist Error

Error:

>>> f=open("Hello.py")Traceback (most recent call last):File "<stdin>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'Hello.py'

Cause:

The open () function does not specify the mode. The default mode is read-only. If the directory does not contain Hello. py file, you can check whether the spelling is correct, whether it is case-insensitive, or does not exist.

Solution:

The directory contains a hello. py file. open the file.

>>> F = open ("hello. py ") python knowledge development: How to view the current path of the python Interpreter: >>> import OS >>> OS. getcwd () '/home/autotest'

View the python interpreter files in the current path:

>>> os.listdir('/home/autotest')['hello.py', 'email126pro']

5.2 File Permission Error

Error:

>>> f=open("hello.py")>>> f.write("test")Traceback (most recent call last):File "<stdin>", line 1, in <module>IOError: File not open for writing

Cause:

Open ("hello. py ") if the read/write mode parameter is not added to the input parameter, it means that the file is opened in read-only mode by default, and the characters are written at this time. Therefore, if the permission is limited, an error is returned.

Solution:

Change Mode

>>> f=open("hello.py",'w+')>>> f.write("test")

6. Incorrect KeyError dictionary key value

Error:

Common Errors are: test an interface. The data returned by the interface is generally in json format. Test the interface to verify whether a value is correct. If the key is misspelled, A KeyError is reported. An example is as follows:

>>> d={'a':1,'b':2,'c':3}>>> print d['a']1>>> print d['f']Traceback (most recent call last):File "<stdin>", line 1, in <module>KeyError: 'f'

Solution:

Access key values in d, such as a, B, or c.

Recommendation Form:

In your opinion, the Python team should have this book order.

The Python book order will not meet

Ten good Python books to be missed

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.