01月22日【Python3 基礎知識】
阿新 • • 發佈:2018-02-26
python01月22日【Python3 基礎知識】
2.4 計算器
2.5 tuple操作
2.6 dict
2.7 其他常用操作
2.4 計算器
def add(string): total = 0 numbers = [] numbers += string.split("+") for num in numbers: total += int(num.strip()) print("{0} = {1}".format(string, total)) # def reduce(string): result = 0 numbers = [] numbers += string.split("-") result = int(numbers[0].strip()) numbers.pop(0) for num in numbers: result -= int(num.strip()) print("{0} = {1}".format(string, result)) # def ride(string): total = 1 numbers = [] numbers += string.split("*") for num in numbers: total *= int(num.strip()) print("{0} = {1}".format(string, total)) # def division(string): result = 0 numbers = [] numbers += string.split("/") result = int(numbers[0].strip()) numbers.pop(0) for num in numbers: result /= int(num.strip()) print("{0} = {1}".format(string, result)) if __name__ == ‘__main__‘: print("##############################################") print("1: +法") print("2: -法") print("3: *法") print("4: /法") method = input("請選擇: ") string = input("請輸入:") if method == "1": add(string) elif method == "2": reduce(string) elif method == "3": ride(string) elif method == "4": division(string) else: print("輸入錯誤") print("##############################################")
2.5 tuple操作
# 元組的元素不能修改
t = (‘a‘, ‘b‘, 3, ‘b‘)
print(t)
print(t[0]) # 按下標輸出元素
# index: 按元素輸出下標
print(t.index(‘b‘)) # 默認左往右
print(t.index(‘b‘, -1)) # 倒序查找
# count:統計字符個數
print(t.count(‘b‘))
2.6 dict
# 字典的定義: d1 = dict(name = ‘long‘, age = 30) d2 = {‘id‘:101, ‘name‘:‘longlong‘} d3 = dict([(‘name‘, ‘long‘), (‘age‘, 20)]) print(d1) print(d2) print(d3) # 方法 # get(key): 根據key獲取value # setdefault: 根據key獲取value,如果key不存在,可以設定默認的value print((d1.get(‘name‘))) print(d1.setdefault(‘dizhi‘, ‘guangxi‘)) # print(d1.keys()) print(d1.values()) # for x, y in d1.items(): print("{0}:{1}".format(x, y)) # update: 根據key更新valye;如果沒有key則會添加該鍵值對 print(d1) d1.update(d2) print(d1) # pop:根據key彈出value print(d3.pop(‘name‘)) print(d3)
2.7 其他常用操作
# help: 方法解釋
a = ‘123‘
help(a.count)
# dir: 查看有什麽方法可用
print(dir(a))
## type: 查看變量類型
print(type(a))
# len: 獲取長度
print(len(a))
# isinstance: 判斷變量是否某類型
print(isinstance(a, str))
01月22日【Python3 基礎知識】