数据类型 Numeric & String
1. Python数据类型
1.1 总体:numerics, sequences, mappings, classes, instances, and exceptions
1.2 Numeric Types: int (包含boolean), float, complex
1.3 int: unlimited length; float: 实现用double in C, 可查看 sys.float_info; complex: real(实部) & imaginary(虚部),用z.real 和 z.imag来取两部分
1.4 具体运算以及法则参见:https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex
import sys
a = 3
b = 4
c = 5.66
d = 8.0
e = complex(c, d)
f = complex(float(a), float(b))
print (*"a is type"* , type(a))
print (*"b is type"* , type(b))
print (*"c is type"* , type(c))
print (*"d is type"* , type(d))
print (*"e is type"* , type(e))
print (*"f is type"* , type(f))
print(a + b)
print(d / c)
print (b / a)
print (b // a)
print (e)
print (e + f)
print (*"e's real part is: "* , e.real)
print (*"e's imaginary part is: "* , e.imag)
print (sys.float_info)
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
a is type <class 'int'>
b is type <class 'int'>
c is type <class 'float'>
d is type <class 'float'>
e is type <class 'complex'>
f is type <class 'complex'>
7
1.4134275618374559
1.3333333333333333
1
(5.66+8j)
(8.66+12j)
e's real part is: 5.66
e's imaginary part is: 8.0
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
Process finished with exit code 0
字符串(String)&变量 (Variable)
-
字符串:
一串字符
显示或者打印出来文字信息
导出
编码:# -- coding: utf-8 --
单引号,双引号,三引号
不可变(immutable)
Format字符串
age = 3
name = "Tom"
print("{0} was {1} years old".format(name, age))
联合:+: print(name + " was " + str(age) + " years old")
换行符: print("What's your name? \nTom") -
字面常量(literal constant):
可以直接以字面的意义使用它们:
如:6,2.24,3.45e-3, "This is a string"
常量:不会被改变
- 变量:
储存信息
属于identifier
identifier命名规则:
第一个字符必须是字母或者下划线
其余字符可以是字母,数字,或者下划线
区分大小写
如:合法:i, name_3_4, big_bang
不合法:2people, this is tom, my-name, >123b_c2
-
注释: #
-
缩进(Indentation)
数据结构:列表(List)
-
print中的编码:
编码:# -- coding: utf-8 -- -
print中的换行
print("What's your name? \nTom") -
List
创建
访问
更新
删除
脚本操作符
函数方法
# -*- coding: utf-8 -*-
#创建一个列表
number_list = [1, 3, 5, 7, 9]
string_list = ["abc", "bbc", "python"]
mixed_list = ['python', 'java', 3, 12]
#访问列表中的值
second_num = number_list[1]
third_string = string_list[2]
fourth_mix = mixed_list[3]
print("second_num: {0} third_string: {1} fourth_mix: {2}".format(second_num, third_string, fourth_mix))
#更新列表
print("number_list before: " + str(number_list))
number_list[1] = 30
print("number_list after: " + str(number_list))
#删除列表元素
print("mixed_list before delete: " + str(mixed_list))
del mixed_list[2]
print("mixed_list after delete: " + str(mixed_list))
#Python脚本语言
print(len([1,2,3])) #长度
print([1,2,3] + [4,5,6]) #组合
print(['Hello'] * 4) #重复
print(3 in [1,2,3]) #某元素是否在列表中
#列表的截取
abcd_list =['a', 'b', 'c', 'd']
print(abcd_list[1])
print(abcd_list[-2])
print(abcd_list[1:])
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
second_num: 3 third_string: python fourth_mix: 12
number_list before: [1, 3, 5, 7, 9]
number_list after: [1, 30, 5, 7, 9]
mixed_list before delete: ['python', 'java', 3, 12]
mixed_list after delete: ['python', 'java', 12]
3
[1, 2, 3, 4, 5, 6]
['Hello', 'Hello', 'Hello', 'Hello']
True
b
c
['b', 'c', 'd']
Process finished with exit code 0
列表操作包含以下函数:
1、cmp(list1, list2):比较两个列表的元素
2、len(list):列表元素个数
3、max(list):返回列表元素最大值
4、min(list):返回列表元素最小值
5、list(seq):将元组转换为列表
列表操作包含以下方法:
1、list.append(obj):在列表末尾添加新的对象
2、list.count(obj):统计某个元素在列表中出现的次数
3、list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4、list.index(obj):从列表中找出某个值第一个匹配项的索引位置
5、list.insert(index, obj):将对象插入列表
6、list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7、list.remove(obj):移除列表中某个值的第一个匹配项
8、list.reverse():反向列表中元素
9、list.sort([func]):对原列表进行排序
tuple(元组)
创建只有一个元素的tuple,需要用逗号结尾消除歧义
a_tuple = (2,)
tuple中的list
mixed_tuple = (1, 2, ['a', 'b'])
print("mixed_tuple: " + str(mixed_tuple))
mixed_tuple[2][0] = 'c'
mixed_tuple[2][1] = 'd'
print("mixed_tuple: " + str(mixed_tuple))
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
mixed_tuple: (1, 2, ['a', 'b'])
mixed_tuple: (1, 2, ['c', 'd'])
Process finished with exit code 0
Tuple 是不可变 list。 一旦创建了一个 tuple 就不能以任何方式改变它。
Tuple 与 list 的相同之处
定义 tuple 与定义 list 的方式相同, 除了整个元素集是用小括号包围的而不是方括号。
Tuple 的元素与 list 一样按定义的次序进行排序。 Tuples 的索引与 list 一样从 0 开始, 所以一个非空 tuple 的第一个元素总是 t[0]。
负数索引与 list 一样从 tuple 的尾部开始计数。
与 list 一样分片 (slice) 也可以使用。注意当分割一个 list 时, 会得到一个新的 list ;当分割一个 tuple 时, 会得到一个新的 tuple。
Tuple 不存在的方法
您不能向 tuple 增加元素。Tuple 没有 append 或 extend 方法。
您不能从 tuple 删除元素。Tuple 没有 remove 或 pop 方法。
然而, 您可以使用 in 来查看一个元素是否存在于 tuple 中。
用 Tuple 的好处
Tuple 比 list 操作速度快。如果您定义了一个值的常量集,并且唯一要用它做的是不断地遍历它,请使用 tuple 代替 list。
如果对不需要修改的数据进行 “写保护”,可以使代码更安全。使用 tuple 而不是 list 如同拥有一个隐含的 assert 语句,说明这一数据是常量。如果必须要改变这些值,则需要执行 tuple 到 list 的转换。
Tuple 与 list 的转换
Tuple 可以转换成 list,反之亦然。内置的 tuple 函数接收一个 list,并返回一个有着相同元素的 tuple。而 list 函数接收一个 tuple 返回一个 list。从效果上看,tuple 冻结一个 list,而 list 解冻一个 tuple。
Tuple 的其他应用
一次赋多值
v = ('a', 'b', 'e')
(x, y, z) = v
解释:v 是一个三元素的 tuple, 并且 (x, y, z) 是一个三变量的 tuple。将一个 tuple 赋值给另一个 tuple, 会按顺序将 v 的每个值赋值给每个变量。
字典 (Dictionary)
字典内置函数&方法( 键(key),对应值(value))
Python字典包含了以下内置函数:
1、cmp(dict1, dict2):比较两个字典元素。
2、len(dict):计算字典元素个数,即键的总数。
3、str(dict):输出字典可打印的字符串表示。
4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。
Python字典包含了以下内置方法:
1、radiansdict.clear():删除字典内所有元素
2、radiansdict.copy():返回一个字典的浅复制
3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4、radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false
6、radiansdict.items():以列表返回可遍历的(键, 值) 元组数组
7、radiansdict.keys():以列表返回一个字典所有的键
8、radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里
10、radiansdict.values():以列表返回字典中的所有值
# -*- coding: utf-8 -*-
#创建一个词典
phone_book = {'Tom': 123, "Jerry": 456, 'Kim': 789}
mixed_dict = {"Tom": 'boy', 11: 23.5}
#访问词典里的值
print("Tom's number is " + str(phone_book['Tom']))
print('Tom is a ' + mixed_dict['Tom'])
#修改词典
phone_book['Tom'] = 999
phone_book['Heath'] = 888
print("phone_book: " + str(phone_book))
phone_book.update({'Ling':159, 'Lili':247})
print("updated phone_book: " + str(phone_book))
#删除词典元素以及词典本身
del phone_book['Tom']
print("phone_book after deleting Tom: " + str(phone_book))
#清空词典
phone_book.clear()
print("after clear: " + str(phone_book))
#删除词典
del phone_book
# print("after del: " + str(phone_book))
#不允许同一个键出现两次
rep_test = {'Name': 'aa', 'age':5, 'Name': 'bb'}
print("rep_test: " + str(rep_test))
#键必须不可变,所以可以用数,字符串或者元组充当,列表不行
list_dict = {['Name']: 'John', 'Age':13}
list_dict = {('Name'): 'John', 'Age':13}
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Tom's number is 123
Tom is a boy
phone_book: {'Tom': 999, 'Jerry': 456, 'Kim': 789, 'Heath': 888}
updated phone_book: {'Tom': 999, 'Jerry': 456, 'Kim': 789, 'Heath': 888, 'Ling': 159, 'Lili': 247}
phone_book after deleting Tom: {'Jerry': 456, 'Kim': 789, 'Heath': 888, 'Ling': 159, 'Lili': 247}
after clear: {}
rep_test: {'Name': 'bb', 'age': 5}
Traceback (most recent call last):
File "D:/python/untitled1/note08.py", line 46, in <module>
list_dict = {['Name']: 'John', 'Age':13}
TypeError: unhashable type: 'list'
Process finished with exit code 1
函数
函数:程序中可重复使用的程序段
给一段程程序起一个名字,用这个名字来执行一段程序,反复使用 (调用函数)
用关键字 ‘def' 来定义,identifier(参数)
identifier
参数list
return statement
局部变量 vs 全局变量
# -*- coding: utf-8 -*-
#没有参数和返回的函数
def say_hi():
print(" hi!")
say_hi()
say_hi()
#有参数,无返回值
def print_sum_two(a, b):
c = a + b
print(c)
print_sum_two(3, 6)
def hello_some(str):
print("hello " + str + "!")
hello_some("China")
hello_some("Python")
#有参数,有返回值
def repeat_str(str, times):
repeated_strs = str * times
return repeated_strs
repeated_strings = repeat_str("Happy Birthday!", 4)
print(repeated_strings)
#全局变量与局部 变量
x = 60
def foo(x):
print("x is: " + str(x))
x = 3
print("change local x to " + str(x))
foo(x)
print('x is still', str(x))
x = 60
def foo():
global x
print("x is: " + str(x))
x = 3
print("change local x to " + str(x))
foo()
print('value of x is', str(x))
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
hi!
hi!
9
hello China!
hello Python!
Happy Birthday!Happy Birthday!Happy Birthday!Happy Birthday!
x is: 60
change local x to 3
x is still 60
x is: 60
change local x to 3
value of x is 3
Process finished with exit code 0
默认参数
关键字参数
VarArgs参数
# -*- coding: utf-8 -*-
# 默认参数
def repeat_str(s, times=1):
repeated_strs = s * times
return repeated_strs
repeated_strings = repeat_str("Happy Birthday!")
print(repeated_strings)
repeated_strings_2 = repeat_str("Happy Birthday!", 4)
print(repeated_strings_2)
# 不能在有默认参数后面跟随没有默认参数
# f(a, b =2)合法
# f(a = 2, b)非法
# 关键字参数: 调用函数时,选择性的传入部分参数
def func(a, b=4, c=8):
print('a is', a, 'and b is', b, 'and c is', c)
func(13, 17)
func(125, c=24)
func(c=40, a=80)
# VarArgs参数
def print_paras(fpara, *nums, **words):
print("fpara: " + str(fpara))
print("nums: " + str(nums))
print("words: " + str(words))
print_paras("hello", 1, 3, 5, 7, word="python", anohter_word="java")
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Happy Birthday!
Happy Birthday!Happy Birthday!Happy Birthday!Happy Birthday!
a is 13 and b is 17 and c is 8
a is 125 and b is 4 and c is 24
a is 80 and b is 4 and c is 40
fpara: hello
nums: (1, 3, 5, 7)
words: {'word': 'python', 'anohter_word': 'java'}
Process finished with exit code 0
控制流:if & for 语句
- if 语句
if condition:
do something
elif other_condition:
do something
- for 语句
# -*- coding: utf-8 -*-
#if statement example
number = 59
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that')
# You can do whatever you want in a block ...
else:
print('No, the number is a lower than that')
# you must have guessed > number to reach here
print('Done')
# This last statement is always executed,
# after the if statement is executed.
#the for loop example
for i in range(1, 10):
print(i)
else:
print('The for loop is over')
a_list = [1, 3, 5, 7, 9]
for i in a_list:
print(i)
a_tuple = (1, 3, 5, 7, 9)
for i in a_tuple:
print(i)
a_dict = {'Tom':'111', 'Jerry':'222', 'Cathy':'333'}
for ele in a_dict:
print(ele)
print(a_dict[ele])
for key, elem in a_dict.items():
print(key, elem)
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Enter an integer : 77
No, the number is a lower than that
Done
1
2
3
4
5
6
7
8
9
The for loop is over
1
3
5
7
9
1
3
5
7
9
Tom
111
Jerry
222
Cathy
333
Tom 111
Jerry 222
Cathy 333
Process finished with exit code 0
控制流:while & range语句
# -*- coding: utf-8 -*-
number = 59
guess_flag = False
while guess_flag == False:
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
guess_flag = True
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that, keep guessing')
# You can do whatever you want in a block ...
else:
print('No, the number is a lower than that, keep guessing')
# you must have guessed > number to reach here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
print('Done')
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Enter an integer : 66
No, the number is a lower than that, keep guessing
Enter an integer : 38
No, the number is higher than that, keep guessing
Enter an integer : 59
Bingo! you guessed it right.
(but you do not win any prizes!)
Done
Process finished with exit code 0
# -*- coding: utf-8 -*-
number = 59
num_chances = 3
print("you have only 3 chances to guess")
for i in range(1, num_chances + 1):
print("chance " + str(i))
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
break
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
# You can do whatever you want in a block ...
else:
print('No, the number is lower than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
# you must have guessed > number to reach here
print('Done')
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
you have only 3 chances to guess
chance 1
Enter an integer : 55
No, the number is higher than that, keep guessing, you have 2 chances left
chance 2
Enter an integer : 69
No, the number is lower than that, keep guessing, you have 1 chances left
chance 3
Enter an integer : 23
No, the number is higher than that, keep guessing, you have 0 chances left
Done
Process finished with exit code 0
控制流:break, continue & pass
1. break
2. continue
3. pass
number = 59
while True:
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
break
# New block ends here
if guess < number:
# Another block
print('No, the number is higher than that, keep guessing')
continue
# You can do whatever you want in a block ...
else:
print('No, the number is a lower than that, keep guessing')
continue
# you must have guessed > number to reach here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
print('Done')
a_list = [0, 1, 2]
print("using continue:")
for i in a_list:
if not i:
continue
print(i)
print("using pass:")
for i in a_list:
if not i:
pass
print(i)
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Enter an integer : 23
No, the number is higher than that, keep guessing
Enter an integer : 59
Bingo! you guessed it right.
(but you do not win any prizes!)
Done
using continue:
1
2
using pass:
0
1
2
Process finished with exit code 0
输入输出方式介绍(Output Format)
str_1 = input("Enter a string: ")
str_2 = input("Enter another string: ")
print("str_1 is: " + str_1 + ". str_2 is :" + str_2)
print("str_1 is {} + str_2 is {}".format(str_1, str_2))
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Enter a string: fanrunqi
Enter another string: rookie
str_1 is: fanrunqi. str_2 is :rookie
str_1 is fanrunqi + str_2 is rookie
Process finished with exit code 0
读写文件
1. 写出文件
2. 读入文件
some_sentences = '''\
I love learning python
because python is fun
and also easy to use
'''
#Open for 'w'irting
f = open('sentences.txt', 'w')
#Write text to File
f.write(some_sentences)
f.close()
#If not specifying mode, 'r'ead mode is default
f = open('sentences.txt')
while True:
line = f.readline()
#Zero length means End Of File
if len(line) == 0:
break
print(line)
# close the File
f.close
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
I love learning python
because python is fun
and also easy to use
Process finished with exit code 0
错误与异常处理(Error & Exceptions)
Python有两种错误类型:
1. 语法错误(Syntax Errors)
2. 异常(Exceptions)
首先,try语句下的(try和except之间的代码)被执行
如果没有出现异常,except语句将被忽略
如果try语句之间出现了异常,try之下异常之后的代码被忽略,直接跳跃到except语句
如果异常出现,但并不属于except中定义的异常类型,程序将执行外围一层的try语句,如果异常没有被处理,将产生unhandled exception的错误
处理异常(Handling Exceptions)
Exception doc: https://docs.python.org/3.4/library/exceptions.html
#Handling exceptions
while True:
try:
x = int(input("Please enter a number"))
break
except ValueError:
print("Not valid input, try again...")
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Please enter a numberfan
Not valid input, try again...
Please enter a numberrun
Not valid input, try again...
Please enter a numberqi
Not valid input, try again...
Please enter a number7
Process finished with exit code 0
面向对象编程(Object-Oriented)和装饰器(decorator)
1. 面向对象编程
Python支持面向对象编程
类(class):现实世界中一些事物的封装 (如:学生)
类:属性 (如:名字,成绩)
类对象
实例对象
引用:通过引用对类的属性和方法进行操作
实例化:创建一个类的具体实例对象 (如:学生张三)
2. 装饰器(decorator)
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def introduce(self):
print("hi! I'm " + self.name)
print("my grade is: " + str(self.grade))
def improve(self, amount):
self.grade = self.grade + amount
jim = Student("jim", 86)
jim.introduce()
jim.improve(10)
jim.introduce()
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
hi! I'm jim
my grade is: 86
hi! I'm jim
my grade is: 96
Process finished with exit code 0
def add_candles(cake_func):
def insert_candles():
return cake_func() + " candles"
return insert_candles
def make_cake():
return "cake"
gift_func = add_candles(make_cake)
print(make_cake())
print(gift_func())
def add_candles(cake_func):
def insert_candles():
return cake_func() + " candles"
return insert_candles
def make_cake():
return "cake"
make_cake = add_candles(make_cake)
print(make_cake())
# print(gift_func)
def add_candles(cake_func):
def insert_candles():
return cake_func() + " and candles"
return insert_candles
@add_candles
def make_cake():
return "cake"
# make_cake = add_candles(make_cake)
print(make_cake())
# print(gift_func)
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
cake
cake candles
cake candles
cake and candles
Process finished with exit code 0
图形界面(GUI)
1. GUI: Graphical User Interface
2. tkinter: GUI library for Python
3. GUI Example
# -*- coding: utf-8 -*-
from tkinter import *
import tkinter.simpledialog as dl
import tkinter.messagebox as mb
# tkinter GUI Input Output Example
# 设置GUI
root = Tk()
w = Label(root, text="Label Title")
w.pack()
# 欢迎消息
mb.showinfo("Welcome", "Welcome Message")
guess = dl.askinteger("Number", "Enter a number")
output = 'This is output message'
mb.showinfo("Output: ", output)
猜数字游戏
# -*- coding: utf-8 -*-
from tkinter import *
import tkinter.simpledialog as dl
import tkinter.messagebox as mb
root = Tk()
w = Label(root, text = "Guess Number Game")
w.pack()
#欢迎消息
mb.showinfo("Welcome", "Welcome to Guess Number Game")
#处理信息
number = 59
while True:
#让用户输入信息
guess = dl.askinteger("Number", "What's your guess?")
if guess == number:
# New block starts here
output = 'Bingo! you guessed it right, but you do not win any prizes!'
mb.showinfo("Hint: ", output)
break
# New block ends here
elif guess < number:
output = 'No, the number is a higer than that'
mb.showinfo("Hint: ", output)
else:
output = 'No, the number is a lower than that'
mb.showinfo("Hint: ", output)
print('Done')
网友评论