Python基礎總結(3)

2021-08-06 01:14:30 字數 1981 閱讀 9813

檔案操作

讀txt文字

f=open("aaa.txt","r")

g=f.read()

print g

f.close()

寫檔案

f=open("tttt.txt","w")

f.write('12646')

f.write('\n')

f.write('5416')

f.close()

csv檔案:

test_data=

f=open("unrate.csv","r")

data=f.read()

rows=data.split('\n')

for row in rows:

split_row=row.split(",")

print test_data

f.close()

定義函式

def

printhello

():print

"hello python"

defprintnum

():for i in range(0,10):

print i

return

defadd

(a,b):

return a+b

print printhello()

print printnum()

print add(12,13)

寫中文在開頭加:

#encoding

:utf-8

原始字串:

在字串開頭加r即可

str=r'c:\now'
如果希望得到乙個跨越多行的字串 如:

aaa,

abcdefg,

***xsat

…… 需要使用三重引號 「」「…」「」

取隨機整數

random.randint(1,10)
邏輯操作符

and or not

elif相當於else if

score=int(input('請輸入乙個分數'))

if100>=score>=90:

print

'a'elif

90>score>=80:

print

'b'elif

80>score>=60:

print

'c'elif

60>score>=0:

print

'd'

x,y=4,5

if xelse:

small=y

#可以改進為

small=x if xelse y

斷言(assert)

生成乙個0~4的列表

list(range(5))

[0,1,2,3,4]

從列表移除元素

remove(『aaa』)

del member[1]

pop()彈出最後乙個元素

pop(1)彈出1號位

list*3變成3組

list.count(123)計數123出現次數

list.index(123)返回123所在位置

list.index(123,3,7)從3號位到7號位

reverse

list.reverse()翻轉列表

list.sort()排序 從小到大

list.sort(reverse=true) 從大到小

拷貝list

list_back=list[:]

Python學習總結3 Python基礎

一 介紹 python採用縮排方式 print absolute value of an integer a 100 if a 0 print a else print a 其中,為注釋。縮減用4個空格表示。其他每一行都是乙個語句,當語句以冒號 結尾時,縮排的語句視為 塊。二 資料型別 2.整數 包...

Python3 基礎知識總結

基礎部分如運算 字串格式化 多行注釋 author xyhu 單行注釋 加減乘 1 1 2 8 1 7 10 2 20 除法自動轉換成浮點數 35 5 7.0 5 3 1.6666666666666667 整數除法的結果都是向下取整 5 3 1 5.0 3.0 1.0 浮點數也可以 5 3 2 5....

Python開發基礎知識總結字典3

d1 dict d2 data1 張三 88 李四 87 王五 90 d2 dict data1 print d2 data2 dict name summer age 23,height 172 print data2 字典的基本用法 字典包含多個 key value 對,而 key 是字典的關鍵...