Python

初入Python世界

2018-07-31  本文已影响63人  逆风g

Python是一门解释型的高级编程语言,同时也是一门脚本语言。编译型语言、解释型语言、脚本语言之间有何区别呢?

深度学习中为什么选择Python

  1. Python语言非常简洁明了,能以很少的代码实现复杂的功能:
# 打开文件目录
path = '/Users/gcf/Desktop/Image/'
dirs = os.listdir( path )

# 输出Image下所有文件和文件夹
for file in dirs:
   print file
  1. Python语言扩充性好,非常轻松地调用其他语言编写的模块。模块底层复杂且对效率要求高的模块用C/C++等语言实现,顶层调用的API用Python封装。这可以使得无须花费很多时间在编程实现上,更多时间用在思考问题的逻辑上。
  2. Python拥有非常多的资源库,常用的功能都能找到对应的库,并且安装和调用都非常方便:
    安装专门用于科学计算的numpy库
    pip install numpy
# 导入numpy库
import numpy as np
# 使用numpy创建一个数组
data = np.array([3,4,5,6])
  1. Python 是跨平台且开源的,Python写代码同时能在Linux,Windows 以及 macOS 上跑起来。
  2. 现今的各大深度学习框架,要么官方接口就是Python,要么支持Python接口。像常用的TensorFlow、Caffe、Keras、MXNet、Theano等框架都是支持Python语言的。

2018年5月份编程语言排行榜


可以看到Python语言排名还是挺靠前的。

安装Python

实际安装命令以Homebrew主页显示为准

Python2与Python3区别

# py2
>>> print 'hello world! '
hello world!
>>> print ('hello world!')
hello world!
# py3
>>> print ('hello world!')
hello world!
# py2
>>> number = input('enter a number:')
enter a number:111
>>> type(number)
<type ‘int’>
>>> number = raw_input('enter a number:')
enter a number:111
>>> type(number)
<type ‘str’>
# py3
>>> number = input('enter a number: ')
enter a number: 111
>>> type(number)
<class ‘str’>
# py2
>>> print 5.0/2
2.5
>>> print 5/2
2
>>> print 5%2
1
>>> print 5//2
2
# py3
>>> print 5.0/2
2.5
>>> print 5/2
2.5
>>> print 5%2
1
>>> print 5//2
2

还有很多不一一说明。

python基础语法

>>> a =1.0
>>> type(a)
<type ‘float’>
>>> a = ‘hello’
>>> type(a)
<type ‘str’>
>>> 
# person.py
class Person:
    def __init__(self,name,age,height,weight):
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight
    def exercise(self):
        self.weight -= 1
        print 'Exercise makes me thin.'
    def sleep(self):
        self.height += 1
        print 'Sleep makes me grow taller.'
# test.py
import person
p = person.Person('li lei',15,165,60)
p.sleep()
for i in range(5):
    p.exercise()
print p.name
print p.age
print p.height
print p.weight

打印结果:

Sleep makes me grow taller.
Exercise makes me thin.
Exercise makes me thin.
Exercise makes me thin.
Exercise makes me thin.
Exercise makes me thin.
li lei
15
166
55

如何使用Python语言编程

  1. 交互式编程
    在终端输入python命令,输入编写的代码内容即可:


  2. 脚本式编程
    把要编写的代码内容保存在一个文本文件里,以 .py 为扩展名,如:test.py
    print 'hello word!’
    再在终端先进入test.py的目录,然后执行python test.py
  3. 使用IDE工具直接run,比如PyCharm:



上一篇 下一篇

猜你喜欢

热点阅读