Python基本介绍
Python是解释型语言
一般来说,大部分编程语言为编译型或者解释型,这也意味着我们可以直接在解释器里直接输入指令就可以立刻运行:
1 + 2 * 3 - 4
运行结果:
3
多条代码将从上至下逐条运行
x = 5
y = 2
print(x+y)
运行结果:
7
赋值
在Python里,我们用=
进行赋值。语法如x=5
。意思是新建一个变量x
,并将5赋值于x。变量x的类型可以是多种多样,不一定是数值型。
x = 1
print('The value of x is', x)
x = 2.5
print('Now the value of x is', x)
x = 'hello there'
print('Now it is ', x)
运行结果:
The value of x is 1
Now the value of x is 2.5
Now it is hello there
这里x类型分别是整型、浮点型和字符串。变量不需要事前声明变量类型,类型会根据所赋值的类型改变。
函数
和大多数编程语言一样,Python中也是用圆括号()
来执行函数。例如以下四舍五入函数round
将圆周率保留两位小数:
round(3.1415926, 2)
运行结果:
3.14
在Python3中,print
是作为一个函数,可以把变量“打印”出来。
x = 'hello there'
print(x)
hello there
变量类型
Python值都有相应的类型,如果我们使用不恰当类型的值进行运算将会报错。
s = 'Hello Python'
print(s + 5)
运行结果:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
type函数
我们可以通过执行type
函数来查询变量类型:
type(1)
int
type('hello')
str
type(2.5)
float
type(True)
bool
Null值
我们有时候要表示“无数据”或者“不可用,在Python中,我们将使用一个特殊的值None
。这和Java中的Null
类似。None
不会被打印出来。
result = None
我们可以用is
来判断变量是不是None
:
result is None
True
类型转换
我们可以将一个值从原始类型转变为新的类型。类型名比如int
,float
,str
等等也可以作为函数名作用在某个值上,将其转变为新的类型。
将整型int
转变为float
:
x = 1
print(type(x))
y = float(x)
print(y, type(y))
<type 'int'>
(1.0, <type 'float'>)
变量没有类型
变量本身是没有类型之分的,但是变量指代的值是有类型的。因为变量可以反复赋值以覆盖之前的赋值,因此变量所指代的值的类型是可变的。
y = 'hello'
print('The type of the value referred to by y is ', type(y))
y = 5.0
print('And now the type of the value is ', type(y))
The type of the value referred to by y is <class 'str'>
And now the type of the value is <class 'float'>
多态性(Polymorphism)
有些运算符可以作用于不同的数据类型中:
1 + 1
2
'a' + 'b'
'ab'
条件语句和缩进
在Python中,控制结构使用冒号:
和缩进来区分各个层次。缩进一个tab的占位表示一个层次,如果缩进占位不合理将会导致错误。
x = 5
if x > 0:
print('x is strictly positive.')
print(x)
print('finished.')
x is strictly positive.
5
finished.
方法
我们会经常看到这种语法,其中变量名后跟一个点,然后是一个动作名,再跟一组括号。括号可以为空,或者可以包含一些值。
variable_name.action()
在此示例中,action
是方法的名称。方法是可以对变量执行的操作。 例如:
name = 'eren yeager'
print(name.title()) #输出结果为 Eren Yeager
其中name
是字符串,title
方法是已写入Python语言的函数,它对字符串有作用。