Python learning notes sorting 3: input and output, python eval function,

Source: Internet
Author: User
Tags print format

Python learning notes sorting 3: input and output, python eval function,

1. Variables in python:

Variable declaration in python does not need to specify the variable data type (int, float, etc.) like C ++ or Java, because python automatically determines the type based on the value assigned to the variable. For example, if radius = 20 and area = radius * 3.14159, python automatically regards radius as an "integer" and area as a "floating point ". Therefore, you do not have to carefully check whether there are any errors in the data type as you did before. This is user-friendly.

2. input and print:

Paste a small program first

# Prompt the user to enter three numbersnumber1 = eval(input("Enter the first number: "))number2 = eval(input("Enter the second number: "))number3 = eval(input("Enter the third number: "))# Compute averageaverage = (number1 + number2 + /      number3) / 3#Display resultprint("The average of ", number1, number2, number3,   "is", average)

Tips in the Applet:

1) print format: print (itme1, item2,..., itemk). If the print content is too long, you can directly wrap it;
2) '/', which is used to connect two rows. If the content of a row is too long, you can use this symbol to separate it;
3) input (""). When two input functions, input (), raw_input (), and input (), are available in python2.x to obtain input data, its value is a real number, and raw_input (), no matter what the input is, its value is a string, so you need to use the eval () function to convert the value to a real number, eval () next, let's take a deeper look. In python3.x, there is only one input function input (), which is equivalent to the raw_input () function in python2.x. Therefore, pay special attention to the version issue during programming, there are many differences like this. My program is explained in python3.2. If python2.x is used, you can remove eval () or change input to raw_input. The result is the same.

3. eval () function

The eval () function is used in the preceding applet to convert string into an arithmetic expression for execution. For example, the result of eval ("1 + 2") is 3. Is its function limited?
On this basis, I checked the eval function definition and explanation in the python official documentation. The eval definition in python3.4.1 is as follows:
Eval (expression, globals = None, locals = None) --- the explanation in the official document is that the globals and locals parameters are optional. If the globals parameter is provided, it must be of the dictionary type; if the locals parameter is provided, it can be any map object.

Before moving on, add a bit of knowledge about the python namespace (reference from the http://blog.sina.com.cn/s/blog_64668ff00100od2b.html), python uses the namespace to record the trajectory of the variable, the namespace is a dictionary, the key is the variable name and the value is the variable value.

There are several available namespaces in any part of a Python program. Each function has its own namespace, which is called a local namespace. It records the function variables, including the function parameters and the volume of locally defined changes. Each module has its own namespace, which is called a global namespace. It records module variables, including functions, classes, other imported modules, module-level variables, and constants. There is also a built-in namespace, which can be accessed by any module. It stores built-in functions and exceptions.

When a line of code uses the value of variable x, Python searches for variables in all available namespaces in the following order:

1) local namespace-This refers to the method of the current function or class. If a function defines a local variable x or a parameter x, Python uses it and then stops searching.

2) global namespace-This refers to the current module. If the module defines a variable, function, or class named x, Python uses it and then stops searching.

3) built-in namespace-Global for each module. As a final attempt, Python assumes that x is a built-in function or variable.

In fact, this is not difficult to understand. To put it bluntly, it is the meaning of global variables and local variables in c ++. For example, if you use the num variable in a function, it first finds whether the variable name exists in the function, that is, the local namespace. If the variable name cannot be found, the search will continue outside the function, that is, the global namespace. If no search is found, the built-in keywords will be searched. If no search is found, only the NameError will be reported.

It is easier to understand this point. The global namespace of python is stored in a dict object named globals (), and the local namespace is stored in a dict object named locals. We can use print (locals () to view all the variable names and variable values in the function. Continue eval () function...

1) when the last two parameters are empty, it is easy to understand that it is a string-type arithmetic expression and can be computed. It is equivalent to eval (expression ).

2) When the locals parameter is null and the globals parameter is not empty, first check whether there is a variable in the globals parameter and calculate it.

3) when neither of the two parameters is null, search for the locals parameter first and then the globals parameter.

Here is a small example:

#test eval() and locals()x = 1y = 1num1 = eval("x+y")print (num1)def g():   x = 2   y = 2   num3 = eval("x+y")  print (num3)    num2 = eval("x+y",globals())   # num2 = eval("x+y",globals(),locals())  print (num2)g()

Needless to say, the value of num1 is 2. The value of num3 is also well understood. It is 4. What about the value of num2? Because the globals () parameter is provided, we should first find the global x and y values, that is, 1. Obviously, the value of num2 is also 2. If this sentence is commented out, what about the following sentence? According to 3rd), the result is 4. (PS: My runtime environment is python3.2) Of course, you can also explicitly define the dict object as the eval () parameter, and the rules are the same.

Add: the value of the locals () object cannot be modified. The value of the globals () object can be modified. Write a applet to test the value.

#test globals() and locals()z=0def f(): z = 1  print (locals())    locals()["z"] = 2  print (locals())  f() globals()["z"] = 2print (z)

We can conclude that the two print (locals () results are the same, indicating that the modification was not successful. The value of print (z) is 2, indicating that the modification is successful. In addition, it seems that locals () can be used to add variables. If you are interested, try it.

The above content is a small series of Python learning notes for everyone to share 3 input and output, all the descriptions of the python eval function, I hope you will like it.

Articles you may be interested in:
  • Python eval () function Risk Analysis
  • Python executes the string expression function (eval exec execfile)
  • Exec and eval instances in Python
  • Invalid syntax Error when calling eval function in python Study Notes

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.