Python 2 基礎中的基礎知識

2021-09-19 07:53:46 字數 2123 閱讀 4982

我選擇最新版python直譯器版本

從最簡單的hello world 開始

>>> print("hello world!")

hello world!

>>>

就像最簡單的計算器

不用多說,一看就懂

>>> 2+6

8>>> 2/6

0.3333333333333333

>>> 2//6

0>>> 5*9

45>>> 5.0/6

0.8333333333333334

>>> 2.0//6

0.0>>> 6//2

3>>> 6.0//2

3.0>>> 6.0/2.4

2.5>>> 6.0 # 整數除法,丟棄小數部分

2.0>>> 6%3

0>>> 3%6 # 取餘運算

3>>>

變數

>>> x = 9

>>> x*x

81>>>

語句

>>> print(5*5)

25

獲取使用者輸入

>>> input("how old are you: ")                 

how old are you: 250

'250'

>>>

函式

>>> 2**3

8>>> pow(2,3)

8>>> -10

-10>>> abs(-10)

10>>>

模組

>>> import math

>>> math.floor(54.69)

54>>>

這裡我們倒入乙個數學模組math, 該模組中有很多函式,使用math.flooar() 的方式可以訪問這些函式。

>>> from math import sqrt

>>> sqrt(-1)

traceback (most recent call last):

file "", line 1, in valueerror: math domain error

>>> sqrt(100)

10.0

>>>

>>> import cmath # cmath 模組支援複數

>>> cmath.sqrt(-1)

1j>>>

以上是互動式視窗程式設計。當然了,我們可以建立.py檔案來編寫程式。

建立檔案1001_base.py

#!/usr/bin/env python

print("hello world")

(base) [root@8f5e50928415 python_action]# python 1001_base.py 

hello world

10 注釋

在python中單行注釋 使用 #

多行注釋 使用

# 被注釋內容

'''被注釋內容

'''"""

被注釋內容

"""

字串

在python中處理字串,就像處理英文一樣舒服。

>>> x = 'ni shi'       

>>> y = 'zhu ma?'

>>>

>>> x + y

'ni shizhu ma?'

>>> y = ' zhu ma?'

>>> x + y

'ni shi zhu ma?'

>>>

非常方便的拼接。

最基礎完。

Python 基礎知識2

1.類新增新屬性和新屬性賦值 metaclass type class rectangle def init self self.width 0 self.height 0 def setattr self,name,value if name size size property value se...

python基礎知識(2)

1.變數和按引用傳遞 在pyhton中對變數賦值時,你其實是在建立物件的引用。2.動態引用和強型別 python中的物件引用沒有與之相關聯的型別的資訊 即python可以自動判斷所定義的型別不需要進行型別宣告 而隱式轉換只是在很明顯的情況下才會發生。可以用type 檢視變數的型別,也可以用isins...

Python基礎知識(2)

在程式語言中,注釋的作用是為了讓自己或他人更快地了解程式作者的思路和意圖,提高 的可讀性。同時在多人協同開發時,也可以提高開發效率。特備說明 注釋部分不參與 的編譯執行。單行注釋主要應用於對某個變數,等的簡短說明,不能換行,只能在一行內應用。多行注釋主要運用於大段文字的說明,可以換行使用,一般用於對...