第一个源程序

​#!/usr/bin/python
# Filename : helloworld.py​

​print​​ ​​'Hello world'​

执行:

​$ python helloworld.py ​​或者 $ ./helloworld.py 

因为系统知道它必须用源文件第一行指定的那个解释器来运行程序

 

字面值常量:

​'This is a string'、"It's a string!"​​这样的字符串

在Python中有4种类型的数——整数、长整数、浮点数和复数。

  • ​2​​是一个整数的例子。
  • 长整数不过是大一些的整数。
  • ​3.23​​和​​52.3E-4​​是浮点数的例子。E标记表示10的幂。在这里,​​52.3E-4​​表示​​52.3 * 10​-4
  • ​(-5+4j)​​和​​(2.3-4.6j)​​是复数的例子。 
变量

  它们的值可以变化,即你可以使用变量存储任何东西。

标识符的命名

变量是标识符的例子。 标识符 是用来标识 某样东西 的名字。在命名标识符的时候,你要遵循这些规则:

  • 标识符的第一个字符必须是字母表中的字母(大写或小写)或者一个下划线(‘ _ ’)。
  • 标识符名称的其他部分可以由字母(大写或小写)、下划线(‘ _ ’)或数字(0-9)组成。
  • 标识符名称是对大小写敏感的。例如,mynamemyName不是一个标识符。注意前者中的小写n和后者中的大写N。
  • 有效 标识符名称的例子有i__my_namename_23a1b2_c3
  • 无效 标识符名称的例子有2thingsthis is spaced outmy-name
数据类型

变量可以处理不同类型的值,称为数据类型。基本的类型是数和字符串,我们已经讨论过它们了。在后面的章节里面,我们会研究怎么用​​类​​创造我们自己的类型。

缩进

在逻辑行首的空白(空格和制表符)用来决定逻辑行的缩进层次,从而用来决定语句的分组。

这意味着同一层次的语句必须有相同的缩进。每一组这样的语句称为一个

你需要记住的一样东西是错误的缩进会引发错误。例如:

​i = ​​​​5​

 ​​print ​​​​'Value is'​​​​, i ​​​​# Error! Notice a single space at the start of the line​

​print ​​​​'I repeat, the value is'​ ​​​, i​

当你运行这个程序的时候,你会得到下面的错误:

​  File "whitespace.py", line 4
    print 'Value is', i # Error! Notice a single space at the start of the line
    ^
SyntaxError: invalid syntax ​

它告诉你, 你不能随意地开始新的语句块 (当然除了你一直在使用的主块)。何时你能够使用新块,将会在后面的章节,如​ ​控制流​​中详细介绍。

如何缩进

不要混合使用制表符和空格来缩进,因为这在跨越不同的平台的时候,无法正常工作。我 强烈建议 你在每个缩进层次使用 单个制表符 或 两个或四个空格 。

选择这三种缩进风格之一。更加重要的是,选择一种风格,然后一贯地使用它,即 只 使用这一种风格。

运算符优先级

如果你有一个如​​2 + 3 * 4​​那样的表达式,是先做加法呢,还是先做乘法?我们的中学数学告诉我们应当先做乘法——这意味着乘法运算符的优先级高于加法运算符。

我建议你使用圆括号来分组运算符和操作数,以便能够明确地指出运算的先后顺序,使程序尽可能地易读。例如,​​2 + (3 * 4)​​显然比​​2 + 3 * 4​​清晰。

表达式

例5.1 使用表达式

​#!/usr/bin/python
# Filename: expression.py​


​length = ​​​​5​

​breadth = ​​​​2​

​area = length * breadth​

​print ​​​​'Area is'​​​​, area​

​print ​​​​'Perimeter is'​ ​​​, ​​​​2 ​​​​* (length + breadth)​

输出

​$ python expression.py
Area is 10
Perimeter is 14 ​

它如何工作

注意Python如何打印“漂亮的”输出。尽管我们没有在​​'Area is'​ ​和变量​​area​​之间指定空格,Python自动在那里放了一个空格,这样我们就可以得到一个清晰漂亮的输出,而程序也变得更加易读(因为我们不需要担心输出之间的空格问题)。这是Python如何使程序员的生活变得更加轻松的一个例子。

使用if语句

例6.1 使用if语句

​#!/usr/bin/python
# Filename: if.py ​


​number = ​​​​23​

​guess = ​ ​​​int​​​​(​​​​raw_input​​​​(​​​​'Enter an integer : '​ ​​​))​


​if ​​​​guess == number:​

​    print ​​​​'Congratulations, you guessed it.' ​​​​# New block starts here​

​    print ​​​​"(but you do not win any prizes!)" ​​​​# New block ends here​

​elif ​​​​guess < number:​

​    print ​​​​'No, it is a little higher than that' ​ ​​​# Another block​

​    # You can do whatever you want in a block ...​

​else​​​​:​

​    print ​​​​'No, it is a little lower than that' ​

​    # you must have guess > number to reach here​


​print ​​​​'Done'​

​# This last statement is always executed, after the if statement is executed ​

输出

​$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done
$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done
$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done ​

使用while语句

例6.2 使用while语句

​#!/usr/bin/python
# Filename: while.py​


​number = ​​​​23​

​running = ​​​​True​


​while ​ ​​​running:​

​    guess = ​​​​int​​​​(​​​​raw_input​​​​(​​​​'Enter an integer : '​ ​​​))​


​    if ​​​​guess == number:​

​        print ​​​​'Congratulations, you guessed it.' ​

​        running = ​ ​​​False ​​​​# this causes the while loop to stop​

​    elif ​​​​guess < number:​

​        print ​​​​'No, it is a little higher than that' ​

​    else​​​​:​

​        print ​ ​​​'No, it is a little lower than that' ​

​else​​​​:​

​    print ​​​​'The while loop is over.' ​

​    # Do anything else you want to do here​


​print ​ ​​​'Done'​

输出

​$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done​

使用for语句

例6.3 使用for语句

​#!/usr/bin/python
# Filename: for.py​


​for ​​​​i ​​​​in ​​​​range​​​​(​​​​1​​​​, ​​​​5​​​​):​

​    print ​ ​​​i​

​else​​​​:​

​    print ​​​​'The for loop is over'​

输出

​$ python for.py
1
2
3
4
The for loop is over ​

使用break语句

例6.4 使用break语句

​#!/usr/bin/python
# Filename: break.py​


​while ​​​​True​​​​:​

​    s = ​​​​raw_input​​​​(​​​​'Enter something : '​ ​​​)​

​    if ​​​​s == ​​​​'quit'​​​​:​

​        break​

​    print ​​​​'Length of the string is'​​​​, ​​​​len​​​​(s)​

​print ​​​​'Done'​

使用continue语句

例6.5 使用continue语句

​#!/usr/bin/python
# Filename: continue.py​


​while ​​​​True​​​​:​

​    s = ​​​​raw_input​​​​(​​​​'Enter something : '​ ​​​)​

​    if ​​​​s == ​​​​'quit'​​​​:​

​        break​

​    if ​​​​len​​​​(s) < ​​​​3​​​​:​

​        continue​

​    print ​​​​'Input is of sufficient length'​

​    # Do other kinds of processing here...​

输出

​$ python continue.py
Enter something : a
Enter something : 12
Enter something : abc
Input is of sufficient length
Enter something : quit ​

定义函数

函数是重用的程序段。它们允许你给一块语句一个名称,然后你可以在你的程序的任何地方使用这个名称任意多次地运行这个语句块。这被称为 调用 函数。我们已经使用了许多内建的函数,比如​​len​​和​​range​​。

函数通过​​def​​关键字定义。def关键字后跟一个函数的 标识符 名称,然后跟一对圆括号。圆括号之中可以包括一些变量名,该行以冒号结尾。接下来是一块语句,它们是函数体。下面这个例子将说明这事实上是十分简单的:

例7.1 定义函数

​#!/usr/bin/python
# Filename: function1.py​


​def ​​​​sayHello​​​​():​

​    print ​ ​​​'Hello World!' ​​​​# block belonging to the function​


​sayHello() ​​​​# call the function​

输出

​$ python function1.py
Hello World! ​

使用函数形参

例7.2 使用函数形参

​#!/usr/bin/python
# Filename: func_param.py​


​def ​​​​printMax​​​​(a, b):​

​    if ​ ​​​a > b:​

​        print ​​​​a, ​ ​​​'is maximum'​

​    else​​​​:​

​        print ​ ​​​b, ​​​​'is minimum'​


​printMax(​​​​3​​​​, ​ ​​​4​​​​) ​​​​# directly give literal values​


​x = ​​​​5​

​y = ​​​​7​


​printMax(x, y) ​​​​# give variables as arguments​

(源文件:​​code/func_param.py​​)

输出

​$ python func_param.py
4 is minimum
7 is maximum  ​

使用局部变量

例7.3 使用局部变量

​#!/usr/bin/python
# Filename: func_local.py​


​def ​​​​func​​​​(x):​

​    print ​ ​​​'x is'​​​​, x​

​    x = ​ ​​​2​

​    print ​​​​'Changed local x to'​​​​, x​


​x = ​ ​​​50​

​func(x)​

​print ​​​​'x is still'​​​​, x​

输出

​$ python func_local.py
x is 50
Changed local x to 2
x is still 50​

使用global语句

如果你想要为一个定义在函数外的变量赋值,那么你就得告诉Python这个变量名不是局部的,而是 全局 的。我们使用​ ​global​​语句完成这一功能。没有​​global​​语句,是不可能为定义在函数外的变量赋值的。

例7.4 使用global语句

​#!/usr/bin/python
# Filename: func_global.py​


​def ​​​​func​​​​():​

​    global ​ ​​​x​


​    print ​​​​'x is'​​​​, x​

​    x = ​​​​2​

​    print ​​​​'Changed local x to'​​​​, x​


​x = ​ ​​​50​

​func()​

​print ​​​​'Value of x is'​​​​, x​

输出

​$ python func_global.py
x is 50
Changed global x to 2
Value of x is 2​

默认参数值

对于一些函数,你可能希望它的一些参数是 可选 的,如果用户不想要为这些参数提供值的话,这些参数就使用默认值。这个功能借助于默认参数值完成。你可以在函数定义的形参名后加上赋值运算符(=)和默认值,从而给形参指定默认参数值。

注意,默认参数值应该是一个参数。更加准确的说,默认参数值应该是不可变的——这会在后面的章节中做详细解释。从现在开始,请记住这一点。

使用默认参数值

例7.5 使用默认参数值

​#!/usr/bin/python
# Filename: func_default.py​


​def ​​​​say​​​​(message, times = ​​​​1​​​​):​

​    print ​ ​​​message * times​


​say(​​​​'Hello'​​​​)​

​say(​​​​'World'​​​​, ​​​​5​​​​)​

(源文件:​​code/func_default.py​​)

输出

​$ python func_default.py
Hello
WorldWorldWorldWorldWorld ​

它如何工作

名为​​say​​的函数用来打印一个字符串任意所需的次数。如果我们不提供一个值,那么默认地,字符串将只被打印一遍。我们通过给形参​​times​​指定默认参数值​​1​​来实现这一功能。

在第一次使用​​say​​的时候,我们只提供一个字符串,函数只打印一次字符串。在第二次使用​​say​​的时候,我们提供了字符串和参数​​5​​,表明我们想要 说 这个字符串消息5遍。

重要

只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参。

这是因为赋给形参的值是根据位置而赋值的。例如,​​def func(a, b=5)​ ​是有效的,但是​​def func(a=5, b)​​是 无效 的。