变量, 表达式, 语句

变量

变量是构成表达式的最基本单位, 因为python是动态语言, 变量没有固定的类型

In [1]:
# 给变量赋值
msg = 'this is a message'
print(msg)
#使用内置函数type()查看变量的类型
print( type(msg) )

pi = 3.1415926
print(pi)
print(type(pi))

n = 20
print(type(n), n)
this is a message
<class 'str'>
3.1415926
<class 'float'>
<class 'int'> 20

变量名不能与关键字相同, python的关键字如下: keywords

变量名是对值的引用, 每个变量名在被赋值之后, 都指向了内存中的一个对象 vairable_is_ptr

表达式

python的表达式非常简洁,看如下例子

In [10]:
#数学运算
print('3 + 5 = ', 3 + 5)
print('3 - 5 = ', 3 - 5 )
print('3 ^ 5 = ', 3 ** 5)  # 3的5次方
print('5 / 3 = ', 5 / 3)    # 3除以5(非整除)
print('5 // 3 = ', 5 // 3)  # 3除以5(整除))
print('3 * 5 = ', 3 * 5)
print('5 % 3 = ', 5 % 3) # 取余运算
3 + 5 =  8
3 - 5 =  -2
3 ^ 5 =  243
5 / 3 =  1.6666666666666667
5 // 3 =  1
3 * 5 =  15
5 % 3 =  2
In [3]:
# 字符串运算
# 用+号连接两个字符串, 返回一个新的字符串
s1 = 'hello '
s2 = 'world'
print('s1 + s2 = ', s1 + s2)
print('s1 = ', s1)
print('s2 = ', s2)


# 用 * 号将字符串重复n次
#print()函数会将参数一个一个输出, 并在末尾输出换行符, 参数中间用一个空格隔开
print('python is ', 's' + 'o' * 10, 'cool')  
s1 + s2 =  hello world
s1 =  hello 
s2 =  world
python is  soooooooooo cool
In [4]:
# 逻辑表达式

print(type(True))
print(type(False))
x = 10
print('x = ', x)
print('0 < x < 20 : ',0 < x < 20)  # 逻辑表达式 
print('0 > -x > -20 : ', 0 > -x > -20)
print('x > 0 and -x < 0 : ' , x > 0 and -x < 0)
print('not True : ' , not True)  # not运算符对逻辑值取反
print('not False' , not False)
<class 'bool'>
<class 'bool'>
x =  10
0 < x < 20 :  True
0 > -x > -20 :  True
x > 0 and -x < 0 :  True
not True :  False
not False True

语句

python中, 一条语句占一行, 可以用分号;结尾, 但不是必须的
也可以在一行中写多条语句, 中间用分号;分开
但是python的表达能力很强, 一条语句已经能够做很多的事情, 因此不建议在一行中写多条语句

In [5]:
a = 'this is an assignment statement, which occupies one line'
b = 2; c = 3;  # 在一行中写了两条语句

print('a = ', a)
print('b = ', b)
print('c = ', c)
print('-' * 20)

#上面第二行中的两条语句可以简写为如下
# 这其实是python中的内置对象tuple, 后面会介绍到
b , c = 4 , 5
print('b = ', b)
print('c = ', c)
a =  this is an assignment statement, which occupies one line
b =  2
c =  3
--------------------
b =  4
c =  5
In [6]:
# 选择语句, 可以任意嵌套

if x < 0:
    print('x is negative')
elif x > 0:
    print('x is positive')
else:
    print('x equals zero')

# while循环语句
i = 0
while i < 10:
    i += 1
print('i = ', i)

# for 循环语句
for j in range(5):
    print('j = ',j )
x is positive
i =  10
j =  0
j =  1
j =  2
j =  3
j =  4
In [19]:
#类型检查
print('4 is int : ',  isinstance(4, int) )
print('4 is str : ',  isinstance(4, str) )
print("'abc' is str : ", isinstance('abc', str))  # 用单引号 与双引号可以相互嵌套
print('"abc" is int : ' , isinstance("abc", int))
print('1.5 is int : ', isinstance(1.5, int))
print('1.5 is float : ', isinstance(1.5, float))
4 is int :  True
4 is str :  False
'abc' is str :  True
"abc" is int :  False
1.5 is int :  False
1.5 is float :  True