在linux 下创建一个文件叫hello.py,并输入
| 
 1 
 | 
 print("Hello World!") 
 | 
然后执行命令:python hello.py ,输出
| 
 1 
2 
3 
 | 
 localhost:~ jieli$ vim hello.py 
localhost:~ jieli$ python hello.py 
Hello World! 
 | 
指定解释器
上一步中执行 python hello.py 时,明确的指出 hello.py 脚本由 python 解释器来执行。
如果想要类似于执行shell脚本一样执行python脚本,例: ./hello.py ,那么就需要在 hello.py 文件的头部指定解释器,如下:
| 
 1 
2 
3 
 | 
 #!/usr/bin/env python 
print "hello,world" 
 | 
如此一来,执行: ./hello.py 即可。
ps:执行前需给予 hello.py 执行权限,chmod 755 hello.py
声明变量
| 
 1 
2 
3 
 | 
 #_*_coding:utf-8_*_ (声明字体为utf-8) 
name = "Alex Li" 
 | 
上述代码声明了一个变量,变量名为: name,变量name的值为:"Alex Li" 
变量定义的规则:
- 变量名只能是 字母、数字或下划线的任意组合
 - 变量名的第一个字符不能是数字
 - 以下关键字不能声明为变量名
 
[‘and‘, ‘as‘, ‘assert‘, ‘break‘, ‘class‘, ‘continue‘, ‘def‘, ‘del‘, ‘elif‘, ‘else‘, ‘except‘, ‘exec‘, ‘finally‘, ‘for‘, ‘from‘, ‘global‘, ‘if‘, ‘import‘, ‘in‘, ‘is‘, ‘lambda‘, ‘not‘, ‘or‘, ‘pass‘, ‘print‘, ‘raise‘, ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘]
变量的赋值
| 
 1 
2 
3 
4 
5 
6 
7 
8 
 | 
 name = "Alex Li" 
name2 = name 
print(name,name2) 
name = "Jack" 
print(name,name2) 
 | 
如上执行结果是 Alex Li Alex Li / Jack Alex Li 注释 单行注释用#,多行注释用"""注释内容"""
应该显示的告诉python解释器,用什么编码来执行源代码,即:
| 
 1 
2 
3 
4 
 | 
 #!/usr/bin/env python(使用python解释器) 
# -*- coding: utf-8 -*-(使用utf-8编码来处理这个程序,否则打不出来汉字) 
print "你好,世界" 
 | 
input,提供输入入口,
以下会提示,what is your name ,如填下xuweiwie,最终打印 hello xuweiwei
name = input("What is your name?")
print("Hello " + name )
编译型&解释型
编译型语言在程序执行之前,先会通过编译器对程序执行一个编译的过程,把程序转变成机器语言。运行时就不需要翻译,而直接执行就可以了。最典型的例子就是C语言。
解释型语言就没有这个编译的过程,而是在程序运行的时候,通过解释器对程序逐行作出解释,然后直接运行,最典型的例子是Ruby
python是先编译后解释
字符串格式化输出
| 
 1 
2 
3 
4 
 | 
 name = "alex" 
print ("i am %s " % name) 
#输出: i am alex 
 | 
| 
 1 
2 
3 
4 
 | 
 name = 234 
print ("i am %d " % name) 
#输出: i am 234 
 | 
PS: 字符串是 %s;整数 %d;浮点数%f
python3比python2多了一个默认的中文字符编码