天天看點

python自學第一課! - star~

python自學第一課!

python基礎

1. 第一句python

==> 以後檔案字尾名是 .py

2. 兩種執行方式

python解釋器 py檔案路徑

python 進入解釋器:

實時輸入并擷取到執行結果

3. 解釋器路徑

#!/usr/bin/env python

4. 編碼

# -*- coding:utf8 -*-

ascill 00000000  8位 中文不支援

unicode 0000000000000000+ 16位+  簡單的字元會占用記憶體

utf-8 能用多少表示就是用多少表示

Python3 無需關注編碼,自動支援

Python2 每個檔案中隻要出現中文,頭部必須加

5. 執行一個操作

#!/usr/bin/env python
# -*- coding:utf8 -*-

#遇見input 永遠等待,直到使用者輸入了值,就會将輸入的值指派給n,n代指使用者輸入的内容

#變量
n1 = input(\'請輸入使用者名: \')
n2 = input(\'請輸入密碼: \') #input 輸入的都是字元串,輸入的數字也當成字元串來處理
print(n1)
print(n2)

#變量,n1代指某一個變化的值
n1 = "alex"
n2 = "root"
print(n1)
print(n2)      

變量:隻能有字母數字下劃線組成,不能以數字開頭,不能使用python關鍵字  

注釋: #号單行注釋   \'\'\'.......\'\'\'三個單引号多行注釋

資料類型轉換:

death_age = 80

name = input("your name :")
age = input("your age:")
#int integer 整數類型 把字元串轉換為int,用int()
#str string 字元串類型,把資料轉換為字元串,用str()
print("your name:",name)
print("you can still live for",death_age-int(age))      

a.IF語句

n1 = input(\'>>>\')
if n1 == "alex":
    n2 = input(\'>>>\')
    if n2 == "确認":
        print(\'alex SB\')
    else:  
        print(\'alex DB\')
else:
    print(\'error\')
# n1 = "alex"指派   n1 == "alex"比較      

b.

if 條件1:

pass

elif 條件2:

pass

elif 條件3:

pass

else:

pass

print(\'end\')

c.

if n1 == "alex" or n2 == "alex!23":

print(\'OK\')

else:

print(\'OK\')

基本資料類型

字元串 -:      n1 = "alex" n2 = \'root\' n3 = """eric""" n4=\'\'\'tony\'\'\'  引号引起來的

n1="star"

n2 = n1*10 表示顯示10次

數字 -:         age=21 weight = 64 fight = 5

加減乘除等:

字元串:

加法:

n1 = "alex"

n2 = "sb"

n4 = "db"

n3 = n1 + n2 + n4

# "alexsbdb"

乘法:

n1 = "alex"

n3 = n1 * 10

數字:

n1 = 9
n2 = 2

n3 = n1 + n2
n4 = n1 - n2
n5 = n1 * n2
n6 = n1 / n2
n7 = n1 % n2 取餘數
n8 = n1 ** n2
n9 = n1 // n2 取商
print(n3,n4,n5,n6,n7,n8,n9)      
num = 12    
n = num % 2
if n == 0:
    print(\'偶數\')
else:
    print(\'奇數\')      

循環:

死循環 

import   time

while 1==1:

  print(\'ok\',time.time())

print(132)   #這行永遠不會執行

import time
count = 0
while count < 10:
    print(time.time())
    count = count + 1
print(\'ok\')      

練習:

#使用while循環輸入1 2 3 4 5 6 7 8 9 10
\'\'\'
i = 1
while i <= 10:
    input(\'>>>\')
    i=i+1
\'\'\'
#求1-100的所有數的和
\'\'\'
i = 1
a = 0
while i<= 100:
    a = a + i
    i = i+1
print(a)
\'\'\'
#輸出1-100内的所有奇數
\'\'\'
i = 1
while i <= 100:
    if i%2 == 1:
        print(i)
    i=i + 1
\'\'\'

#輸出1-100内的所有偶數
\'\'\'
i = 1
while i <= 100:
    if i%2 == 0:
        print(i)
    i=i + 1
\'\'\'
#求1-2+3-4+5...99所有的和
i = 1
s = 0
while i < 100:
    if i % 2 == 0:
        s = s - i
    eles:
        s = s + i
    i = i + 1

#使用者登入(三次機會重試)
\'\'\'
i = 1
username = "star"
userpassword = "123456"
while i <= 3:
    name = input(\'請輸入使用者名:\')
    password = input(\'請輸入密碼:\')
    if name == username and password == userpassword:
        print(\'登入成功\',name)
        break
    else:
        print(\'使用者名密碼輸入不正确\')
        i = i + 1
\'\'\'