Python隨筆(一)、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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章