Python beginners often make mistakes (Part 1)

Source: Internet
Author: User

 
In the past few months, I taught some children who did not know Python to familiarize themselves with the language. Gradually, I found some errors that almost all beginners of Python would make, so I decided to share my suggestions with you. Each part of this series focuses on different common errors, describes how to generate such errors, and provides solutions.
Use a variable value as the default value.
This is an absolute value that must be put first. Not only is the cause of this BUG very subtle, but it is also difficult to check this problem. Think about the following code snippet:
 

deffoo(numbers=[]):    numbers.append(9)    printnumbers

Here, we define a list (empty by default), add 9 to it and print it out.
 
>>> foo()[9]>>> foo(numbers=[1,2])[1,2,9]>>> foo(numbers=[1,2,3])[1,2,3,9]

Does it look okay? But when we do not enter the number parameter to call the foo function, the magic thing happens:
 
>>> foo()# first time, like before[9]>>> foo()# second time[9,9]>>> foo()# third time...[9,9,9]>>> foo()# WHAT IS THIS BLACK MAGIC?![9,9,9,9]

So, what is the situation? Intuition tells us that no matter how many times we do not enter the number parameter to call the foo function, 9 here should be allocated to an empty list. This is wrong! In Python, the default value of a function is instantiated when the function is defined, rather than called.
We will still ask why the default value is assigned different values when the function is called? Because every time you specify a default value for a function, Python stores this value. If you override the default value when calling a function, the stored value will not be used. If you do not override the default value, Python will make the default value reference the stored value (numbers in this example ). It does not copy the stored values to assign values to this variable. This concept may be difficult for beginners to understand, so it can be understood as follows: There are two variables: one is internal and the other is the current runtime variable. The reality is that we have two variables for interaction with the same value, so once the value of numbers changes, it will also change the record of the initial value stored in Python.
The solution is as follows:
 
deffoo(numbers=None):    ifnumbersisNone:        numbers=[]    numbers.append(9)    printnumbers

Generally, when people hear this, they will ask another question about the default value. Think about the following program:
 
deffoo(count=0):    count+=1    printcount

When we run it, the results are exactly what we expected:
 
>>> foo()1>>> foo()1>>> foo(2)3>>> foo(3)4>>> foo()1

Why? The secret is not when the default value is assigned, but the default value itself. An integer is an unchangeable variable. Unlike the list type, Integer Variables cannot be changed during function execution. When count + = 1 is executed, the original value of count is not changed. Instead, count points to different values. However, when we execute numbers. append (9), we change the original list. As a result, this result is returned.
The following is another problem that will occur when default values are used in functions:
Defprint_now (now = time. time ()):
Printnow

Same as above, time. the value of time () is variable, so it will only be calculated when the function is defined, no matter how many calls, will return the same event-the event output here is the time when the program was interpreted by Python.
 
>>> print_now()1373121487.91>>> print_now()1373121487.91>>> print_now()1373121487.91

* This problem is similar to its solution in Python 2.x and 3.x. It is the only difference in Python 3.x, yes. The print expression in it should be the function call method (print (numbers )).
* You should note that in the solution, if numbers is None instead of if not numbers. This is another common error. I am going to introduce it in the following article.

Related Article

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.