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(): 将字符串或整型转为浮点数。