python的基本使用
print 功能
print 字符串
- python 中 print 字符串 要加’ ‘(单引号)或者” “(双引号)。
>>> print('hello world')
hello world
>>> print("hello world 2")
hello world 2
- print 字符串叠加,可以使用 + 将两个字符串链接起来。
>>> print('Hello world' + ' Hello Gong Kong')
Hello world Hello Gong Kong
简单运算
- 可以直接print 加法+,减法-,乘法*,除法/. 注意:字符串不可以直接和数字相加,否则出现错误。
>>> print(1 + 1) 2 >>> print(3 - 1) 2 >>> print(3 * 4) 12 >>> print(1 + 1) 2 >>> print(3 - 1) 2 >>> print(3 * 4) 12 >>> print(12 / 4) 3.0 >>> print('iphone' + 4) Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> print('iphone' + 4) TypeError: must be str, not int
- 当int()一个浮点型数时,int会保留整数部分,比如 int(1.9),会输出1,而不是四舍五入。
>>> print(int('2') + 3) # int为定义整数型 5 >>> print(int(1.9)) # 当定义为一个浮点型数时,int会保留整数部分 1 >>> print(float('1.2') + 3) # float是浮点型,可以把字符串转换为小数 4.2
基础数学运算
基本的加减乘除
- python可以直接运算数字,也可以加print 进行运算。
>>> 1 + 1
2
>>> 2 - 1
1
>>> 2 * 3
6
>>> 4 / 3
1.3333333333333333
- ^ 与 *:python当中^符号,区别于Matlab,在python中,^用两个*表示,如3的平方为3**2 , **3表示立方,**4表示4次方,依次类推。
>>> 3 ** 2 # **2表示3的二次方
9
>>> 3 ** 3 # **3表示3的三次方
27
>>> 3 ** 4
81
- 取余数 % :取余数符号为“%”。
>>> 8 % 3
2
变量 variable
自变量命名规则
- 可以将一个数值,或者字符串串附值给自变量,如apple=1中,apple为自变量的名称,1为自变量的值。 也可以将字符串赋值给自变量 apple=’iphone7 plus’
apple = 1 # 赋值数字
print(apple) # 输出值为1
apple = 'iphone7 plus' # 赋值字符串
print(apple) # 输出值为iphone7 plus
- 如果需要用多个单词来表示自变量,需要加下划线,如apple_2016=’iphone 7 plus’。
apple_2016 = 'iphone7 plus and new macbook'
print(apple_2016) # 输出值为iphone7 plus and new macbook
- python允许一次定义多个自变量,如 a,b,c=1,2,3。
a, b, c = 11, 12, 13
print(a, b, c) # 输出值为11, 12, 13