第1章 python基础

1.python语言类型

cpython

1 Python的官方版本,使用C语言实现,使用最为广泛,CPython实现会将源文件(py文件)转换成字节码文件(pyc文件),然后运行在Python虚拟机上
View Code

Jpython

1  Python的Java实现,Jython会将Python代码动态编译成Java字节码,然后在JVM上运行。
View Code

Ironpython

1 Python的C#实现,IronPython将Python代码编译成C#字节码,然后在CLR上运行。(与Jython类似)
View Code

pypy(特殊)

1 Python实现的Python,将Python的字节码字节码再编译成机器码。
View Code

rubypython

1 用ruby语言编写的python
View Code

2.变量

2.1变量的定义规则:

     1.变量名只能是字母,数字或下划线的任意组合。

     2.变量名第一个字符不能是数字

     3.以下关键字不能声明为变量:【and,as,assert,break,class,continue,def,elif,else,except,exec,finally,for,global,if,import,in,is,lambda,not,or,pass,print,raise,return,try,while,whit,yield】

 2.2. 变量的定义方式:

  驼峰式

1 UserName='f'anglingen
View Code

下划线式,官方推荐:

1 uesr_name='fanglingen'
View Code

2.3. 定义变量不好的例子:

     1.变量名字不要用中文和拼音

     2. 名字不要太长

     3.不要词不答意

3.程序交互

1 username=input('请输入用户名:')
2 password=int(input('请输入密码:'))
View Code

4.数据类型

4.1  数字

       int(整型)

       在32位的机器上,整数位为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647.

        在64位的机器上,整数位为64位,取值范围为-2**63-2**63-1,即-9223372036854775808-9223372036854775807

 4.2  字符串

        python中加了''号 的都被当成字符串

1 >>> a='fangliengen'
2 >>> print (type(a))
3 <class 'str'>
View Code

       字符串拼接,字符串可以相加,可以相乘

 1 >>> print (type(a))
 2 <class 'str'>
 3 >>> a='fangliengen'
 4 >>> print (type(a))
 5 <class 'str'>
 6 >>> b='123'
 7 >>> print (a+b)
 8 fangliengen123
 9 >>> a*10
10 'fangliengenfangliengenfangliengenfangliengenfangliengenfangliengenfangliengenfangliengenfangliengenfangliengen'
View Code

 4.3. 布尔值

1 >>> a=1
2 >>> b=2
3 >>> a > b
4 False
5 >>> a < b
6 True
View Code

4.4. 列表类型

1 >>> a=['1','2','3','4','5']
2 >>> print a[0]
3 1
4 >>> print a[2]
5 3
View Code

4.5 字典类型

1 >>> user_info={'fang': '123','alex': '1234'}
2 >>> print user_info['fang']
3 123
View Code

 5.格式化输出

例如:问用户的名字,年龄,工作,爱好等。

 1 输出格式:
 2 -------info of fanglingen---------
 3          name:  fanglingen
 4          age:   28
 5          job:   IT
 6       hobbie:   read
 7 ----------end-------------
 8 
 9 代码如下:
10 name=input('请输入你的名字:')
11 age=input('请输入你的年龄:')
12 job=input('请输入你的的工作:')
13 hobbie=input('请输入你的爱好:')
14 info = '''
15 -------info of %s---------
16          name:  %s
17          age:   %s
18          job:   %s
19       hobbie:   %s
20 ----------end-------------
21 '''%(name,name,age,job,hobbie)
22 print(info)
View Code

 6.基本运算

 6.1算术运算

 

 6.2 比较运算

6.3 赋值运算

6.4逻辑运算

6.5 成员运算

6.6 身份运算

6.7运算符优先级,自上而下,优先级从高到低

7.流程控制之 if.....else语句 

         注意(同级判断,它条件从上到下,只要第一个条件符合,就执行,下面的就不判断了)。

7.1 单分支:

      if  条件 :

          满足条件执行.....

1 i=0
2 while i < 3:
3     username=input('请输入用户名:')
4     password=int(input('请输入密码:'))
5     if username == 'seven' and password == 123:
6         print('登录成功!')
7     else:
8         print('登录失败!')
View Code

7.2  多分支:

      if  条件 :

          满足条件执行.....

     elif 条件:

          满足条件执行:

      else:

          满足条件执行....

 1 tag=0
 2 while tag < 4:
 3     age=28
 4     if tag == 3:
 5         mun=input('您好要继续猜吗?如果继续请选择Y/y,如果退出选择N/n')
 6         if mun == 'Y' or mun == 'y':
 7               tag = 0
 8         elif mun == 'N' or mun == 'n':
 9               break
10     guess=int(input('请您猜猜我的年龄有多大:'))
11     if guess == age:
12         print('恭喜您,猜对了!')
13         break
14     elif guess > age:
15         print('您猜的大了,望小一点猜!')
16         tag+=1
17     else:
18         print('您猜的小了,望大一点猜!')
19         tag+=1
View Code

 8.流程控制之循环

 8.1 while 条件循环

       while  条件:

            条件成立执行.........

      例如:猜年龄游戏

                1.允许用户最多尝试三次。

                 2.每尝试3次后用户还没有猜对,询问用户还要不要玩下去,如果回答Y/y,继续3次,依次往复,如果回答N/n,退出程序

                 3.如果用户猜对,就退出程序。

 1 tag=0
 2 while tag < 4:
 3     age=28
 4     if tag == 3:
 5         mun=input('您好要继续猜吗?如果继续请选择Y/y,如果退出选择N/n')
 6         if mun == 'Y' or mun == 'y':
 7               tag = 0
 8         elif mun == 'N' or mun == 'n':
 9               break
10     guess=int(input('请您猜猜我的年龄有多大:'))
11     if guess == age:
12         print('恭喜您,猜对了!')
13         break
14     elif guess > age:
15         print('您猜的大了,望小一点猜!')
16         tag+=1
17     else:
18         print('您猜的小了,望大一点猜!')
19         tag+=1
View Code

 break:跳出本层循环

continue:跳出本次循环,继续下次循环

9. 练习:

 1 user_info={'fang': '123','alex': '1234'}
 2 tag=True
 3 while tag:
 4    username=input('请输入用户名')
 5    if username in user_info.keys():
 6         i=0
 7         while i < 3:
 8             password = input('请输入密码')
 9             if  password == user_info[username]:
10                 print('登录成功!')
11                 tag=False
12                 break
13             else:
14                   if i == 2:
15                       print('登录失败,重试超过3次!')
16                       tag=False
17                       break
18                   else:
19                       print('登录失败,密码错误,请重试!')
20                       i+=1
21    else:
22        print('用户名不存在!')
23        break
View Code

 1 user文件内容:
 2 test1|test1123|0
 3 test2|test2123|0
 4 test3|test3123|0
 5 test4|test4123|0
 6 test5|test5123|0
 7 test6|test6123|0
 8 
 9 
10 f1=open('user','r')
11 data =f1.read()
12 f1.close()
13 user_str_info = data.split('\n')
14 user_info={}
15 for item in user_str_info:
16     if item != '':
17         key = item.split('|')
18         user_info[key[0]]={'pwd':key[1],'times':key[2]}
19 
20 tag=True
21 while tag:
22         username=input('请输入用户名:')
23         if  username in user_info.keys():
24              conut=0
25              while conut < 3:
26                  password=input('请输入密码:')
27                  if password == user_info[username]['pwd']:
28                      mun=int(user_info[username]['times'])
29                      if mun == 3:
30                          print('用户已经被锁定!')
31                          tag=False
32                          break
33                      elif mun < 3:
34                          print('用户登录成功!')
35                          mun=0
36                          user_info[username]['times']=mun
37                          f2 = open('user', 'w')
38                          for key in user_info.keys():
39                              print(key, user_info[key]['pwd'], user_info[key]['times'], sep='|', end='\n', file=f2)
40                          f2.close()
41                          tag=False
42                          break
43                  else:
44                        if conut==2:
45                            print('密码输入错误3次,用户被锁定!')
46                            mun = int(user_info[username]['times'])
47                            mun += 1
48                            user_info[username]['times'] = mun
49                            f2 = open('user', 'w')
50                            for key in user_info.keys():
51                                print(key, user_info[key]['pwd'], user_info[key]['times'], sep='|', end='\n', file=f2)
52                            f2.close()
53                            tag = False
54                            break
55                        else:
56                             print('密码输入错误!')
57                             mun = int(user_info[username]['times'])
58                             mun += 1
59                             user_info[username]['times'] = mun
60                             f2 = open('user', 'w')
61                             for key in user_info.keys():
62                                 print(key, user_info[key]['pwd'], user_info[key]['times'], sep='|', end='\n', file=f2)
63                             f2.close()
64                             conut+=1
65         else:
66              print('用户不存在!')
67              break
View Code
 1 # 当然此表你在文件存储时可以这样表示
 2 # 1 1,Alex Li,22,13651054608,IT,2013-04-01
 3 # 现需要对这个员工信息文件,实现增删改查操作
 4 #     可进行模糊查询,语法至少支持下面3种:
 5 #           select name,age from staff_table where age > 22
 6 #           select  * from staff_table where dept = "IT"
 7 #               select  * from staff_table where enroll_date like "2013"
 8 #         查到的信息,打印后,最后面还要显示查到的条数
 9 #     可创建新员工纪录,以phone做唯一键,staff_id需自增
10 #     可删除指定员工信息纪录,输入员工id,即可删除
11 #     可修改员工信息,语法如下:
12 #           UPDATE staff_table SET dept="Market" WHERE where dept = "IT"
13 #  注意:以上需求,要充分使用函数,请尽你的最大限度来减少重复代码!
14 
15 
16 def fetch(**kwargs):
17     #查询语法一:select name,age from staff_table where age > 22
18     #查询语法二:select * from staff_table where dept = IT
19     pass
20 
21 
22 def insert(data):
23     #insert into staff_table values(staff_id,name,age,phone,dept,enroll-date);
24     l=data.split(' ')[-1]
25 
26     # user_info()[len(user_info())]={'name':name,'age':age,'phone':phone,'dept':dept,'enroll-date':date}
27     pass
28 
29 def update(ID):
30     pass
31 
32 def delete(*args,id=0):
33     print(args)
34     user_info().pop(id)
35     print(user_info())
36 # tag=True
37 # while tag:
38 def user_info():
39     with open('test','r') as read_f:
40         user_str_info=read_f.read().split('\n')
41         staff_table={}
42         for item in user_str_info:
43             key=item.split(',')
44             staff_table[key[0]]={'name':key[1],'age':key[2],'phone':key[3],'dept':key[4],'enroll_date':key[5]}
45         return staff_table
46 print(user_info())
47 # while True:
48 #        count=input(">>>>>>>>>>>").strip()
49 #        count=count.split()
50 #        print(count)
51 #        if count[0] == 'delete':
52 #            pass
53 #        elif count[0] == 'select':
54 #            select()
55 #        elif count[0] == 'insert':
56 #            pass
57 
58 if __name__ == "__main__":
59     msg = """
60     1:查询
61     2:添加
62     3:删除
63     4:修改
64     5:退出
65     """
66     msg_dict = {
67         "1": fetch,
68         "2": insert,
69         # "3": delete,
70         # "4": update,
71         "5": exit,
72     }
73     while True:
74         print(msg)
75         choice = input("输入序号>>:")
76         if len(choice) == 0 or choice not in msg_dict: continue
77         if choice == '5': break
78         data = input("请输入数据>>:").strip()
79         msg_dict[choice](data)
View Code

      

        

             

原文地址:https://www.cnblogs.com/fanglingen/p/7131469.html