https://zhuanlan.zhihu.com/p/24536868

学习参考于这个博文。

我做一个笔记。

关于python一些常用的语法快速的预览,适合已经掌握一门编程语言的人。零基础,没有任何编程经验的不适用快速入门。

基础数据类型

和其他主流语言一样,Python为我们提供了包括integer、float、boolean、strings等在内的很多基础类型。

数值类型

x = 3
print type(x) # Prints "<type 'int'>"
print x # Prints "3"
print x + 1 # Addition; prints "4"
print x - 1 # Subtraction; prints "2"
print x * 2 # Multiplication; prints "6"
print x ** 2 # Exponentiation; prints "9"
x += 1
print x # Prints "4"
x *= 2
print x # Prints "8"
y = 2.5
print type(y) # Prints "<type 'float'>"
print y, y + 1, y * 2, y ** 2 # Prints "2.5 3.5 5.0 6.25"

不过需要注意的是,Python并没有x++或者x--这样的自增或者自减操作符。另外,Python内置的也提供了长整型与其他复杂数值类型的整合,可以参考这里

布尔类型

Python提供了常见的逻辑操作符,不过需要注意的是Python中并没有使用&&、||等,而是直接使用了英文单词。

t = True
f = False
print type(t) # Prints "<type 'bool'>"
print t and f # Logical AND; prints "False"
print t or f # Logical OR; prints "True"
print not t # Logical NOT; prints "False"
print t != f # Logical XOR; prints "True"

字符串

Python对于字符串的支持还是很好的,不过需要注意到utf-8编码问题。

hello = 'hello'   # String literals can use single quotes
world = "world" # or double quotes; it does not matter.
print hello # Prints "hello"
print len(hello) # String length; prints "5"
hw = hello + ' ' + world # String concatenation
print hw # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatting
print hw12 # prints "hello world 12"

Python中的字符串对象还包含了很多有用的方法,譬如:

s = "hello"
print s.capitalize() # Capitalize a string; prints "Hello"
print s.upper() # Convert a string to uppercase; prints "HELLO"
print s.rjust(7) # Right-justify a string, padding with spaces; prints " hello"
print s.center(7) # Center a string, padding with spaces; prints " hello "
print s.replace('l', '(ell)') # Replace all instances of one substring with another;
# prints "he(ell)(ell)o"
print ' world '.strip() # Strip leading and trailing whitespace; prints "world"

可以在这里中查看详细的方法列表。

复杂数据类型

列表

Python中的列表等价于数组,不过其能够动态扩展并且能够存放不同类型的数值。

xs = [3, 1, 2]   # Create a list
print xs, xs[2] # Prints "[3, 1, 2] 2"
print xs[-1] # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo' # Lists can contain elements of different types
print xs # Prints "[3, 1, 'foo']"
xs.append('bar') # Add a new element to the end of the list
print xs # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop() # Remove and return the last element of the list
print x, xs # Prints "bar [3, 1, 'foo']"

同样你可以在文档中查看更多的细节。

切片

Python中对于数组的访问也相当人性化,通过简单的操作符即可以完成对于数组中子数组的截取。

nums = range(5)    # range is a built-in function that creates a list of integers
print nums # Prints "[0, 1, 2, 3, 4]"
print nums[2:4] # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print nums[2:] # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print nums[:2] # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print nums[:] # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print nums[:-1] # Slice indices can be negative; prints ["0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
print nums # Prints "[0, 1, 8, 9, 4]"

遍历

你可以使用基本的for循环来遍历数组中的元素,就像下面介个样纸:

animals = ['cat', 'dog', 'monkey']
for animal in animals:
print animal
# Prints "cat", "dog", "monkey", each on its own line.

如果你在循环的同时也希望能够获取到当前元素下标,可以使用enumerate函数:

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print '#%d: %s' % (idx + 1, animal)
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line

变换

在编程中我们经常需要对数组进行变换,比较著名的我们可以使用map、reduce、filter这几个函数,而在Python中提供了非常方便的List Comprehension操作符。譬如我们需要对数组中元素进行依次平方操作

nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
squares.append(x ** 2)
print squares # Prints [0, 1, 4, 9, 16]

我们可以简写为如下方式:

nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print squares # Prints [0, 1, 4, 9, 16]

List Comprehensions也支持进行条件选择:

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print even_squares # Prints "[0, 4, 16]"

字典

Python中的字典类型即类似于Java中的Map或者JavaScript中的Object,也就是所谓的键值对类型,基本的使用方式为:

d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print d['cat'] # Get an entry from a dictionary; prints "cute"
print 'cat' in d # Check if a dictionary has a given key; prints "True"
d['fish'] = 'wet' # Set an entry in a dictionary
print d['fish'] # Prints "wet"
# print d['monkey'] # KeyError: 'monkey' not a key of d
print d.get('monkey', 'N/A') # Get an element with a default; prints "N/A"
print d.get('fish', 'N/A') # Get an element with a default; prints "wet"
del d['fish'] # Remove an element from a dictionary
print d.get('fish', 'N/A') # "fish" is no longer a key; prints "N/A"

更多的语法细节可以参考这里

遍历

对于字典的遍历也非常简单:

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
legs = d[animal]
print 'A %s has %d legs' % (animal, legs)
# Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"

如果你希望同时访问键和其对应的值,可以使用iteritems方法:

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.iteritems():
print 'A %s has %d legs' % (animal, legs)
# Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"

变换

nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print even_num_to_square # Prints "{0: 0, 2: 4, 4: 16}"

Set

Set是一系列无序且唯一的元素的集合:

animals = {'cat', 'dog'}
print 'cat' in animals # Check if an element is in a set; prints "True"
print 'fish' in animals # prints "False"
animals.add('fish') # Add an element to a set
print 'fish' in animals # Prints "True"
print len(animals) # Number of elements in a set; prints "3"
animals.add('cat') # Adding an element that is already in the set does nothing
print len(animals) # Prints "3"
animals.remove('cat') # Remove an element from a set
print len(animals) # Prints "2"

更多语法细节可以参考这里

遍历

集合遍历的语法和数组遍历很类似,不过因为集合本身是无序的,因此你不能够依赖于遍历的顺序来预测集合中元素的顺序:

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
print '#%d: %s' % (idx + 1, animal)
# Prints "#1: fish", "#2: dog", "#3: cat"

变换

from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print nums # Prints "set([0, 1, 2, 3, 4, 5])"

Tuples

Python中的Tuple指不可变的有序元素集合,Tuple很类似于列表,不过区别在于Tuple可以做字典中的键类型,而列表则不可以。

d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6) # Create a tuple
print type(t) # Prints "<type 'tuple'>"
print d[t] # Prints "5"
print d[(1, 2)] # Prints "1"

Function:函数

Python中的函数使用def关键字进行定义,譬如:

def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero' for x in [-1, 0, 1]:
print sign(x)
# Prints "negative", "zero", "positive"

同时,Python中的函数还支持可选参数:

def hello(name, loud=False):
if loud:
print 'HELLO, %s!' % name.upper()
else:
print 'Hello, %s' % name hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True) # Prints "HELLO, FRED!"

更多的语法细节可以参考这里

Classes:类

Python中对于类的定义也很直接:

class Greeter(object):

    # Constructor
def __init__(self, name):
self.name = name # Create an instance variable # Instance method
def greet(self, loud=False):
if loud:
print 'HELLO, %s!' % self.name.upper()
else:
print 'Hello, %s' % self.name g = Greeter('Fred') # Construct an instance of the Greeter class
g.greet() # Call an instance method; prints "Hello, Fred"
g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"

可以参考这里获取更多信息。

python 基本语法速览,快速入门的更多相关文章

  1. 快看Sample代码,速学Swift语言(1)-语法速览

    Swift是苹果推出的一个比较新的语言,它除了借鉴语言如C#.Java等内容外,好像还采用了很多JavaScript脚本里面的一些脚本语法,用起来感觉非常棒,作为一个使用C#多年的技术控,对这种比较超 ...

  2. markdown预览-快速入门

    最近要写文档,领导指定用markdown. 这个两三年前用过两次的神器工具,都忘的差不多了. 为了熟练一点这个技能,决定好好的重新学一次. 于是乎:看快速入门文档 ...30分钟...看完文档发现要来 ...

  3. 人生苦短我用Python,本文助你快速入门

    目录 前言 Python基础 注释 变量 数据类型 浮点型 复数类型 字符串 布尔类型 类型转换 输入与输出 运算符 算术运算符 比较运算符 赋值运算符 逻辑运算符 if.while.for 容器 列 ...

  4. python 实现 PC 客户端自动化快速入门:pywinauto !

    本文转载自:http://www.lemfix.com/topics/420 一.前言 ​ 我们柠檬班的小可爱,在学完我们柠檬班自动化的课程之后,就掌握了接口自动化,web自动化,app自动化,这些工 ...

  5. aardio 编程语言快速入门 —— 语法速览

    本文仅供有编程基础的用户快速了解常用语法.如果『没有编程基础』 ,那么您可以通过学习任何一门编程语言去弥补你的编程基础,不同编程语言虽然语法不同 -- 编程基础与经验都是可以互通的.我经常看到一些新手 ...

  6. python视频教程:十分钟快速入门python

    想要学习python这门语言,却始终找不到一个全面的Python视频教程,倘若你是真心想学好一门语言,小编建议你亲自动手实践的.下面来看看入门python的学习教程. Python的语言特性 Pyth ...

  7. Python网络爬虫实战(一)快速入门

    本系列从零开始阐述如何编写Python网络爬虫,以及网络爬虫中容易遇到的问题,比如具有反爬,加密的网站,还有爬虫拿不到数据,以及登录验证等问题,会伴随大量网站的爬虫实战来进行. 我们编写网络爬虫最主要 ...

  8. python网络爬虫实战之快速入门

    本系列从零开始阐述如何编写Python网络爬虫,以及网络爬虫中容易遇到的问题,比如具有反爬,加密的网站,还有爬虫拿不到数据,以及登录验证等问题,会伴随大量网站的爬虫实战来进行. 我们编写网络爬虫最主要 ...

  9. 用Python进行实时计算——PyFlink快速入门

    Flink 1.9.0及更高版本支持Python,也就是PyFlink. 在最新版本的Flink 1.10中,PyFlink支持Python用户定义的函数,使您能够在Table API和SQL中注册和 ...

随机推荐

  1. 77.PS接收来自PL的按键中断

    本篇文章主要介绍外设(PL)产生的中断请求,在PS端进行处理. 在PL端通过按键产生中断,PS接受到之后点亮相应的LED. 本文所使用的开发板是zedboardPC 开发环境版本:Vivado 201 ...

  2. SurfaceFlinger 讲解

    SurfaceFlinger是Android multimedia的一个部分,在Android 的实现中它是一个service,提供系统 范围内的surface composer功能,它能够将各种应用 ...

  3. 191.Number of 1Bits---位运算---《剑指offer》10

    题目链接:https://leetcode.com/problems/number-of-1-bits/description/ 题目大意:与338题类似,求解某个无符号32位整数的二进制表示的1的个 ...

  4. Ural Sport Programming Championship 2015

    Ural Sport Programming Championship 2015 A - The First Day at School 题目描述:给出课程安排,打印一个课程表. solution 暴 ...

  5. Android 开发笔记(一) 按钮事件调用Activity

    UI创建按钮及事件 Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);mEmailSignInB ...

  6. ActiveMQ-Prefetch机制和constantPendingMessageLimitStrategy

    首先简要介绍一下prefetch机制.ActiveMQ通过prefetch机制来提高性能,这意味这 客户端的内存里可能会缓存一定数量的消息.缓存消息的数量由prefetch limit来控 制.当某个 ...

  7. Groovy 与 DSL

    一:DSL 概念 指的是用于一个特定领域的语言(功能领域.业务领域).在这个给出的概念中有 3个重点: 只用于一个特定领域,而非所有通用领域,比如 Java / C++就是用于通用领域,而不可被称为 ...

  8. Learning a Deep Compact Image Representation for Visual Tracking

    这篇博客对论文进行了部分翻译http://blog.csdn.net/vintage_1/article/details/19546953,不过个人觉得博主有些理解有误. 这篇博客简单分析了代码htt ...

  9. beego学习笔记(4):开发文档阅读(2)

    bee工具的安装和使用 bee 工具是一个为了协助快速开发 beego 项目而创建的项目,通过 bee 您可以很容易的进行 beego 项目的创建.热编译.开发.测试.和部署. go get gith ...

  10. 最直白、最易懂的话带你认识和学会---数据分析基础包之numpy的使用

    前言 numpy是一个很基础很底层的模块,其重要性不言而喻,可以说对于新手来说是最基础的入门必须要学习的其中之一.在很多数据分析,深度学习,机器学习亦或是人工智能领域的模块中,很多的底层都会用到这个模 ...