python之路:进击的小白

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 python
2 #-*-coding:utf-8-*-
3 
4 import getpass
5 password_input=getpass.petpass("密码:")

6.模块

  • os模块
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3  
4 import os
5  
6 os.system("df -h") #调用系统命令
  • sys模块
 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3  
 4 import sys
 5  
 6 print(sys.argv)
 7  
 8  
 9 #输出
10 $ python test.py helo world
11 ['test.py', 'helo', 'world']  #把执行脚本时传递的参数获取到了
  • Tab模块
 1 import sys
 2 import readline
 3 import rlcompleter
 4 
 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 import sys
 4 import readline
 5 import rlcompleter
 6 import atexit
 7 import os
 8 # 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 except IOError:
15     pass
16 atexit.register(readline.write_history_file, histfile)
17 del os, histfile, readline, rlcompleter
18 
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 %s
 6 --------------------
 7 Name:   %s
 8 Age :   %d
 9 Job :   %s
10 -------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 = 0
 5 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 < num:
11             print("猜小了")
12         else:
13             print("猜对了")
14             break
15     else:
16         couter_confirm = input("还想继续吗?")
17         if couter_confirm == 'y':
18             counter = 0
19             continue
20         else:
21             print("bay!")
22             break
23     counter +=1
猜年龄

break跳出本层循环

continue不向下循环从头开始循环

posted @ 2016-05-15 17:05  zhang_kk  阅读(296)  评论(0编辑  收藏  举报