在本节中,我们将学习Python编程语言的基础知识(版本3)。我们不会学习Python的所有知识点,但足以做一些基础的机器学习。
变量(variables)是python中的对象,可以存储数值或字符串。我们来看看如何创建一些变量。
# 数值示例
x = 5
print (x)
5
# 字符串示例
x = "hello"
print (x)
hello
# 变量可以相互使用
a = 1
b = 2
c = a + b
print (c)
3
变量可以有很多不同的类型。 即使在数值变量中,也可以使用整数(int),浮点数(float)等。所有基于字符串的变量都是string(str)类型。我们可以通过打印它的类型来查看变量的类型。
# int 变量
x = 5
print (x)
print (type(x))
# float 变量
x = 5.0
print (x)
print (type(x))
# text 变量(即为str)
x = "5"
print (x)
print (type(x))
# boolean 变量
x = True
print (x)
print (type(x))
5 <class 'int'> 5.0 <class 'float'> 5 <class 'str'> True <class 'bool'>
知道变量的类型是一种很好的做法。当你想在那时使用数值运算时,它们需要类型兼容。
# int 变量
a = 5
b = 3
print (a + b)
# string 变量
a = "5"
b = "3"
print (a + b)
8 53
列表(lists)是python中的对象,可以包含有序的数字序列和字符串。
# 创建列表
list_x = [3, "hello", 1]
print (list_x)
[3, 'hello', 1]
# 向列表中添加元素
list_x.append(7)
print (list_x)
[3, 'hello', 1, 7]
# 访问列表中特定位置的元素
print ("list_x[0]: ", list_x[0])
print ("list_x[1]: ", list_x[1])
print ("list_x[2]: ", list_x[2])
print ("list_x[-1]: ", list_x[-1]) # 索引值为-1时,表示访问最后的元素
print ("list_x[-2]: ", list_x[-2]) # 索引值为-2时,表示访问倒数第二个元素
list_x[0]: 3 list_x[1]: hello list_x[2]: 1 list_x[-1]: 7 list_x[-2]: 1
# 切片
print ("list_x[:]: ", list_x[:])
print ("list_x[2:]: ", list_x[2:])
print ("list_x[1:3]: ", list_x[1:3])
print ("list_x[:-1]: ", list_x[:-1])
list_x[:]: [3, 'hello', 1, 7] list_x[2:]: [1, 7] list_x[1:3]: ['hello', 1] list_x[:-1]: [3, 'hello', 1]
# 列表的长度
len(list_x)
4
# 替换列表中的元素
list_x[1] = "hi"
print (list_x)
[3, 'hi', 1, 7]
# 组合列表
list_y = [2.4, "world"]
list_z = list_x + list_y
print (list_z)
[3, 'hi', 1, 7, 2.4, 'world']
元组(tuples)也是python中可以保存数据但是不能替换值的对象(因此,元组称为不可变,而列表称为可变)。
# 创建元组
tuple_x = (3.0, "hello")
print (tuple_x)
(3.0, 'hello')
# 添加元素到元组
tuple_x = tuple_x + (5.6,)
print (tuple_x)
(3.0, 'hello', 5.6)
# 试图改变元组的值(事实上不可行)
tuple_x[1] = "world"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-15-86abc19d8025> in <module>() ----> 1 tuple_x[1] = "world" TypeError: 'tuple' object does not support item assignment
字典(dictionaries) 是包含键值对(key-value)的python对象。在下面的字典示例中,键是“name”和“eye_color”变量。它们各自都有与之相关的值。 字典不能有两个相同的键。
# 创建字典
goku = {"name": "Goku",
"eye_color": "brown"}
print (goku)
print (goku["name"])
print (goku["eye_color"])
# 改变键的值
goku["eye_color"] = "green"
print (goku)
# 添加新的键值对
goku["age"] = 24
print (goku)
# 字典的长度
print (len(goku))
您可以使用if语句有条件地执行某些操作。
# If 语句
x = 4
if x < 1:
score = "low"
elif x <= 4:
score = "medium"
else:
score = "high"
print (score)
# 带有布尔值的if语句
x = True
if x:
print ("it worked")
您可以在python中使用for或while循环来重复执行某些操作,直到满足条件为止。
# for循环
x = 1
for i in range(3): # 从 i=0 到 i=2
x += 1 # 等价于 x = x + 1
print ("i={0}, x={1}".format(i, x)) # 打印多个变量
# 循环遍历列表中的元素
x = 1
for i in [0, 1, 2]:
x += 1
print ("i={0}, x={1}".format(i, x))
# while循环
x = 3
while x > 0:
x -= 1 # 等价于 x = x - 1
print (x)
函数(functions)是模块化可重用代码块的一种方法。
# 创建函数
def add_two(x):
x += 2
return x
# 调用函数
score = 0
score = add_two(x=score)
print (score)
# 具有多输入的函数
def join_name(first_name, last_name):
joined_name = first_name + " " + last_name
return joined_name
# 调用函数
first_name = "Goku"
last_name = "Mohandas"
joined_name = join_name(first_name=first_name, last_name=last_name)
print (joined_name)
类(classes) 是面向对象的Python编程的基础部分。
# 创建函数
class Pets(object):
# 类初始化
def __init__(self, species, color, name):
self.species = species
self.color = color
self.name = name
# 用于打印
def __str__(self):
return "{0} {1} named {2}.".format(self.color, self.species, self.name)
# 示例函数
def change_name(self, new_name):
self.name = new_name
# 创建类的实例:对象
my_dog = Pets(species="dog", color="orange", name="Guiness",)
print (my_dog)
print (my_dog.name)
# 调用类的函数
my_dog.change_name(new_name="Charlie")
print (my_dog)
print (my_dog.name)
本文是对python的快速浏览,我们将在未来的课程中学到更多东西。如果您想在进入机器学习之前了解关于python的更多信息,请查看此免费课程: Free Python Course