python中fac函式 python系列 基礎

2021-10-19 20:37:32 字數 2610 閱讀 6659

基本資料型別

整型浮點型

字串型

布林型複數型

python3整型只有int,支援二進位制;字串可以用'或",如'hello'或"hello";複數形如3+5j

型別檢查

可以使用type函式對變數型別進行檢查

a = 10

b = 12.3

c = 3 + 5j

d = "hello python"

e = true

print(type(a))

print(type(b))

print(type(c))

print(type(d))

print(type(e))

型別轉換

int(): 轉換整型,可以指定進製

float():轉換浮點型

str(): 轉換字串,可以指定編碼

chr(): 將整數轉換成該編碼對應的字串(乙個字元)

ord(): 將字串(乙個字元)轉換呈對應的編碼(整數)

運算子運算子

描述下標,切片

指數按位與,按位或,按位異或,按位取反,正負號

乘,除,模,整除

加,減右移,左移

小於等於,大於,小於,大於等於

等於,不等於

is is not

身份運算子

in not int

身份運算子

not or and

邏輯運算子

分支結構

if elif和else 進行

海**式

a = float(input('a='))

b = float(input('b='))

c = float(input('c='))

if a + b > c and a + c > b and b + c > a:

print("len: %f" %(a+b+c))

else:

print("不能構成三角形")

迴圈結構

for-in迴圈

對容器進行迭代,優先使用for-in迴圈

sum = 0

for x int range(101) :

sum += x

print(sum)

range函式使用方法:

range(101):0-100整數,取不到101

range(1,101):1-100整數,左閉右開

range(1,101,2):1-100的奇數,其中2是步長

range(100,0,-2):100-1的偶數,其中-2是步長

while迴圈

不知道具體迴圈次數,優先使用while迴圈,用乙個bool值控制while迴圈。可以使用break提前跳出當前迴圈

import random

answer = random.randint(1,100)

counter = 0

while true:

counter += 1

number = int(input('請輸入:'))

if number < answer:

print('大一點')

elif number > answer:

print('小一點')

else:

print('猜對了')

print('猜了%d次' %counter)

if counter > 7:

print('智商餘額明顯不足')

函式和模組

函式將一種特定的功能**封裝到一起,組成乙個函式,只需要在用的時候呼叫這個函式就可以了。定義函式用def關鍵字,用return返回乙個結果

def fac(num):

result = 1

for n in range(1, num+1):

result *= n

return result

n = int(input("n = "))

m = int(input("m = "))

print(fac(m) // fac(n) // fac(m-n))

python函式的特點:

可以有預設值

支援使用可變引數

不支援函式過載

在引數前面加*表示該引數是乙個可變引數

def add(*args):

total = 0

for val in args:

total += val

return total

print(add())

print(add(1))

print(add(1,2,3))

模組python每個檔名就代表了乙個模組,在不同的模組可以有相同名稱的函式,使用import關鍵字可以匯入模組

module1.py

def foo():

print("hello module 1")

module2.py

def foo():

print("hello module 2")

test.py

import module1 as m1

import module2 as m2

m1.foo()

m2.foo()

參考文獻

mac終端輸入python預設開啟python3

1.終端開啟 bash profile檔案 open bash profile 2.新增以下內容到.bash profile檔案 setting path for python 3.5 path library frameworks python.framework versions 3.5 bin...

Python學習入門8 新人怎麼學習Python

人生苦短 我用python 不論學習什麼語言 乙個好的基礎才是你成為高階開發人員的基石。隨著人工智慧和大資料的火熱,python成為了廣大科學家和普通大眾的學習語言。在學習python的過程中,有很多人感到迷茫,不知道自己該從什麼地方入手,今天我們就來說一些新手該如何學習python程式設計。在學習...

python金融分析 用於金融分析的Python包

recommended by activestate.1.numpy 實現各種陣列物件函式和傅利葉變換等等科學計算模組。3.matplotlib 乙個跨平台的數值繪圖包,可繪製高質量的2d,3d影象。4.mysql for python python操作mysql資料庫的介面軟體包。5.pyqt 乙...