Day1-Python入門

1、什麼是Python
Python是一門計算機語言,學習它就跟學習英語同樣,想學好它,就要跟學好英語同樣。單詞(關鍵字)+語法
Python解釋器是使用C語言編寫的。python

目前Python主要應用領域linux

1 WEB開發——最火的Python web框架Django, 支持異步高併發的Tornado框架,短小精悍的flask,bottle;                 
2 網絡編程——支持高併發的Twisted網絡框架, py3引入的asyncio使異步編程變的很是簡單;                                 
3 爬蟲——爬蟲領域,Python幾乎是霸主地位,Scrapy\Request\BeautifuSoap\urllib等,想爬啥就爬啥;                 
4 雲計算——目前最火最知名的雲計算框架就是OpenStack,Python如今的火,很大一部分就是由於雲計算                              
5 人工智能——誰會成爲AI和大數據時代的第一開發語言?已經是一個不須要爭論的問題。Python 做爲 AI 時代頭牌語言的位置基本確立;                 
6 自動化運維——問問中國的每一個運維人員,運維人員必須會的語言是什麼?10我的相信會給你一個相同的答案,它的名字叫Python                      
7 金融分析——到目前,Python是金融分析、量化交易領域裏用的最多的語言                                               
8 科學運算——Python愈來愈適合於作科學計算,和科學計算領域最流行的商業軟件Matlab相比,Python是一門通用的程序設計語言;                
9 遊戲開發——在網絡遊戲開發中Python也有不少應用。相比Lua or C++,Python 比 Lua 有更高階的抽象能力,Python更適合做爲一種Host語言。

2、編程語言分類
機器語言:優勢是最底層,執行速度快;缺點是最複雜,開發效率低;
彙編語言:優勢是比較底層,執行速度快;缺點是複雜,開發效率低;
高級語言:站在(奴隸主)的角度,說人話,即用人類的字符去編寫程序,屏蔽了硬件的操做。web

高級語言又分爲:
編譯型(須要編譯器,至關於用谷歌翻譯):如C語言,執行速度快,調試麻煩。語言執行速度快,不依賴語言運行環境,跨平臺差;
解釋型(須要解釋器,至關於同聲傳譯):如python,執行速度慢,調試方便。跨平臺好,一份代碼,處處使用,缺點是執行速度慢,依賴解釋器運行。
這裏強調下:速度不是關鍵(瓶頸理論),開發效率高才是王道。。。機器執行1s,考慮網絡延遲10s;高級語言執行3s,網絡延遲10s,一樣整個過程都是10s。
3、第一個Python程序
進入解釋器的交互模式:調取方便,沒法永久保存代碼;
腳本文件的方式(notepad++):永久保存代碼;
PS. python解釋器執行程序是解釋執行,即打開文件讀取內容,所以文件的後綴名沒有硬性限制,但一般定義爲.py結尾。
執行Python程序的三個階段:編程

1. 啓動python.exe軟件,並放入內存中;flask

2. 由python解釋器將文件內容由硬盤讀取到內存中;網絡

3. 解釋執行剛剛讀進來的內容。併發

4、變量
程序執行的本質就是一系列狀態的變化,變是程序執行的直接體現,因此咱們須要有一種機制可以反映或者說是保存下來程序執行時狀態以及狀態的變化。
變量名(至關於門牌號,指向值所在的空間),等號,變量值;框架

變量的定義規範運維

1 變量名只能是 字母、數字或下劃線的任意組合
2 變量名的第一個字符不能是數字
3 關鍵字不能聲明爲變量名['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 
'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

實操異步

# print('hello world')
# age=10
# #定義一個變量,會有三個特徵:id,type,value
#
# print(id(age),type(age),age)
#
# name='egon'
# print(id(name),type(name),name)

# #id不是真正的內存,是python自定義的。

# print=123
# print('abcde')
# #不能用特殊字符作變量名

#變量的命名方式:
#1:駝峯體
# AgeOfOldboy=73
#2:下劃線(推薦)
# age_of_oldboy=73

# x='age_of_guoxq:18'
# y='age_of_guoxq:18'
# print(id(x),id(y))

#常量
AGE_OF_OLDBOY=73
AGE_OF_OLDBOY=72
print(AGE_OF_OLDBOY)

5、用戶與程序交互

linux環境要寫:  
#!/usr/bin/env python
#coding:utf-8

實操

#在python3中的input:不管用輸入何種類型,都會存成字符串類型
# name=input('please input your name: ')   #name='18',仍然被認爲是字符串;
# print(id(name),type(name),name)

'''
在python2中
raw_input與python3的input是同樣的
name=raw_input('please input your name: ')
print(id(name),type(name),name)
'''

#python2中input,用戶必須輸入值,輸入的值是什麼類型,就存成什麼類型
name=input('please input your name: ')
print(id(name),type(name),name)

#'egon'才正確;18的type會被識別爲int。

6、基本數據類型

字符串

1 在python中,加了引號的字符就是字符串類型,python並無字符類型。
2 定義:name='egon' #name=str('egon') 
3 用於標識:描述性的內容,如姓名,性別,國籍,種族

列表

1 在[]內用逗號分隔,能夠存放n個任意類型的值
2 定義:students=['egon','alex','wupeiqi',] #students=list(['egon','alex','wupeiqi',]) 
3 用於標識:存儲多個值的狀況,好比一我的有多個愛好

字典

1 在{}內用逗號分隔,能夠存放多個key:value的值,value能夠是任意類型
2 定義:info={'name':'egon','age':18,'sex':18} #info=dict({'name':'egon','age':18,'sex':18})
3 用於標識:存儲多個值的狀況,每一個值都有惟一一個對應的key,能夠更爲方便高效地取值

布爾

 1 布爾值,一個True一個False
 2 計算機俗稱電腦,即咱們編寫程序讓計算機運行時,應該是讓計算機無限接近人腦,或者說人腦能幹什麼,計算機就應該能幹什麼,人腦的主要做用是數據運行與邏輯運算,
此處的布爾類型就模擬人的邏輯運行,即判斷一個條件成立時,用True標識,不成立則用False標識
3 >>> a=3 4 >>> b=5 5 >>> 6 >>> a > b #不成立就是False,即假 7 False 8 >>> 9 >>> a < b #成立就是True, 即真 10 True

實操

#數字
#int整型:年紀,身份證號,qq號,等級
# age=18 #age=int(18)

#float浮點型:身高,體重,薪資
# height=1.81
# height=float(1.81)
# print(type(height),height)


#字符串類型:把一對字符放到單引號或者雙引號或者三引號中
#字符串:表示一些描述性狀態,人的名字,人的性別
# name="egon" #name=str("egon")
# print(type(name))
#
# comment='''
# 老男孩的alex,買了一輛tesla,然而,sb纔買tesla呢
# '''
#
# msg="i'm is ok"

#字符串拼接:
#1 只能字符串之間拼接
#2 字符串之間只能用+或*
# name='egon'
# msg='hello'
# age=18
# print(name+msg+str(age))
#
# print(name*10)


# hobbies='play read music movie'
# print(hobbies)
#列表:定義在[]內,用逗號分隔開的多個元素,每一個元素能夠是任意類型
#表示:存取放多個值,好比存放人的愛好,人的信息,
# hobbies=['play','read','music','movie'] #hobbies=list(['play','read','music','movie'])
# print(type(hobbies))
# print(hobbies[3])
# print(hobbies[0])
# print(hobbies[-1])

# print(hobbies[10])

# l=[1,1.3,'egon',['a','b']]
# print(l[3][1])


#      id             name   sex    hobbies
# info=[12312312321312,'egon','male',['read','music',]]
# print(info[3][1])
# print(info[1])


#字典:定義的{}內,用key=value形式表示一個元素,用逗號分隔開
# info={'name':'egon','id':12312312321312,'sex':'male','hobbies':['read','music',]}
# print(info['name'])
# print(info['hobbies'][1])

"""
info={
        'name':'guoxq',
        'hobbies':['play','music'],
        'company_info':{
            'name':'oldboy',
            'type':'edu',
            'num':40
        }
    }
print(info['company_info']['name'])
"""

"""
students=[
    {'name':'alex','age':38,'hobbies':['play','sleep']},
    {'name':'egon','age':18,'hobbies':['read','sleep']},
    {'name':'wupeiqi','age':58,'hobbies':['music','read','sleep']},
]
print(students[1]['hobbies'][1])
"""

#布爾類型:
# print(type(True))
# # print(type('true'))
AGE=73
age=18
print(age > AGE)
print(age < AGE)

7、格式化輸出
程序中常常會有這樣場景:要求用戶輸入信息,而後打印成固定的格式
好比要求用戶輸入用戶名和年齡,而後打印以下格式:
My name is xxx,my age is xxx.
這就用到了佔位符,如:%s、%d

佔位符

#%s字符串佔位符:能夠接收字符串,也可接收數字
print('My name is %s,my age is %s' %('egon',18))
#%d數字佔位符:只能接收數字
print('My name is %s,my age is %d' %('egon',18))
print('My name is %s,my age is %d' %('egon','18')) #報錯

#接收用戶輸入,打印成指定格式
name=input('your name: ')
age=input('your age: ') #用戶輸入18,會存成字符串18,沒法傳給%d

print('My name is %s,my age is %s' %(name,age))

#注意:
#print('My name is %s,my age is %d' %(name,age)) #age爲字符串類型,沒法傳給%d,因此會報錯

實操

#My name is xxx,my age is xxx

# name=input("user_name>>: ")
# age=input("user_age>>: ")

# print('My name is ,my age is',name,age)
# print('My name is %s,my age is %s' %(name,age))
# print('My name is %s,my age is %s' %('egon','18'))
# print('My name is %s,my age is %s' %('egon',18))
# print('My name is %s,my age is %d' %('egon',18))
print('My name is %s,my age is %d' %('egon','18'))

練習題

練習:用戶輸入姓名、年齡、工做、愛好 ,而後打印成如下格式
------------ info of Egon -----------
Name : Egon
Age : 22
Sex : male
Job : Teacher 
------------- end -----------------

name=input('Name>>:')
age=input('Age>>:')
sex=input('Sex>>:')
job=input('Job>>:')
print('------------ info of Egon -----------')
print('Name  : %s' %name)
print('Age   : %s' %age)
print('Sex   : %s' %sex)
print('Job   : %s' %job)
print('------------- end -----------------')

8、基本運算符

如下假設變量:a=10,b=20

算術運算

比較運算

賦值運算

邏輯運算

>>> True or Flase and False
True
>>> (True or Flase) and False
False

身份運算

is比較的是id
而==比較的是值

實操

a=100
b=31
# res=a+b

# print(a+b)
# print(a-b)
# print(a*b)
# print(a/b) #真正的除法,有整數,有小數
# print(a//b) #地板除,只取整數部分
# a=10
# b=3
# print(a%b) #地板除,只取整數部分
# print(3**2) #地板除,只取整數部分


#比較運算
age=73

# print(age > 30)
# print(age < 30)
# print(age != 30)
# print(age != 73)
# print(age == 73)


#賦值運算
# height=180
#
# height+=1 #height=height+1  變量名和運算符號移到=左邊
#
# print(height)


#邏輯
# age=11
# name='egon'
# print(age > 10 and name == 'ego1111111n')
# print(age > 10 or name == 'ego1111111n')

# age=11
# print(age > 3)
# print(not age > 10)

9、流程控制之if...else
      咱們編程的目的是爲了控制計算機可以像人腦同樣工做,那麼人腦能作什麼,就須要程序中有相應的機制去模擬。人腦無非是數學運算和邏輯運算,對於數學運算在上一節咱們已經說過了。對於邏輯運算,即人根據外部條件的變化而作出不一樣的反映。

實操

# age=input('>>: ')
# age=int(age)
# if age > 30:
#     print('叫阿姨')

#
# age=input('>>: ')
# age=int(age)
# if age > 30:
#     print('叫阿姨')
# else:
#     print('叫妹妹')
#

# sex=input('sex>>: ')
# age=int(input('age>>: '))
# is_pretty=True
# if sex == 'female' and age > 18 and age < 30 and is_pretty == True:
#     print('表白中。。。')
# else:
#     print('叫阿姨')

# x='True'
# print(bool(x))   只要不是x=''結果都爲True
#
# sex = input('sex>>: ')
# age = int(input('age>>: '))
# is_pretty = bool(input('is_pretty>>: '))
#
# if sex == 'female' and age > 18 and age < 30 and is_pretty == True:
#     print('表白中。。。')
# else:
#     print('叫阿姨')


#if嵌套
# age = int(input('age>>: '))
# is_pretty = bool(input('is_pretty>>: '))
#
# success=False
# if sex == 'female' and age > 18 and age < 30 and is_pretty == True:
#     if success:
#         print('在一塊兒')
#     else:
#         print('什麼尼瑪的愛情,去qnmlgb的愛情啊。。。')
# else:
#     print('叫阿姨')


#if多分支
score=int(input("your score>>:"))

if score >= 90:
    print('優秀')
elif score >= 80:
    print('良好')
elif score >= 70:
    print('及格')
else:
    print('太差了')

練習題

一、用戶登陸驗證

name='guoxq'
passowrd=123456
name=input('please input your name >>:')
passowrd=int(input('password >>:'))

if name == 'guoxq' and passowrd == 123456:
    print('登錄成功')
else:
    print('登陸失敗')

二、根據用戶輸入內容輸出其權限

msg=input('請輸入你的驗證碼:')
if msg == 'glod':
    print('你有管理權限')
elif msg == 'silver':
    print('你有副管理員權限')
elif msg == 'bronze':
    print('你有用戶權限')
else:
    print('你不具有任何條件')

三、工做日與週末

Today=input('Today is ')
if Today == 'Monday' or Today == 'Tuesday' or Today == 'Wednesday' or Today == 'Thursday' or Today == 'Friday':
    print('上班')
elif Today == 'Saturday' or Today == 'Sunday':
    print('出去浪')
else:
    print('不存在的節日')

或者:
today=input('>>: ')
if today in ['Saturday','Sunday']:
    print('出去浪')
elif today in ['Monday','Tuesday','Wednesday','Thursday','Friday']:
    print('上班')
else:
    print('''必須輸入其中一種:
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
    Sunday
    ''')

10、流程控制之while
那麼如何作到不用寫重複代碼又能讓程序重複一段代碼屢次呢? 循環語句就派上用場啦
條件循環:while,語法以下
while 條件:
  # 循環體

  # 若是條件爲真,那麼循環體則執行,執行完畢後再次循環,從新判斷條件。。。
  # 若是條件爲假,那麼循環體不執行,循環終止
PS.
break:跳出本層循環;
continue:跳出本次,直接進入下一次循環。直到代碼的中間位置,後面的代碼再也不運行了。

break&continue

#break用於退出本層循環
while True:
    print ("123")
    break
    print ("456")

#continue用於退出本次循環,繼續下一次循環
while True:
    print ("123")
    continue
    print ("456")

while+else

#與其它語言else 通常只與if 搭配不一樣,在Python 中還有個while ...else 語句,while 後面的else 做用是指,當while 循環正常執行完,中間沒有被break 停止的話,就會執行else後面的語句
count = 0
while count <= 5 :
    count += 1
    print("Loop",count)

else:
    print("循環正常執行完啦")
print("-----out of while loop ------")
輸出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循環正常執行完啦
-----out of while loop ------

#若是執行過程當中被break啦,就不會執行else的語句啦
count = 0
while count <= 5 :
    count += 1
    if count == 3:break
    print("Loop",count)

else:
    print("循環正常執行完啦")
print("-----out of while loop ------")
輸出

Loop 1
Loop 2
-----out of while loop ------

嵌套tag的玩法

  tag=True 

  while tag:

    ......

    while tag:

      ........

      while tag:

        tag=False

實操

# AGE_OF_OLDBOY=73
#
# guess=int(input('請輸入老男孩的年齡: '))
# if guess > AGE_OF_OLDBOY:
#     print('太大了')
# elif guess < AGE_OF_OLDBOY:
#     print('過小了')
# else:
#     print('蒙對了')
#
#猜想三次呢?不能把上面的程序重複寫三次吧?!
#
#while:條件循環
# while 條件:
#     循環體


# count=0
# while count < 3:
#     print('loop',count)
#     count+=1

# count=0
# while True:
#     if count < 101:
#         print(count)
#     count+=1

#break:跳出本層循環
# count=0
# while True:
#     if count > 100:
#         break
#     print(count)
#     count+=1

#continue:跳出本次循環
# count=0
# while True:
#     if count > 10:
#         break
#     print(count)
#     count+=1

# count=0
# while count <= 10:
#     print(count)
#     count+=1

# count=0
# while count <= 10:
#     if count == 7:
#         count+=1
#         continue
#     print(count)
#     count+=1

# count=0
# while count < 11:
#     print(count)
#     count+=1
# else:
#     print('while正常循環完畢,沒有被break打斷,纔會執行這裏的代碼')

#while+else:
# count=0
# while count <= 10:
#     if count == 3:
#         break
#     print(count)
#     count+=1
# else:
#     print('while正常結束了,沒有被break打斷,纔會執行這裏的代碼')



#注意一:
# count=0
# while count <= 5:
#     print(count)
#     count+=1
#     # continue #加到這裏沒意義


#注意二:

# name='egon'
# password='alex3714'
# count=0
# while count < 3:
#     u=input('u>>:')
#     p=input('p>>:')
#
#     if u == name and p == password:
#         print('login sucessful')
#         break
#     else:
#         print('user nor password err')
#         count+=1

# name='guoxq'
# password='123'
# count=0
# while count < 3:
#     user=input('請輸入用戶名: ')
#     passw=input('請輸入密碼: ')
#     if user == name and passw == password:
#         print('login successful')
#         break
#     else:
#      print('login fail')
#      count+=1

# name='guoxq'
# password='123'
# count=0
# while True:
#     if  count > 2:
#         break
#     user=input('請輸入用戶名: ')
#     passw=input('請輸入密碼: ')
#     if user == name and passw == password:
#         print('login successful')
#         break
#     else:
#      print('login fail')
#      count+=1

# name='egon'
# password='alex3714'
# count=0
# while True:
#     if count == 3:
#         break
#     u = input('u>>:')
#     p = input('p>>:')
#
#     if u == name and p == password:
#         print('login sucessful')
#         while True:
#             cmd = input('>>: ')
#             if cmd == 'quit':
#                 break
#             print('run %s' % cmd)
#         break
#     else:
#         print('user nor password err')
#         count += 1

# while True:
#     print ("123")
#     break
#     print ("456")
#
# while True:
#     print ("123")
#     continue
#     print ("123")

實現用戶輸入用戶名和密碼,當用戶名爲 seven 或 alex 且 密碼爲 123 時,顯示登錄成功,不然登錄失敗,失敗時容許重複輸入三次

name='egon'
password='alex3714'
count=0
tag=True
while tag:
    if count == 3:
        break
    u = input('u>>:')
    p = input('p>>:')

    if u == name and p == password:
        print('login sucessful')
        while tag:
            cmd = input('>>: ')
            if cmd == 'quit':
                tag=False
                continue
            print('run %s' % cmd)

    else:
        print('user nor password err')
        count += 1

練習題(上):

一、打印0到10,奇數or偶數

#打印0-10
count=0
while count <= 10:
    print('loop',count)
    count+=1

#打印0-10之間的偶數
count=0
while count <= 10:
    if count%2 == 0:
        print('loop',count)
    count+=1

#打印0-10之間的奇數
count=0
while count <= 10:
    if count%2 == 1:
        print('loop',count)
    count+=1

二、使用while循環輸出1 2 3 4 5 6 8 9 10

# count=0
# while True:
#     count += 1
#     if count < 11:
#         if count == 7:
#             continue
#         print(count)

# count=0
# while count < 10:
#     count+=1
#     if  not count ==7:
#         print(count)

# count=0
# while count < 10:
#     count+=1
#     if  count !=7:
#         print(count)

# count=1
# while count <=10:
#     if count == 7:
#         count+=1
#         continue
#     print(count)
#     count+=1

三、求1-100的全部數之和

# res=0
# count=1
# while count <= 100:
#     res+=count
#     print(res)
#     count+=1

四、求1-2+3-4+5 ... 99的全部數的和

# res=0
# count=1
# while count <= 99:
#     if count%2 == 0:
#         res-=count
#     else:
#         res+=count
#     count+=1
# print(res)

五、求2-3+4-5+6...+100的全部數的和

# res=0
# count=2
# while count <= 100:
#     if count % 2 == 0:
#         res+=count
#     else:
#         res-=count
#     count+=1
#     print(res)

六、用戶登錄(三次機會重試)

# name='guoxq'
# password='123'
# count=0
# while count < 3:
#     usr = input('請輸入用戶名: ')
#     passw = input('請輸入密碼: ')
#     if usr == name and passw == password:
#         print('login successful')
#         break
#     else:
#         print('login fail')
#         count+=1

七、猜年齡遊戲

# 要求:
#     容許用戶最多嘗試3次,3次都沒猜對的話,就直接退出,若是猜對了,打印恭喜信息並退出
# AGE_OF_OLDBOY = 73
# count = 0
# while count < 3:
#     age=int(input('>>:'))
#     count+=1
#     if  age > 73:
#         print('bigger')
#     elif age < 73:
#         print('smaller')
#     else:
#         print('congratulation')

# age_of_oldboy=73
# count=0
# while count < 3:
#     guess=int(input('>>: '))
#     if guess == age_of_oldboy:
#         print('you got it')
#         break
#     count+=1

八、猜年齡遊戲升級版

# 要求:
#     容許用戶最多嘗試3次
#     每嘗試3次後,若是還沒猜對,就問用戶是否還想繼續玩,若是回答Y或y, 就繼續讓其猜3次,以此往復,若是回答N或n,就退出程序
#     如何猜對了,就直接退出

# AGE_OF_OLDBOY = 73
# count=0
# while True:
#     if count == 3:
#         choice = input('繼續(Y/N?)>>: ')
#         if choice == 'Y' or choice == 'y':
#             count = 0
#         else:
#             break
#     age = int(input('>>: '))
#     if age == AGE_OF_OLDBOY:
#         print('you got it')
#         break
#     count+=1

# for i in range(1,10):
#     for j in range(1,i+1):
#         print('%s*%s=%s' %(i,j,i*j),end=' ')
#     print()

 

  本小節完結😝

相關文章
相關標籤/搜索