Python學習之基礎學習1

最近幾天做不實驗,無所事事決定學一下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

每天進步一點點~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章