這是一篇我自學Python的文章,可能會斷斷續(xù)續(xù)或者不完整,僅作參考。
略過安裝環(huán)境的步驟。
算數(shù)、字符串與變量
整數(shù)計算
整數(shù)是不帶小數(shù)部分的數(shù)字,例如1,10,22,65
4種基本運算符:+、-、*、/
Python還使用 **和%來表示乘方和求余。//表示整除。
>>>5 + 9
14
>>>22 - 6
16
>>>12 * 15
180
>>>24 / 3
8.0
>>>25 % 6
1
>>>2 ** 4
16
浮點數(shù)計算
在Python中,浮點數(shù)是帶小數(shù)點的數(shù),例如3.2、2.8、-3.2
所有適用于整數(shù)的運算符都可用于浮點數(shù)。
>>> 3.2 * 5.1 + 1.2
17.52
Python同樣存在 溢出 與 精度有限。
其他函數(shù)及模塊導入
acos(x) 求x的反余弦(結果是弧度) acos(2.0)等于0.0
asin(x) 求x的反正弦(結果是弧度) asin(0.0)等于0.0
atan(x) 求x的反正切(結果是弧度) atan(0.0)等于0.0
ceil(x) 為x取整,結果是不小于x的最小整數(shù) ceil(9.2)等于10.0 ceil(-9.8)等于-9.0
cos(x) 求x的余弦(x是弧度) cos(0.0)等于1.0
exp(x) 求冪函數(shù)e` exp(1.0)等于2.71828 exp(2.0)等于7.38906
fabs(x) 求x的絕對值 fabs(5.1)等于5.1 fabs(-5.1)等于5.1
floor(x) 為x取整,結果是不大于x的最大整數(shù) floor(9.2)等于9.0 floor(-9.8)等于-10.0
fmod(x,y) 求x/y的余數(shù),結果是浮點數(shù) fmod(9.8,4.0)等于1.8
hypot(x,y) 求直角三角的斜邊長度,直邊長度為x和y:Sqrt(x2-y2) hypot(3.0,4.0)等于5.0
log10(x) 求x的對數(shù)(以10為底) log10(10.0)等于1.0 log10(100.0)等于2.0
pow(x,y) 求x的y次方(xy) pow(2.7,7.0)等于128.0 pow(9.0,0.5)等于3.0
sin(x) 求x的正弦(x是弧度) sin(0.0)等于0.0
sqrt(x) 求x的平方根 sqrt(900.0)等于30.0 sqrt(9.0)等于3.0
tan(x) 求x的正切(x是弧度) tan(0.0)等于0.0
使用任何模塊前需要導入模塊,下面以math模塊為例
import math #導入math模塊
math.sqrt(5) #調(diào)用math模塊
這兩種導入方式導致調(diào)用的方式不同。
from math import * #導入math模塊
sqrt(5) #調(diào)用math模塊
字符串
字符串是一些字符或字符集合,例如'cat!'、'cat'、'http'
表示字符串需要用引號來表示' '、''' '''、" "
len(c) 可用來統(tǒng)計字符串個數(shù)
>>> len('hello')
5
>>> len('char')
4
len(c) 返回的是整數(shù),可以直接參與整數(shù)運算。
字符串也可以參與“相加”運算,將字符串拼接起來
>>> 'hello' + ' world'
'hello world'
>>> 'hi' * 3
'hihihi'
變量
在Python中,變量標記(label)或者指向一個指。
>>> color = 'blue'
>>> color
'blue'
color 表示的是一個變量名,它指向一個值:‘blue’
變量的命名規(guī)則:
1.變量名長度不限,但必須是字母、數(shù)字、下劃線_,不能使用空格、連字符、標點符號和其他字符。
2.變量名第一個字符不能是數(shù)字。
3.不能將Python關鍵字作為變量名。比如 if、in、is 等。
實例項目
字符串處理
#!/usr/bin/python
# -*- coding:utf-8 -*-
pwd = input("What's your name? \n")
if pwd == 'flower':
print('Logging on success')
else:
print('fild to logging on')
print('All done')
# 另外一種寫法 print('yes') if pwd == 'flower' else 'no'
#可代替上面的寫法
知識點 :
1.字符串的輸入
2.轉義字符
3.條件語句
4.布爾邏輯
5.打印字符串
6.注釋
不定期更新