1.1 在交互式環境中輸入表達式
可用Python或Anaconda進入Python交互環境。
>>> 2+2
4
數學操作符:
** 指數 2**3 8
% 取模/取餘數 22%8 6
// 整除/商數取整 22//8 2
/ 除法 22/8 2.75
* 乘法 3*5 15
+ 加法 3 +4 7
- 減法 9-4 5
1.2 整型、浮點型和字符串數據類型
整型: -2, 0, 3
浮點數: -1.24, 1.44, 3.0
字符串: ‘a', 'hello'
1.3 字符串連接和複製
>>> 'Alice' + 'Bob'
AliceBob
但不能和整型或浮點數相加,否則會出錯 "TypeError: Can't convert 'int' object to str implicitly"
字符串乘整數是將字符串複製多少次
>>> 'Alice' * 5
AliceAliceAliceAliceAlice
1.4 在變量中保存值
spam = 42, spam = 'China'
變量名規則: 只能是一個詞,只能包含字母、數字和下劃線,不能以數字開頭,區分大小寫!
1.5 第一個程序
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
註釋: # 開頭爲註釋
input(): 等待用戶在鍵盤上輸入一些文本
print(): 打印
len():返回字符串中字符的個數
str(): 將數字類型 轉化 爲 字符串型; int(): 將字符串型或浮點數轉化爲整型; float(): 將字符串或整型轉爲浮點數。