简明 Python 教程
运算符通常由左向右结合,即具有相同优先级的运算符按照从左向右的顺序计算。例如,2 + 3 + 4
被计算成(2 + 3) + 4
。一些如赋值运算符那样的运算符是由右向左结合的,即a = b = c
被处理为a = (b = c)
。
另外,注意Python如何打印“漂亮的”输出。尽管我们没有在'Area is'
和变量area
之间指定空格,Python自动在那里放了一个空格,这样我们就可以得到一个清晰漂亮的输出,而程序也变得更加易读(因为我们不需要担心输出之间的空格问题)。这是Python如何使程序员的生活变得更加轻松的一个例子。
我们为内建的raw_input
函数提供一个字符串,我们通过int
把这个字符串转换为整数
guess =
int
(
raw_input
(
'Enter an integer : '
))
if语句的例子,注意缩进:
#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
raw_input("press enter key to close..");
注:
给C/C++程序员的注释
在Python中没有
switch
语句。你可以使用
if..elif..else
语句来完成同样的工作(在某些场合,使用
字典会更加快捷。)
while循环语句有一个可选的
else
从句:
# 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'
给C/C++程序员的注释
记住,你可以在
while
循环中使用一个
else
从句。
for..in
是另外一个循环语句:
# Filename: for.py
for i in range(1, 5):
print i
else:
print 'The for loop is over'
我们所做的只是提供两个数,
range
返回一个序列的数。这个序列从第一个数开始到第二个数为止。例如,
range(1,5)
给出序列
[1, 2, 3, 4]
。默认地,
range
的步长为1。如果我们为
range
提供第三个数,那么它将成为步长。例如,
range(1,5,2)
给出
[1,3]
。记住,range
向上 延伸到第二个数,即它
不包含第二个数。
给C/C++/Java/C#程序员的注释
Python的for
循环从根本上不同于C/C++的for
循环。C#程序员会注意到Python的for
循环与C#中的foreach
循环十分类似。Java程序员会注意到它与Java 1.5中的for (int i : IntArray)
相似。
在C/C++中,如果你想要写for (int i = 0; i < 5; i++)
,那么用Python,你写成for i in range(0,5)
。你会注意到,Python的for
循环更加简单、明白、不易出错。
break
语句是用来 终止 循环语句的,即哪怕循环条件没有称为False
或序列还没有被完全递归,也停止执行循环语句。
一个重要的注释是,如果你从for
或while
循环中 终止 ,任何对应的循环else
块将不执行。
例:
# 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
语句被用来告诉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...
注意,
continue
语句对于
for
循环也有效。