Python 学习之二:Python超短教程

前言

本教程综合Stanford CS231N和UC Berkerley CS188的Python教程。 教程很短,但适合有一定编程基础,学过其他语言的童鞋。

Python启动Python 解释器

Python可以有两种使用方式,一种就是使用解释器interpreter,类似Matlab,输入一行代码,运行一行;另一种就是编写一个py后缀的文档,称为脚本,然后python xxx.py运行脚本script。这里我们使用解释器。 在已安装Python的情况下,在Terminal输入python,可以启动Python:

pythondcafa7e5f, , ) [. build 5666) (dot 3)] on darwinmore information.>>>

这里我是使用2.7.9版本的Python

操作符

在Python解释器中,使用>>>来表示一行代码,类似Matlab(使用<<) 先是最基本的操作符+,,-,*,/:

* / / 3.10.6451612903225806

接下来还有常用的次方运算,采用**

** 38数据类型

Python和其他语言很大的不同就是Python不需要定义数据类型,数据类型是根据数据的情况自行确定的。 比如上面的运算,输入3就是整型,输入3.1就是浮点数

数字x=(x) # Prints x + x * 2 # Multiplication; prints “6”print x ** 2 # Exponentiation; prints “9”x += 1print x # Prints “4”

注意Python不支持x++或者x–的操作

布尔量Boolean

用True和False表示

f = Falset t # Logical NOT; prints “False”

这里要注意Python中不使用&&, ||,!来表示与,或,非 而是直接使用英语and,or,not

(1==0)True>>> (2==2) and (2==3)False>>> (2==2) or (2==3)True字符串hello = ‘hello’ # String literals can use single quotesworld = hello # Prints “hello”print len(hello) # String length; prints “5”hw = hello + ‘ ‘ + world # String concatenationprint hw # prints “hello world”hw12 = hw12 # prints “hello world 12

有很多现成的方法对字符串进行操作:

s.rjust(7) # Right-justify a string, padding with spaces;print s.center(7) # Center a string, padding with spaces; printsprint s.replace(‘l’, ‘(ell)’) # Replace all instances of one substri# prints “he(ell)(ell)o”

事实上,不管是用单引号还是双引号都是一样的。

>>> a = ‘hello’>>> ab’hello’>>> a == bTrue

那么,我们可以通过dir和help来查看某个类型对应的methods.

>>> a = ‘hello’>>> dir(a)[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__getslice__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘_formatter_field_name_split’, ‘_formatter_parser’, ‘capitalize’, ‘center’, ‘count’, ‘decode’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isdigit’, ‘islower’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]>>> help(a.find)Help :find(…)S.find(sub [,start [,end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start slice notation.Return -1 on failure.

上面的help之后按Q退出查看。

数据结构List列表>>> fruits = [‘apple’,’orange’,’pear’,’banana’]>>> fruits[0]’apple’也就越容易失败,还不如怀揣一颗平常心,

Python 学习之二:Python超短教程

相关文章:

你感兴趣的文章:

标签云: