7.指定python编译器与使用注释
一个简单的程序:
#!/usr/bin/python
# Filename: expression.py
length = 5
breadth = 2
area = length * breadth
print 'Area is', area
print 'Perimeter is', 2 * (length + breadth)
这里第一句用#!指定了python编译器的路径,这个很重要。因为python3的语法与python2差异非常大,很多模块也不一样,所以需要指定编译器。这里是Python2的编译器,若是python3的,需要改为:#!…/python3
第二句的#表示单行注释,若多行注释,需要使用三引号(”’)括起来。
在命令行输入 python expression.py ,即可运行程序,得到输出:
Area is 10
Perimeter is 14
8.条件语句
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
上面的例子中,if后面有一个空格,之后是判断语句,之后跟一个冒号。执行语句另起一行,在if条件语句一个缩进之后。表示若满足if语句,则执行。上面的elif表示”else if”的意思,可以有也可以没有。后面的else同理。elif和else都要和if在同一个缩进。
运行的结果:
$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done
$ python if.py
Enter