Python随笔(一)、python基础

2023-01-31 04:01:13 python 基础 随笔

PyCharm下设置自己的模板:

在File---settings---File and Code Templates---python script 脚本里添加:

#!/usr/bin/env Python 

#-*- coding:utf-8 _*-  

""" 

@author:${USER} 

@file: ${NAME}.py 

@time: ${YEAR}/${MONTH}/${DAY} 

"""  

一、第一个python程序:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: HelloWorld.py
@time: 2017/11/{DAY}
"""
print("HelloWorld!!!")
print("你好,世界")

二、变量和赋值:
#!usr/bin/env python
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: bianliang.py
@time: 2017/11/18
"""
#赋值
name = "chenjisong"
age = 30
print(name,age)

字符串类型的必须要加引号

a = 3
b = a
a = 5
print(a,b)

返回结果为(5,3)

解析:a = 3,内存地址指向3,b = a,则b = 3,此时a 和 b 都指向内存地址3,当 a = 5的时候,a 的内存地址指向了5,则a = 3 这个内存地址被回收了,但是b的内存地址未被回收,b仍然等于3,所以最后返回的结果是(5,3)

变量起名的原则:

      1、显示,通俗易懂

      2、驼峰写法(首字母大写)          例如:NumsOfJackGf

      3、下横线写法(不能为中横线)   例如:nums_of_jack_gf

      4、不能数字开头,但是可以在中间和结尾

      5、命名中不能有特殊字符

      6、变量的命名不能有空格

     7、关键字不能声明为变量

 内存地址的验证:

C:\Users\Administrator>python

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]

 on win32

Type "help", "copyright", "credits" or "license" for more infORMation.

>>> import keyWord

>>> a = 5

>>> b = a

>>> id(a),id(b)

(1363763552, 1363763552)

a 和 b的内存地址完全一样

>>> a = 10

>>> id(a),id(b)

>>> (1363763712, 1363763552)

当a的值改变之后,a的内存地址也发生了变化(是python中的内存地址,不是物理机器的内存地址)


三、用户交互


[root@python3 ~]# python
Python 3.6.3 (default, Nov 12 2017, 04:07:16)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> name = input("please input your name:")
please input your name:chenjisong

>>> print(name)

chenjisong

>>> a = 5
>>> eval('a')
5

四、条件判断与缩进

IF....ELSE和缩进


伪代码:

如果   你是富二代

          我们俩就拍拖

或者   你很努力上进

          我们可以接触试试

否则

          免谈


缩进要一致:
sex = input ("plsase input your gender:")
if sex == "gril":
   print("I would like to have a baby")
elif sex == "man":
   print("Going to homesexual!")
else:
   print("Pervert!!!")

游戏:猜幸运数字:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: lucky_number.py
@time: 2017/11/18
"""
lucky_number = 18
guess_number = int(input("can you guess my lucky_number:"))
if guess_number > lucky_number:
   print("guess_number is bigger then lucky_number")
elif guess_number < lucky_number:
   print("guess_number is smaller then lucky_number:")
else:
   print("congratulations,you guess it,but no prize")


五、循环控制:

break结束循环:(猜对即跳出循环,没猜对就一直猜)

while True:   
   lucky_number = 18
   guess_number = int(input("can you guess my lucky_number:"))
   if guess_number > lucky_number:
       print("guess_number is bigger then lucky_number")
   elif guess_number < lucky_number:
       print("guess_number is smaller then lucky_number:")
   else:
       print("congratulations,you guess it,but no prize")
       break
while lucky_number != input_num:
   input_num = int(input("input the guess num:"))
   if input_num > lucky_number:
       print("the real number is smaller")
   elif input_num < lucky_number:
       print("the real number is bigger")
   else:
print("bingo")


六、循环次数限制:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: lucky_number.py
@time: 2017/11/18
"""
lucky_number = 18
input_num=-1
guess_count = 0
#while lucky_number != input_num:
while guess_count < 3:
   input_num = int(input("input the guess num:"))
   print("guess count:",guess_count)
   if input_num > lucky_number:
       print("the real number is smaller")
   elif input_num < lucky_number:
       print("the real number is bigger")
   else:
       print("Bingo!")
       break
   guess_count += 1
else:
   print("try too many times")

两重判断:

第一重:三次猜不对直接退出(guess_count>3),打印“try too many times”

第二重:猜对了直接打印bingo,退出

for循环猜数字游戏:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: lucky_number.py
@time: 2017/11/18
"""
#while True:
lucky_number = 18
input_num=-1

for i in range(5):
   input_num = int(input("input the guess num:"))
   if input_num > lucky_number:
       print("the real number is smaller")
   elif input_num < lucky_number:
       print("the real number is bigger")
   else:
       print("Bingo!")
       break
else:
   print("try too many times")


七、常用数据类型

数据类型:

数字:

     int(整型)

     float(浮点型)

     long(长整型)

布尔:(True(1) 和  False(0))  真和假

字符串    str

列表        list

元祖       tuple

字典       dict

type可以查看数据类型:

>>> type(2**10)

<class 'int'>

>>> type(2.99)

<class 'float'>



八、字符串格式化

第一种写法会开辟很多内存空间,对内存资源是一种浪费,所以不建议

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: string_format.py
@time: 2017/11/18
"""
name = input("name:")
age = input("age:")
job = input("job:")

print("Information of "+ name +"\nName:" + name +"\nAge:"+ age +"\nJob:"+ job +"")

第二种写法只开辟了一块内存空间,可以有效节省内存资源,效率更优

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: string_format.py
@time: 2017/11/18
"""
name = input("name:")
age = input("age:")
job = input("job:")

print("Information of %s:\nName:%s\nAge:%s\nJob:%s" %(name,name,age,job))

%s要与后面的值一一对应,否则会报错

第三种写法:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: string_format.py
@time: 2017/11/18
"""
name = input("name:")
age = input("age:")
job = input("job:")
msg = '''
Information of %s:
    Name:%s
    Age :%s
    Job :%s
'''   %(name,name,age,job)
print(msg)

'''   

    '''的妙用


九、列表常用操作:

strip:去掉,拿掉空格:以下例子去掉了前面的空格,但是中间的没法去掉

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: string_format.py
@time: 2017/11/18
"""
name = input("name:").strip()
age = input("age:").strip()
job = input("job:").strip()
msg = '''
Information of %s:
    Name:%s
    Age :%s
    Job :%s
'''   %(name,name,age,job)
print(msg)

输入

name:          chen    jisong

age:     22

job:                 IT

输出:

Information of chen    jisong:

     Name:chen    jisong

     Age :22

     Job :IT

也可以去掉字符:如下

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: string_format.py
@time: 2017/11/18
"""
name = input("name:").strip("chen")
age = input("age:").strip()
job = input("job:").strip()
msg = '''
Information of %s:
    Name:%s
    Age :%s
    Job :%s
'''   %(name,name,age,job)
print(msg)

输入

name:           chen    jisong

age:     22

job:                 IT

输出:

Information of jisong:

     Name:jisong

     Age :30

     Job :IT


列表索引(下标)取值:   []

[root@python3 ~]# python

Python 3.6.3 (default, Nov 12 2017, 04:07:16) 

[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> name_list = ["65brother","87brother","99brother"]

>>> name_list

['65brother', '87brother', '99brother']

>>> name_list[0]

'65brother'

>>> name_list[1]

'87brother'

>>> name_list[2]

'99brother'

>>> dir(name_list)

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

index        索引:

count       计数:

append    追加:

insert       插入:

pop          删除最后一个索引值

remove    删除固定的值

reverse     反转

sort           排序

extend      列表的扩展

>>> name_list

['65brother', '87brother', '99brother']

>>> name_list.append("Eric")

>>> name_list

['65brother', '87brother', '99brother', 'Eric']

>>> name_list.append("87brother")

>>> name_list

['65brother', '87brother', '99brother', 'Eric', '87brother']

>>> name_list.index("87brother")

1

>>> name_list.count("87brother")

2

>>> name_list.insert(2,"66brother")      在索引2之后加66brother

>>> name_list

['65brother', '87brother', '66brother', '99brother', 'Eric', '87brother']

>>> name_list.remove("66brother")

>>> name_list

['65brother', '87brother', '99brother', 'Eric', '87brother']

>>> name_list.pop()                               

'87brother'

>>> name_list

['65brother', '87brother', '99brother', 'Eric']

>>> name_list.reverse()

>>> name_list

['Eric', '99brother', '87brother', '65brother']

>>> name_list.sort()

>>> name_list

['65brother', '87brother', '99brother', 'Eric']

>>> name_list.append("87brother")

>>> name_list.append("87brother")

>>> name_list

['65brother', '87brother', '99brother', 'Eric', '87brother', '87brother']

要一次删除3个87brother,应当怎么做???

>>> for i in range(name_list.count('87brother')):

...    name_list.remove("87brother")

... 

>>> name_list

['65brother', '99brother', 'Eric']


十、列表的后续操作

[root@python3 ~]# python

Python 3.6.3 (default, Nov 12 2017, 04:07:16) 

[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> a = [1, 2, 4, 3, 'a', 'b']

>>> a

[1, 2, 4, 3, 'a', 'b']

>>> a.insert(1,8)     ---在索引一处插入数字

>>> a

[1, 8, 2, 4, 3, 'a', 'b']

正向切片:

>>> a[3:5]

[4, 3]

>>> a[0:7]

[1, 8, 2, 4, 3, 'a', 'b']

反向切片:

>>> a[-4:]

[4, 3, 'a', 'b']

>>> a[-4:-1]

[4, 3, 'a']

>>> a[0:7]

[1, 8, 2, 4, 3, 'a', 'b']

>>> a.sort()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: '<' not supported between instances of 'str' and 'int'  字符串和整型不能进行排序

>>> a[0:7]

[1, 2, 3, 4, 8, 'a', 'b']

>>> a.pop()

'b'

>>> a.pop()

'a'

>>> a.sort()

>>> a

[1, 2, 3, 4, 8]

拿掉字符串后即可进行排序

列表可以相加:

>>> a = [1,2,3,4,5,6,7,8,9]

>>> b = ["a","b","c","d","e","f","g","h","i"]

>>> a + b

[1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

>>> a.extend(b)

>>> a

[1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']


十一、二进制位运算

元祖:

>>> t = (1,2,3,4)

>>> dir(t)

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

元祖改列表,用list方法:

>>> type(t)

<class 'tuple'>

>>> list(t)

[1, 2, 3, 4]

>>> type(t)

<class 'tuple'>

>>> a = list(t)

>>> type(a)

<class 'list'>


二进制运算:

>>> A = 10

>>> B = 50

>>> A & B              两者都真才为真

2

>>> A | B                两者有一真就为真

58

>>> A ^ B              一真一假则为真

56

>>> A >> 1            整体往右移一位

5

>>> A << 1            整体往左移一位

20

>>> B >> 1

25

>>> B << 1

100


逻辑运算符:与(and)  或(or)  非(not)

>>> sex = "man"

>>> age = 26

>>> if sex == "man" and age > 25:

...    print("time to get married")

... 

time to get married


>>> sex = "man"

>>> age = 26

>>> if sex == "man" or age < 23:

...     print("do not worried")

... 

do not worried


>>> name_list=["oldboy","alex","eric"]

>>> if "jack" not in name_list:

...      print("sorry")

... 

sorry


身份运算符(is    is not)

>>> name_list=["oldboy","alex","eric"]

>>> type(name_list) is tuple

False

>>> type(name_list) is list

True

>>> type(name_list) is not list

False

>>> type(name_list) is not tuple

True


十二、简单的嵌套循环

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


#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: cotinue.py
@time: 2017/11/19
"""  
for i in range(10):
   if i < 5:
       continue
   print(i)

执行结果如下:

E:\Python36\python.exe C:/Users/Administrator/PycharmProjects/S12/2017-11-18/cotinue.py

5

6

7

8

9


#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: cotinue.py
@time: 2017/11/19
"""
for j in range(5):
   for i in range(10):
       if i < 5:
           continue
       if j> 3:
           break
       print(i)

执行结果:

5

6

7

8

9

5

6

7

8

9

5

6

7

8

9

5

6

7

8

9


十三、文件的基本操作

读取文件的内容:

一次性加载所有内容到内存

obj.read()

一次性加载所有内容到内存,并根据行分割成字符串

obj.readlines()

每次仅读取一行数据:

for line in obj:

     print line

写入文件内容:

obj.write(“内容”)

关闭文件句柄:

obj.close()


打开文件:

file_obj = file("文件路径","模式")

file_obj = open("文件路径","模式")

打开文件的模式有:

r          以只读方式打开文件。

w         打开一个文件只用于写入。

a          打开一个文件用于追加。

w+       打开一个文件用于读写。

写文件的操作:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: file_opr.py
@time: 2017/11/19
"""
f = open("test.log","w")
f.write("this is the first line\n")
f.write("this is the second line\n")
f.write("this is the third line\n")
f.write("this is the fourth line\n")
f.close()

test.log下面的文字:

this is the first line
this is the second line
this is the third line
this is the fourth line


读文件的操作,循环逐行读取:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: file_opr.py
@time: 2017/11/19
"""
f = open("test.log","r")
#f.write("this is the first line\n")
#f.write("this is the second line\n")
#f.write("this is the third line\n")
#f.write("this is the fourth line\n")
for line in f:
   print (line),
f.close()

执行结果:

this is the first line

this is the second line

this is the third line

this is the fourth line

判断:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: file_opr.py
@time: 2017/11/19
"""
f = open("test.log","r")
#f.write("this is the first line\n")
#f.write("this is the second line\n")
#f.write("this is the third line\n")
#f.write("this is the fourth line\n")
for line in f:
  if "third" in line:
      print ("this is 3 line")
  else:
      print(line)
f.close()

追加文件操作:

#!usr/bin/env python 
#-*- coding:utf-8 _*-  
"""
@author:Administrator
@file: file_opr.py
@time: 2017/11/19
"""
f = open("test.log","a")
#f.write("this is the first line\n")
#f.write("this is the second line\n")
#f.write("this is the third line\n")
#f.write("this is the fourth line\n")
#for line in f:
#   if "third" in line:
#       print ("this is 3 line")
#   else:
#       print(line)
f.write("8\n")
f.write("9\n")
f.write("5\n")
f.write("6\n")
f.write("7\n")
f.close()

test.log输出结果:

this is the first line
this is the second line
this is the third line
this is the fourth line
8
9
5
6
7


相关文章