1.hello world
print("hello world")
2.变量定义的规则
变量名只能是 字母、数字或下划线的任意组合
变量名的第一个字符不能是数字
以下关键字不能声明为变量名
['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']
3.字符编码-*-coding:utf-8-*-
在python2.0版本中,不声明字符编码则不支持中文
python3.0可以不声明默认是 -*-coding:utf-8-*-
4.注释:
单行注释: "#"
多行注释: " ''' "(3个单引号)
5.输入
name_input=input("用户名:")
password_input=input("密码")
密码可以密文(在linux环境中)
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-
3
4 import getpass5 password_input=getpass.petpass("密码:")
6.模块
os模块
1 #!/usr/bin/env python
2 #-*- coding: utf-8 -*-
3
4 importos5
6 os.system("df -h") #调用系统命令
sys模块
1 #!/usr/bin/env python
2 #-*- coding: utf-8 -*-
3
4 importsys5
6 print(sys.argv)7
8
9 #输出
10 $ python test.py helo world11 ['test.py', 'helo', 'world'] #把执行脚本时传递的参数获取到了
Tab模块
1 importsys2 importreadline3 importrlcompleter4
5 if sys.platform == 'darwin' and sys.version_info[0] == 2:6 readline.parse_and_bind("bind ^I rl_complete")7 else:8 readline.parse_and_bind("tab: complete") #linux and python3 on mac
9
10 for mac
mac版本
1 #!/usr/bin/env python
2 #python startup file
3 importsys4 importreadline5 importrlcompleter6 importatexit7 importos8 #tab completion
9 readline.parse_and_bind('tab: complete')10 #history file
11 histfile = os.path.join(os.environ['HOME'], '.pythonhistory')12 try:13 readline.read_history_file(histfile)14 exceptIOError:15 pass
16 atexit.register(readline.write_history_file, histfile)17 delos, histfile, readline, rlcompleter18
19 for Linux
linux版本
可以从网上找
7.格式化输出
1 name_input = input('name:')2 age_input = int(input('age:'))3 job_input = input('job:')4 msg = '''
5 Infomation of user %s6 --------------------7 Name: %s8 Age : %d9 Job : %s10 -------END----------11 '''%(name_input,name_input,age_input,job_input)12 print(msg)13 print("姓名:",name_input)14 print("年龄:",age_input)15 print("职业:",job_input)
%s字符串
%d数字
8.for循环
1 #!/usr/bin/env python
2 #-*-coding:utf-8-*-
3 num = 20
4 counter =05 for i in range(10):6 if counter<3:7 guess_num = int(input("输入年龄:"))8 if guess_num >num:9 print("猜大了")10 elif guess_num <11 print else:13 break>
15 else:16 couter_confirm = input("还想继续吗?")17 if couter_confirm == 'y':18 counter =019 continue
20 else:21 print("bay!")22 break
23 counter +=1
猜年龄
break跳出本层循环
continue不向下循环从头开始循环
11>