【python】(第一章)1.4 數字和表達式
以下內容是我學習《Python基礎教程》第2版 這本書所寫的筆記
轉載請註明出處
1.
>>> 2.75%.5
0.25
【不同】C語言中取余運算必須為整數,不能是浮點型
2.
>>>(-3)**2
9
【不同】C語言中pow (double x,double n);(將返回x的n次冪)
【python 也有這個內建函數】
>>>pow(2,3)
8
1.7 獲取用戶輸入
>>>x=input("x:")
x:
【不同】C語言中printf("please input x:");scanf("%d",&x);
1.8 函數
pow,abs,round 不需要導入模塊,也不需要print。
>>>round(35.5)
36.0
1.9 模塊
>>>import math 【不同】#includ<math.h>
>>>math.floor(32.5)
32.0
>>>int(math.floor(32.5)) 【不同】在C語言中c=(int)a;
32
>>>from math import sqrt | >>>import math
>>>sqrt(9) | >>>foo=math.floor
3.0 | >>>foo(32.5)
| 32.0
| >>>floor(32.5)
| ...not defined
負數的平方根為虛數
>>>import cmath
>>>cmath.sqrt(-1)
1 j(虛數)
>>>(1+3j)*(9+4j) 【(a+bi)(c+di)=(ac-bd)+(bc+ad)i】
(-3+31j) 【可以直接計算不用導入cmath】
值被轉換為字符串的兩種機制
1.>>>print repr("Hello,world") 【""or‘‘都可以】
‘Hello,world!‘ 【以合法的python表達式的形式來表示值】
2.>>>print str("Hello,world") 【合理形式的字符串】【print語句必須加】
Hello,world
【python打印值的時候會保持該值在python代碼中的狀態】
>>>"Hello,world"
‘Hello,world!‘
【使用print語句】
>>>print "Hello,world"
Hello,world
【字符串與數字相加】
【反引號在esc下面1的左邊,不用按shift鍵】
>>>temp=42
>>>print "is:"+`temp` 【反引號】【必須加print】
is:42
>>>print "is:"+str(‘temp‘) 【str】【必須加print】
is:42
>>>print "is:"+repr(‘temp‘) 【repr】【必須加print】
is:‘42‘
【str,repr,反引號 是將python值轉換為字符串的3種方式】
【str讓字符串更容易閱讀,而repr和反引號則把結果字符串轉為合法的python表達式】
1.11.4 input 和 raw_input的比較
>>>name=input("what is your name?")
what is your name? " lili"
>>>print "Hello,"+name+"!"
Hello,lili!
【input會假設用戶輸入的是合法的python表達式,如果不用字符串輸入會出錯】
【要求用戶帶引號輸入他們的名字有點過分】
【這就需要使用raw_input函數】
【它會把所有輸入當做原始數據(raw data),然後將其放入字符串中】
>>>name=raw_input("what is your name?")
what is your name?lili
>>>print "Hello,"+name+"!"
Hello,lili!
【除非對input有特別的需要,否則應該盡可能使用raw_input】
1.11.5 長字符串、原始字符串和Unicode
長字符串
>>>"""is
...123
...+ll""" 【三個單引號也可以】
>>>‘is\n 123\n+11‘
>>>"""is\
...123\
...+ll""" 【不能前面三個雙引號,後面三個單引號,三個單引號會被當成字符串】
>>>‘is123+11‘
【普通字符串也可以跨行,只要加上反斜杠,讓換行符轉義】
>>> \
...1+2
3
原始字符串
【原始字符串不會把反斜線當作特殊字符】
>>> print r ‘C:\nowhere‘
C:\nowhere
>>>print r ‘let\‘s go!‘
let\‘s go!
【不能在原始字符串結尾輸入反斜線】
>>>print r "aaaa\"
error
【解決此類問題的技巧】
>>>print r ‘C:\program \foo\bar‘ ‘\\‘
C:\program \foo\bar\
Unicode字符串
【python的普通字符串在內部是以8位的ASCII碼形式儲存的】
【Unicode字符串則儲存為16位】【可以儲存世界上大多數語言的特殊字符】
>>>u ‘Hello,world!‘
u ‘Hello,world!‘
【python】(第一章)1.4 數字和表達式