1. 程式人生 > 其它 >python基礎程式設計(1)

python基礎程式設計(1)

一、變數

1、定義變數

#定義變數
name='zhangli'
age=18
salary=1000.1
isBoy=True
print('name','age','salary','isBoy')

#執行結果
name age salary isBoy

2、檢視變數資料型別

#檢視資料型別
print(type(name))
print(type(age))
print(type(salary))
print(type(isBoy))

#執行結果
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

3、檢視變數記憶體地址

#檢視變數記憶體地址
name1='zhangli'
name2='zhangli'
print(id(name1))
print(id(name2))

#執行結果
1525455308400
1525455308400

4、引號功能(python語法)

#單引號等價與雙引號
name1="zhangli"
name2='zhangli'
print(name1)
print(name2)

#執行結果
zhangli
zhangli
#多引號可以多行表示
language='''
c++
python
jave
'''
print(language)

#執行結果
c++
python
jave

二、常用資料轉換

 1、字串轉整型(int)

#字串轉整型(int)
age1='10'
print(type(age1))
age=int(age1)
print(type(age))

#執行結果
<class 'str'>
<class 'int'>

2、字串轉float型別

#字串轉float型別
salary1='1000.1'
print(type(salary1))
salary=float(salary1)
print(type(salary))

#執行結果
<class 'str'>
<class 'float'>

三、輸入與輸出

1、換行與空格(python語法)

\n:換行

\t:空格

2、輸出與輸入

#輸入與輸出
username=input('請輸入你的名字:\n')
age=int(input('請輸入你的年齡:\n'))
salary=float(input('請輸入你的工資:\n'))
isBoy=input('請輸入你的性別:\n')
print(input(username))
print(input(age))
print(input(salary))
print(input(isBoy))
print('%s,%d,%f,%s'%(username,age,salary,isBoy))

#執行結果
請輸入你的名字:
zhangli
請輸入你的年齡:
18
請輸入你的工資:
1000.5
請輸入你的性別:
boy
zhangli
18
1000.5
boy
zhangli,181000.500000,boy

3、字串的格式化輸出

#字串的格式化輸出
username=input('請輸入你的名字:\n')
age=int(input('請輸入你的年齡:\n'))
salary=float(input('請輸入你的工資:\n'))
isBoy=input('請輸入你的性別:\n')
print('my name is %s,and my age is %d,and my salary is %f,and my isBoy is %s'
      %(username,age,salary,isBoy))

#執行結果
請輸入你的名字:
zhangli
請輸入你的年齡:
18
請輸入你的工資:
1000.5
請輸入你的性別:
boy
my name is zhangli,and my age is 18,and my salary is 1000.500000,and my isBoy is boy

四、編碼與解碼

1、編碼

#把str的資料型別轉為bytes的資料型別
str1="張荔"
str_bytes=str1.encode('utf-8')
print(str_bytes)

#執行結果
b'\xe5\xbc\xa0\xe8\x8d\x94'

2、解碼

#把bytes的資料型別轉為str的資料型別
bytes_str=str_bytes.decode('utf-8')
print(bytes_str)

#執行結果
張荔

3、網路爬蟲

#網路爬蟲
import  requests

r=requests.get('https://so.gushiwen.cn/gushi/sanbai.aspx')
print(r.content.decode('utf-8'))


#執行結果部分)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" id="html">
<head><meta http-equiv="Cache-Control" content="no-siteapp" /><meta http-equiv="Cache-Control" content="no-transform " /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>
	古詩三百首_古詩文網
</title>
<script type="text/javascript">
    if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
        window.location.href = "https://m.gushiwen.cn/gushi/sanbai.aspx";
    } else {

    }

五、字串

1、查詢物件有那些方法?

#檢視物件有那些方法
str='hello world'
print(dir(str))

#執行結果
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

2、字母大小寫轉換與判斷

#字母小寫轉大寫
str1='hello'
print(str1.upper())
#判斷字母是否為大寫
print('判斷字母是否為大寫:',str1.upper().isupper())

#執行結果
HELLO
判斷字母是否為大寫: True
#字母大寫轉小寫
str2='HELLO'
print(str2.lower())
#判斷字母是否為小寫
print('判斷字母是否為小寫:',str2.lower().islower())

#執行結果
hello
判斷字母是否為小寫: True

3、判斷字串是以什麼字元開頭或結尾

#判斷字串是以什麼字元開頭
str1='hello'
print('判斷字串以什麼開頭:',str1.startswith('h'))
#判斷字串是以什麼字元結尾
print('判斷字串以什麼結尾:',str1.endswith('h'))

#執行結果
判斷字串以什麼開頭: True
判斷字串以什麼結尾: False

4、查詢指定字元索引

#檢視指定字母的索引
str='hello world'
print(str.find('o'))
print(str.find('i'))


#執行結果
4
-1

5、查詢字元段長度

#查詢字元段長度
str='hello world'
print(len(str))

#執行結果
11

6、檢視物件個數

#檢視字元(物件)個數
str='hello world'
print(str.count('o'))

#執行結果
2

7、查詢字串中指定索引的字元

#查詢字串索引
str='hello world'
print(str.index('w'))

#執行結果
6

#注意
find與index的區別:
find查詢不到,執行結果會顯示“-1”
index查詢不到,執行結果會報錯

8、字串的替換

#字串的替換
str3='acd'
print(str3.replace('c','d'))

#執行結果
add

9、取消字串的空格(開頭與結尾)

#取消字串的空格(開頭與結尾)
str4='hello '
print(str4.strip())

#執行結果
hello

10、字串的迴圈

#字串的迴圈
str='hello world'
for acd in str:
	print(acd)
    
#執行結果
h
e
l
l
o
 
w
o
r
l
d

11、拆分字串

#拆分字串
str='hello world'
print(str.split( ))

#執行結果
['hello', 'world']

12、合併字串

#合併字串
str5=['python','java','c++']
print(' '.join(str5))

#執行結果
python java c++

六、字串格式化方法

username=input('請輸入你的名字:\n')
age=int(input('請輸入你的年齡:\n'))
salary=float(input('請輸入你的薪酬:\n'))
#字串格式化的第一種方式
print('my name is %s,and my age is %d,and my salary is %f'%(
	username,age,salary))

#字串格式化的第二種方式
print('my name is {username},and my age is {age},my salary is {salary}'.format(
	username=username,age=age,salary=salary
))

#字串格式化的第三種方式
print('my name is {0},and my age is {1},my salary is {2}'.format(
	username,age,salary
))

#執行結果
請輸入你的名字:
zhangli
請輸入你的年齡:
18
請輸入你的薪酬:
1000.5
my name is zhangli,and my age is 18,and my salary is 1000.500000
my name is zhangli,and my age is 18,my salary is 1000.5
my name is zhangli,and my age is 18,my salary is 1000.5

七、邏輯判斷

1、邏輯判斷關鍵字

if、elif(esle if)、else

#邏輯判斷if,elif(else if),else
score=int(input('請輸入學生成績:\n'))
if score<60:
	print('差勁')
elif score>=60 and score<80:
	print('成績良好')
elif score>=80 and score<90:
	print('成績優秀')
elif score>=90 and score<100:
	print('成績優秀')
else:
	print('不成立')

2、for迴圈

#字串的迴圈
str='hello world'
for acd in str:
	print(acd)
    
#執行結果
h
e
l
l
o
 
w
o
r
l
d

3、while True:死迴圈

while True:
	score = int(input('請輸入學生成績:\n'))
	if score < 60:
		print('差勁')
	elif score >= 60 and score < 80:
		print('成績良好')
	elif score >= 80 and score < 90:
		print('成績優秀')
	elif score >= 90 and score < 100:
		print('成績優秀')
	elif score==100:
		print('滿分')
	elif score == 150:break
	else:
		break

八、列表

1、檢視列表的方法

增加:append、insert
刪除:pop、remove
兩個列表合併:extend
獲取元素的個數:count
獲取元素的索引:index
反轉:reverse
排序:sort
清除:clear
複製:copy

1)增加

append:把新增的元素預設放在最後一位
insert:按照索引位置新增元素

如果是數字,則:
  列表.sort():從小到大順序排序
  列表.sort(reverse=True)
#建立列表
list1=[1,2,3,4,5]
#新增元素,其預設放在最後一位
list1.append(6)
#新增元素,按照索引位置新增元素
list1.insert(2,9)
print(list1)

2)刪除

pop:刪除最後一位並且返回(在計算機裡,所有的返回必須有輸出才能夠看到)
remove:指定要刪除的元素
#建立列表
list2=[1,2,3,4,5]
#刪除最後一位元素,且返回顯示刪除元素
print(list2.pop())
#刪除指定元素
print(list2.remove(4))
#檢視當前元素
print(list2)

3)檢視

print(列表)
#檢視列表
list3=[1,2,3,4,5]
print(list3[4])

4)修改

列表[索引]=修改後的元素
#根據索引修改元素
list3=[1,2,3,4,5]
list3[1]=777
print(list3)

5)檢視索引

print(列表.index(元素))
#查詢索引
list3=[1,2,3,4,5]
print(list3.index(3))

6)檢視元素個數

print(列表.count(元素))
#檢視元素個數
list3=[1,2,3,4,5]
print(list1.count(4))

7)清空

元素.clear()
#清空元素
list3=[1,2,3,4,5]
list3.clear()
print(list3)

8)合併

列表1.extend(列表2)
#兩列表合併
list4=[1,2,3,4]
list5=['a','b','c','d']
list4.extend(list5)
print(list4)

9)反轉

列表.reverse()
#反轉
list6=[1,2,3,4,5,'a','b']
list6.reverse()
print(list6)

10)排序

sort()
注意:
如果是字母,則按照ascill碼進行排序(內部把字母轉換成數字進行從小到大排序)

元素的排序(倒序):sort(reverse=True)
元素的排序(正序):sort()
#字母排序
list7=['a','z','h']
list7.sort(reverse=True)
print(list7)
#數字排序
list8=[100,27,89,345,67]
list8.sort()
print(list8)
list8.sort(reverse=True)
print(list8)