最近几天做不实验,无所事事决定学一下Python,在网上按照教程学习一下Python,顺便分享一下学到的知识,巩固一下。
1.变量
首先学习的是我们最熟悉的变量,Python中的变量可以包含数字或者文本,下面介绍怎么创建变量:
#example 1
x = 3
print(x)
输出结果为:3
#example 2
x = 'hello'
print(x)
输出结果为:hello
#example 3
a = 5
b = 3
print(a+b)
a = '5'
b = '3'
print(a+b)
输出结果为:8和53
2.列表
列表在Python中可以存放数字和文本的有序序列,下面介绍如何创建列表:
#example 1
list_x = [3,'hello','world']
print(list_x)
输出结果为:[3,'hello','world']
list_x.append('name')
print(list_x)
输出结果为:[3,'helo','world','name']
#example 3
list_y = ['three','nihao','shijie']
list_z = list_x + list_y
print(list_z)
print(list_z[0:2])
输出结果为:[3,'hello','world','name','three','nihao','shijie']和[3,'hello']
3.元组
Python中元组和列表相似,不同的是元组中的内容不能更改,下面介绍元组如何创建:
#example 1
tuple_x = (2.1,'dajiahao')
print(tuple_x)
tuple_x = tuple_x + (3.3,)
print(tuple_x)
输出结果为:(2.1,'dajiahao')和(2.1,'dajiahao',3.3)
#example 2
tuple_x[1] = 'hello everyone'
输出结果为:结果报错,元组中的内容不能更改。
4.字典
字典是Python中的可变容器,创建方法如下:
#example 1
Property = {'name':'dengdeng','height',180}
print(property)
print(property['name'])
print(property['height'])
输出结果为:{‘name’:'dengdeng','height':180}和dengdeng和180
#example 2
porperty['age'] = 23
print(porperty)
输出结果为:{'name':'dengdeng','height':180,'age':23}
5.if语句
Python中的if语句与MATLAB中的稍有区别:
#example 1
x = 3
if x < 2:
score = 'low'
elif x > 5:
score = 'height'
else:
score = 'medium'
输出结果为:medium
6.循环语句
Python中的循环语句有for和while两种:
#example 1
x = 1
for i in range(2):
x += 1
print('i = {0},x = {1}'.format(i,x))
输出结果为:i = 0,x = 2;i = 1,x = 3
#example 2
x = 2
while x > 0:
x -= 1
print(x)
输出结果:1 0
7.函数
函数是Python中模块化可重用代码段的一种方法:
#example 1
def add_three(x):
x += 3
return x
score = 0
score = add_three(x = score)
print(score)
输出结果为:3
8.类
面向对象编程中最重要的概念之一,下面介绍如何创建类属性:
#example 1
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 = 'yellow',name = 'dengdeng')
print(my_dog)
print(my_dog.name)
my_dog.change_name(new_name = 'dingding')
print(my_dog)
print(my_dog.name)
输出结果为:yellow dog named dengdeng和dengdeng和yellow dog named dingding和dingding
最后附上学习网站:https://github.com/GokuMohandas/practicalAI