Home Backend Development Python Tutorial Python学习笔记整理3之输入输出、python eval函数

Python学习笔记整理3之输入输出、python eval函数

Jun 10, 2016 pm 03:07 PM

1. python中的变量:

python中的变量声明不需要像C++、Java那样指定变量数据类型(int、float等),因为python会自动地根据赋给变量的值确定其类型。如 radius = 20,area = radius * radius * 3.14159 ,python会自动的将radius看成“整型”,area看成“浮点型”。所以编程时不用再像之前那样小心翼翼的查看数据类型有没有出错,挺人性化的。

2. input和print:

先贴个小的程序

# 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)
Copy after login

小程序中的几个知识点:

1)print的格式,print(itme1, item2, ..., itemk),如果print的内容过长,可以直接换行;
2)'/'符号,它是用来连接两个行的,如果一行内容过长可以用该符号来分割;
3)input(" "),获得输入数据,要注意的是,python2.x版本中有两个输入函数input()和raw_input(),input()输入实数时,它的值就是实数;而raw_input()不管输入的是什么,它的值都是string,所以需要用eval()函数将值转换为实数,eval()下面再深入学习;而在python3.x版本中只有一个输入函数input(),它的功能就相当于python2.x中的raw_input()函数,所以编程时要特别注意版本问题,像这样的差异还有许多。我的程序是在python3.2下解释的,如果在python2.x下,可以去掉eval()或者将input改成raw_input,结果一样。

3. eval()函数

上面的小程序中用到了eval()函数,功能是将string变成算术表达式来执行,比如eval("1+2")的结果是3。那么是不是它的功能就局限于此呢?
在这个基础上,我查了python官方文档关于eval函数的定义和解释。官网python3.4.1文档中关于eval的定义如下:
eval(expression, globals=None, locals=None) --- 官方文档中的解释是,globals和locals参数是可选的,如果提供了globals参数,那么它必须是dictionary类型;如果提供了locals参数,那么它可以是任意的map对象。

在继续往下之前,要先补充一点关于python命名空间的知识(引用自http://blog.sina.com.cn/s/blog_64668ff00100od2b.html),python是用命名空间来记录变量的轨迹的,命名空间是一个dictionary,键是变量名,值是变量值。

在一个 Python 程序中的任何一个地方,都存在几个可用的名字空间。每个函数都有着自已的名字空间,叫做局部名字空间,它记录了函数的变量,包括函数的参数和局部定义的变 量。每个模块拥有它自已的名字空间,叫做全局名字空间,它记录了模块的变量,包括函数、类、其它导入的模块、模块级的变量和常量。还有就是内置名字空间, 任何模块均可访问它,它存放着内置的函数和异常。

当一行代码要使用变量 x 的值时,Python 会到所有可用的名字空间去查找变量,按照如下顺序:

1)局部名字空间 - 特指当前函数或类的方法。如果函数定义了一个局部变量 x, 或一个参数 x,Python 将使用它,然后停止搜索。

2)全局名字空间 - 特指当前的模块。如果模块定义了一个名为 x 的变量,函数或类,Python 将使用它然后停止搜索。

3)内置名字空间 - 对每个模块都是全局的。作为最后的尝试,Python 将假设 x 是内置函数或变量。

其实这并不难理解,说白了,就是c++中全局变量和局部变量的意思。比如你在一个函数中用了num这个变量,它首先会查找函数里,也就是局部名字空间是否有这个变量名;如果找不到,就会到函数外也就是全局名字空间中继续查找;如果再找不到,就会查找内置关键字;如果都找不到,那么就只有报NameError了。

理解了这一点,就比较容易了。python的全局名字空间存储在一个叫globals()的dict对象中;局部名字空间存储在一个叫locals()的dict对象中。我们可以用print (locals())来查看该函数体内的所有变量名和变量值。继续eval()函数...

1)当后两个参数都为空时,很好理解,就是一个string类型的算术表达式,计算出结果即可。等价于eval(expression)。

2)当locals参数为空,globals参数不为空时,先查找globals参数中是否存在变量,并计算。

3)当两个参数都不为空时,先查找locals参数,再查找globals参数。

举一个小例子:

#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()
Copy after login

num1的值不用说,是2;num3的值也很好理解,是4;num2的值呢?由于提供了globals()参数,那么首先应当找全局的x和y值,也就是都为1,那么显而易见,num2的值也是2。如果注释掉该句,执行下面一句呢?根据第3)点可知,结果为4。(PS:我的运行环境是python3.2)当然,也可以显式的定义dict对象作为eval()的参数,规则是一样的。

补充一下:locals()对象的值不能修改,globals()对象的值可以修改,写一个小程序测试一下。

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

可以得出,两个print (locals())的结果是一样的,说明没有修改成功。而print (z)的值是2,说明修改成功了。另外,貌似locals()可以添加变量,感兴趣的可以试一下。

以上内容是小编给大家分享的Python学习笔记整理3之输入输出、python eval函数的全部叙述,希望大家喜欢。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles