1. 程式人生 > 其它 >Python 基礎1

Python 基礎1

變數

1.變數定義

  • 在 Python 中,每個變數 在使用前都必須賦值,變數 賦值以後 該變數 才會被建立

  • 等號(=)用來給變數賦值

2.變數型別

在記憶體中建立一個變數,會包括:

  1. 變數的名稱

  2. 變數儲存的資料

  3. 變數儲存資料的型別

  4. 變數的地址(標示)

**** Python 在定義變數時不需要指定型別!

**** Python 可以根據 = 等號右側的值,自動推匯出變數中儲存資料的型別

變數型別可分為:數字型別和非數字型別

數字型:整數,浮點數,布林型,複數型

非數字型:字串,列表,元組,字典

3.變數之間的計算

1) 數字型變數 之間可以直接計算
2) 字串變數 之間使用 + 拼接字串
3) 字串變數 可以和 整數 使用 * 重複拼接相同的字串
4) 數字型變數 和 字串 之間 不能進行其他計算

jici = 1.23
title = "**<>**"

print(type(jici)) ##  <class 'int'>
## print(jici * 100)
print(title * 10)

fjici = int(jici)
print(fjici)
print(type(fjici))

4.變數輸入輸出

print

input

型別轉換

print(type(jici)) ##  <class 'int'>
## print(jici * 100)
print(title * 10)
fjici = int(jici)
print(fjici)
print(type(fjici)) # 1. 輸入蘋果單價 price_str = input("請輸入蘋果價格:") # 2. 要求蘋果重量 weight_str = input("請輸入蘋果重量:") # 3. 計算金額 # 1> 將蘋果單價轉換成小數 price = float(price_str) # 2> 將蘋果重量轉換成小數 weight = float(weight_str) # 3> 計算付款金額 money = price * weight print(money)
print('------------------1----------------
') a=100#整形變數 b=100.0#浮點型變數 c='zifuxing'#字串 print(a,b,c) print('---------------------2------------------') a=b=c=1 print(a,b,c) a,b,c=1,2,3 print(a,b,c) print('--------------------3-------------------') print('Number 數字') a,b,c=20,5.5,True #type可以查詢變數所指的資料型別 print(type(a),type(b),type(c)) #也可以用isinstance來判斷 # type()不會認為子類是一種父類型別 #isinstance()會認為子類是一種父類型別 print('String 字串') str1='zifuchuan' print(str1[0:-1])#輸出第一個到倒數第二個 print(str1[0])#輸出第一個字串 print(str1[2:5])#輸出第三個到第五個字串 print(str1[2:])#輸出第三個後面所有的字串 print(str1*2)#輸出字串2次 print(str1+'Test')#連結字串 print('列表') listp=['abc',768,2.33,'liebiao',70.2] tinylist=[123,'liebiao'] print(listp)#輸出完整列表 print(listp[0])#輸出列表的第一個元素 print(listp[1:3])#輸出第二個元素到第三個元素 print(listp[2:])#輸出第三個元素開始的所有元素 print(tinylist*2)#輸出兩次列表 print(listp+tinylist)#連結兩個列表 #該變列表中的元素 a=[1,2,3,4,5,6] a[0]=9 a[2:5]=[13,14,5] a[2:5]=[]#可以刪除所指定的元素 print('Tuple 元組,用法跟上面的一樣但修改不了元素') print('set 集合') student={'Tom','Jim','Mary','Tom','Jack','Rose'} print(student)#輸出集合,重複的元素被自動去掉 if 'Rose' in student: print('Rose 在集合中') else: print('Rose不在集合中') #set可以進行集合運算 a=set('abra') b=set('alac') print(a)#set可以去重複所以輸出啊a,b,r print(a-b)#a和b的差 print(a|b)#a和b,的並集 print(a&b)#a和b的交集 print(a^b)#a和b不同時存在的元素 print('Dictionary 字典') tinydict={'name':'runoob','code':'1','site':'www.runoob.com'} print(tinydict)#輸出完整的字典 print(tinydict.keys())#輸出所有的建 print(tinydict.values())#輸出所有的值 print('----資料型別轉換--------') print(int(3.6))#浮點數轉換為整數 print(float(1))#整數轉換為浮點數 print(float('123'))#字串轉為浮點數 print(complex(1,2))#整數為複數 print(complex('1'))#字串為負數 dict={'runoob':'runoob.com','google':'goole.com'} print(str(dict)) i=int(10) print(str(i)) print(repr(dict)) x=7 print(eval('3*x'))#可以操作字串 listi=['Google','Taobao','Runoob','Baidu'] print(tuple(listi)) tpo=tuple(listi) t=('1','2','3') print(list(t)) print(tpo) x=set('runoob') y=set('google') print(x,y)
格式化字元含義
%s 字串
%d 有符號十進位制整數,%06d 表示輸出的整數顯示位數,不足的地方使用 0 補全
%f 浮點數,%.2f 表示小數點後只顯示兩位
%% 輸出 %
"""
在控制檯依次提示使用者輸入:姓名、公司、職位、電話、電子郵箱
"""
name = input("請輸入姓名:")
company = input("請輸入公司:")
title = input("請輸入職位:")
phone = input("請輸入電話:")
email = input("請輸入郵箱:")

print("*" * 50)
print(company)
print()
print("%s (%s)" % (name, title))
print()
print("電話:%d" % int(phone))
print("郵箱:%s" % email)
print("*" * 50)

If 語句

import  random

play=int(input("請輸入您要出的拳 石頭(1)/剪刀(2)/布(3):"))
computer =random.randint(1,3) ## 隨機數

print("玩家選擇的拳頭是 %d - 電腦出的拳是 %d" % (play,computer) )

if play > computer:
    print("玩家Win")
elif play<computer:
    print("電腦win")
else:
    print("Agein")

運算子

01. 算數運算子

運算子描述例項
+ 10 + 20 = 30
- 10 - 20 = -10
* 10 * 20 = 200
/ 10 / 20 = 0.5
// 取整除 返回除法的整數部分(商) 9 // 2 輸出結果 4
% 取餘數 返回除法的餘數 9 % 2 = 1
** 又稱次方、乘方,2 ** 3 = 8


02. 比較(關係)運算子

運算子描述
== 檢查兩個運算元的值是否 相等,如果是,則條件成立,返回 True
!= 檢查兩個運算元的值是否 不相等,如果是,則條件成立,返回 True
> 檢查左運算元的值是否 大於 右運算元的值,如果是,則條件成立,返回 True
< 檢查左運算元的值是否 小於 右運算元的值,如果是,則條件成立,返回 True
>= 檢查左運算元的值是否 大於或等於 右運算元的值,如果是,則條件成立,返回 True
<= 檢查左運算元的值是否 小於或等於 右運算元的值,如果是,則條件成立,返回 True


03. 邏輯運算子

運算子邏輯表示式描述
and x and y 只有 x 和 y 的值都為 True,才會返回 True<br />否則只要 x 或者 y 有一個值為 False,就返回 False
or x or y 只要 x 或者 y 有一個值為 True,就返回 True<br />只有 x 和 y 的值都為 False,才會返回 False
not not x 如果 x 為 True,返回 False<br />如果 x 為 False,返回 True


04. 賦值運算子

運算子描述例項
= 簡單的賦值運算子 c = a + b 將 a + b 的運算結果賦值為 c
+= 加法賦值運算子 c += a 等效於 c = c + a
-= 減法賦值運算子 c -= a 等效於 c = c - a
*= 乘法賦值運算子 c *= a 等效於 c = c * a
/= 除法賦值運算子 c /= a 等效於 c = c / a
//= 取整除賦值運算子 c //= a 等效於 c = c // a
%= (餘數)賦值運算子 c %= a 等效於 c = c % a
**= 冪賦值運算子 c = a 等效於 c = c a


05. 運算子的優先順序

運算子描述
** 冪 (最高優先順序)
* / % // 乘、除、取餘數、取整除
+ - 加法、減法
<= < > >= 比較運算子
== != 等於運算子
= %= /= //= -= += *= **= 賦值運算子
not or and 邏輯運算子

迴圈

## 1
i = 1
while i <= 3:
    print("*" * i)
    i += 1
print("i=%d" % i)
print("************")

## 2.計算 0 ~ 100 之間所有數字的累計求和結果
i = 0
result = 0
while i <= 100:
    result += i
    i += 1
print("result=%d" % result)
print("************")

## 3.計算 0 ~ 100 之間 所有 偶數 的累計求和結果
i = 0
result = 0
while i <= 100:
    if i % 2 == 0:
        result += i
    i += 1
print("result=%d" % result)

## 4.break
i = 0
while i < 10:
    # break 某一條件滿足時,退出迴圈,不再執行後續重複的程式碼
    # i == 3
    if i == 3:
        break
    print(i)
    i += 1
print("over")

## 5.continue- 在迴圈過程中,如果 某一個條件滿足後,不 希望 執行迴圈程式碼,但是又不希望退出迴圈,可以使用 continue
## 也就是:在整個迴圈中,只有某些條件,不需要執行迴圈程式碼,而其他條件都需要執行
i = 0
while i < 10:
    # 當 i == 7 時,不希望執行需要重複執行的程式碼
    if i == 7:
        # 在使用 continue 之前,同樣應該修改計數器
        # 否則會出現死迴圈
        i += 1
        continue
    # 重複執行的程式碼
    print(i)
    i += 1

## 6.
i = 0
while i < 6:
    print("* " * i)
    i += 1

## 7
row=1
while row<=9 :
    col=1
    while col<=row :
        print("%d * %d = %d" % (col,row,col*row),end="\t" )## end = "",表示輸出結束後,不換行;"\t" 可以在控制檯輸出一個製表符,協助在輸出文字時對齊
        col +=1
    print("") ## 一行列印完成的換行
    row +=1
轉義字元描述
\\ 反斜槓符號
\' 單引號
\" 雙引號
\n 換行
\t 橫向製表符
\r 回車

函式

## 1 函式
name = "小明"
# say_hello()
# Python 直譯器知道下方定義了一個函式
def say_hello():
    """打招呼"""
    print("hello 1")
    print("hello 2")
    print("hello 3")

print(name)
# 只有在程式中,主動呼叫函式,才會讓函式執行
say_hello()
print(name)

## 2 函式的引數
def sum_2_num(num1, num2):
    result = num1 + num2
    print("%d + %d = %d" % (num1, num2, result))

sum_2_num(50, 20)

## 3 函式的返回值
def sum_2_num(num1, num2):
    """對兩個數字的求和"""
    result = num1 + num2
    # 可以使用返回值,告訴呼叫函式一方計算的結果
    return result
    # 注意:return 就表示返回,下方的程式碼不會被執行到!
    # num = 1000

# 可以使用變數,來接收函式執行的返回結果
sum_result = sum_2_num(10, 20)
print("計算結果:%d" % sum_result)

## 4  函式的巢狀呼叫
def test1():
    print("*" * 50)

def test2():
    print("-" * 50)
    # 函式的巢狀呼叫
    test1()
    print("+" * 50)

test2()

def print_line(char, times):
    """列印單行分隔線
    :param char: 分隔字元
    :param times: 重複次數
    """
    print(char * times)

def print_lines(char, times):
    """列印多行分隔線
    :param char: 分隔線使用的分隔字元
    :param times: 分隔線重複的次數
    """
    row = 0
    while row < 5:
        print_line(char, times)
        row += 1

print_lines("-", 20)

模組

hm_10_分隔線模組.py

def print_line(char, times):

    """列印單行分隔線

    :param char: 分隔字元
    :param times: 重複次數
    """
    print(char * times)


def print_lines(char, times):

    """列印多行分隔線

    :param char: 分隔線使用的分隔字元
    :param times: 分隔線重複的次數
    """
    row = 0

    while row < 5:

        print_line(char, times)

        row += 1


name = "黑馬程式設計師"
import hm_10_分隔線模組

hm_10_分隔線模組.print_line("-", 50)
print(hm_10_分隔線模組.name)
You are never too old to set another goal or to dream a new dream!!!