之前都是随用随学,想着系统学习一下python,就阅读了下《Python趣味编程入门》,都是些基础,但是也感觉还不错,一下是自己做的一些笔记。
print("Hello World")
name = "kevin"
print("Hello", name)
username = input("Enter your name: ")
print("Welcome", username)
first = input("Enter first number: ")
second = input("Enter second number: ")
a = int(first) # 将first的字符串转化为数字
b = int(second)
print(a+b)
a = int(input("Enter first num: "))
b = int(input("Enter second num: "))
print("the sum is ", a + b)
1.变量名有什么限制?
必须要以字母开头,不能使用现有的函数或者关键字的名称
2.如果变量"a"是包含"123"的字符串,如何将其转换成数字并保存在变量"b"中?
b = int(a)
3.什么是浮点数?
带有小数点的数,比如1.234
4."a=a+5"的简写方式是什么?
a += 5
5.Python如何解读"10 + 5 * 3"?
5乘以3,然后在结果上加上10
a = 2
name = "bob"
if a == 2:
print("a is 2")
if name == "bob":
print("and name is bob")
print("Program ended")
if a > 5:
if a < 5:
if a == 5:
if a != 5:
a = 2
name = "Bob"
if a == 2 and name == "Bob":
print("a is 2")
print("And name is Bob")
a = 900
name = "Bob"
if a == 2 or name == "Bob":
print("a is 2")
print("And name is Bob")
score = int(input("please input your score: "))
if score >= 60:
grade = "A"
elif score >= 50:
grade = "B"
else:
grade = "C"
print("grade: ", grade)
name = "Bob"
print(name.lower()) # name.lower()方法是把“Bob”全部转化为小写字母
a = 1
while a <= 10:
print("a is ", a)
a += 1
myList = [1, 2, 10, 100] # 列表用方括号表示,里面的数字为列表项
for a in myList:
print("a is ", a)
"""
range(1, 10)
从1开始到9结束,当a等于10时,循环立即结束
"""
for a in range(1, 10):
print("a is ", a)
"""
range(1, 10, 3)
从1开始到9结束,3是每次循环的增量
"""
for a in range(1, 10, 3):
print("a is ", a)
这个挑战太简单了,就不写了 哈哈
注意:函数命名时候,不能以数字开头,不能包含标点符号,以及不能和现有的Python关键字或者函数同名。
def say_hello():
print("hello")
def count_to_10():
for i in range(1, 11):
print(i)
say_hello()
count_to_10()
say_hello()
def add_numbers(x, y):
print(x, "+", y, "=", x + y)
def do_greeting(name="Tiger"): #默认为tiger
print("Hello", name)
your_name = input("Enter name ")
do_greeting(your_name)
a = int(input("Enter the first number "))
b = int(input("Enter the second number "))
add_numbers(a, b)
def add_numbers(x, y):
return x + y
a = int(input("Enter the number: "))
b = int(input("Enter another: "))
ans = add_numbers(a, b)
print("Sum is ", ans)
pow(a, b) #以a为底的b次幂
a = pow(2, 10)
print(a)
round()
round(x) #默认取整
round(x, n) #取x的前n位小数
a = 6.55554
print(round(a))
print(round(a, 4))
简单来说,就是存储数据的结构。
my_string = "Hello"
print(my_string[0]) # 只显示字符串中的元素H
元组虽然很牛逼,但是初始化后,其内容就不能改变。
元组和列表可以将不同的数据组合到单一名称下
元组,是一种结构,可以将多个数据组合在单一的名称下。创建元组,需要将数据放在括号中,数据之间用逗号隔开。里面的数据可以是不同数据类型的。
my_tuple = (1, "hello", 2)
print(my_tuple[0])
print(my_tuple[1])
days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
x = int(input("Enter a day number: "))
print(days[x-1])
切片是有特定起始位置的一组元素
来一波切片的例子:
>>> m[:10]#取前十个数
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> m[-10:]#取后十个数
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> m[10:20]#取前11-20个数
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> m[:10:2]#前十个数中,每2个数取一个
[0, 2, 4, 6, 8]
>>> m[5:15:3]#第6-15个数中,每3个数取一个
[5, 8, 11, 14]
>>> m[::10]#所有的数中,每10个数取一个
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> m[:]#什么都不写,可以原样复制一个list
[0, 1, 2, 3, 4, 5, 6, 7,……,99]
# 打印前三个元素
my_tuple = (1, 2, 3, 4, 5)
for x in my_tuple[0:3]:
print(x)
# 其实my_tuple[0:3]可以直接写成my_tuple[:3]或者my_tuple[:-2]
# 打印元组后三个元素
my_tuple = (1, 2, 3, 4, 5)
for x in my_tuple[-3:]:
print(x)
# 每次循环跳过2个元素,打印结果为1,3,5
my_tuple = (1, 2, 3, 4, 5)
for x in my_tuple[::2]:
print(x)
# 小例子:利用切片实现trim(str)功能(类似于python中的strip()函数),即实现去除字符串前后的空格
def trim(str):
while str[:1] == ' ':
str = str[1:]
while str[-1:] == ' ':
str = str[:-2]
return str
s = trim(" hello ")
print(s)
print(len(s))
列表和元素很像,列表用方括号定义,而元组用圆括号。
# 利用切片打印列表的后三个元素
my_list = [1, 2, 3, 4, 5]
for x in my_list[-3:]:
print(x)
# 列表中的列表
my_list = [[1, 2, 3], ["Bob", "Bill"]]
print(my_list[1][0])
print(my_list[0][2])
for x in my_list[0]:
print(x)
# 实时改变元素 enumerate
my_list = [20, 60, 500, 1200, 9000]
for index, x in enumerate(my_list):
my_list[index] = x * 2
print(my_list)
# 或者这样也行
for index in enumerate(my_list):
my_list[index[0]] = index[1] * 2
print(my_list)
# 排序 key=str.lower, reverse=True 小写字母 倒序
my_list = [1, 5, 2, 4, 3]
my_list.sort()
print(my_list)
# 排序的时候大写字母优先,所以可以把所有字母先都转为小写字母再进行排序
my_list = ["My", "name", "is", "Bill"]
my_list.sort()
print(my_list)
# key=str.lower
my_list.sort(key=str.lower)
print(my_list)
my_list.sort(key=str.lower, reverse=True)
print(my_list)
# 添加元素
my_list = [20, 60, 500, 1200, 9000]
my_list.append(10)
print(my_list)
# 插入元素
my_list = [20, 60, 500, 1200, 9000]
# 位置-在这个位置前插入 要插入的元素
my_list.insert(0, 10)
print(my_list)
# 删除元素 根据内容删除用remove(x) 根据索引删除用 pop(index)
my_list = [20, 60, 500, 1200, 9000, 500]
my_list.remove(500)
print(my_list)
# 如果列表中有多个重复的,它会默认删掉第一个, 要想都删掉可以这样
my_list = [20, 60, 500, 1200, 9000, 500, 500]
for x in range(0, my_list.count(500)):
my_list.remove(500)
print(my_list)
print(my_list.pop(2))
print(my_list)
my_list = [10, 20, 60, 500, 1200, 9000]
print(my_list)
x = int(input("Enter the num: "))
y = my_list.pop(x)
print("It contained ", y)
用大括号创建字典,在括号中,放入“键”和“值”的配对,两者用冒号连接在一起。键是我们用于引用字典中元素的名称,值则是它们的数据
注意:键名必须是唯一的
# 创建 修改 添加 删除
# 创建
employees = {"Bob": 1234, "Steve": 5678, "Mike": 9012}
print(employees["Bob"])
# 修改
employees["Bob"] = 777
print(employees["Bob"])
# 添加
employees["Stable"] = 321
print(employees)
# 删除
del employees["Bob"]
print(employees)
employees = {"Bob": 1234, "Steve": 5678, "Mike": 9012}
text = ""
while text != "q":
text = input("Enter a name or 'q' to quit: ")
if text == "q":
break
if text in employees:
print(employees[text])
else:
print("Not Found")
def load_data(filename):
print("XXX NOT IMPLEMENTED")
def save_data(filename):
print("XXX NOT IMPLEMENTED")
employees = {"Bob": 1234, "Steve": 5678, "Mike": 9012}
text = ""
while text != "q":
print("\n---Employee Dictionary Tool 1.0---")
print("Enter 'f' to find, 'a' to add, 'd' to delete")
print("'l' to load, 's' to save, 'q' to quit")
text = input("Your option: ")
if text == "q":
break
elif text == "f":
text = input("Enter name: ")
if text in employees:
print(employees[text])
else:
print("Not Found")
elif text == 'a':
text == input("Enter new name: ")
value = int(input("Enter num: "))
employees[text] = value
print(text, "add successful")
elif text == 'd':
text = input("Enter name: ")
if text in employees:
del employees[text]
print(text, "deleted successful")
else:
print(text, "is Not Found")
elif text == 'l':
text = input("Enter filename: ")
load_data(text)
print("file loaded")
elif text == 's':
text = input("Enter filename: ")
save_data(text)
print("file saved")
else:
print("unvalid order, please input again")
函数,返回多个值,可以直接返回列表
def my_func2():
return 10, 200, 360
def my_func():
return [10, 200, 360]
my_list = my_func()
print(my_list)
函数,传参穿多个参数,需要加上*
‘*’可以表示乘法,任意函数参数 和 元组/列表的拆解
# 在numbers前面加了一个*,就将numbers变成了一个元组,传递给参数的所有数值(不论有多少个),都被放到这个元组中
def average(*numbers):
result = sum(numbers) / len(numbers)
return result
print(average(1, 2, 3))
def average(*numbers):
result = sum(numbers) / len(numbers)
return result
my_tuple = (1, 2, 3)
print(average(*my_tuple))
my_list = (5, 6, 7)
print(average(*my_list))
1.如果字符串变量“mystring”包含“Hello”,如何引用包含字母“o”的元素?
mystring[4] 或者 mystring[-1]
2.元组和列表之间有何不同?
元组使用圆括号,元组内元素不可改变;列表使用方括号,列表内元素可以改变。
3.如果“mylist”是一个姓名列表,你希望对它进行大小写不敏感的排序,如何实现?
key=str.lower
4.如果你有一个名为“employees”的字典,如何删除键为“Bob”的元素?
if “Bob” in employees:
del employees[“Bob”]
5.如何定义一个“summary”函数,使它可以调用“data”中任意个数的元素?
def summary(*data)
# r读 w写 a续写
# 需要手动关闭文件
filename = "C:/Users/Administrator/Desktop/data.txt"
file = open(filename, "w")
file.write("hello world")
file.close()
try:
my_file = open("C:/Users/Administrator/Desktop/data.txt", "w")
except OSError as err:
print(err)
print("Moving on...")
# 不需要手动关闭文件
with open(filename, "w") as my_file:
my_file.write("Hello, world!\n")
my_file.write("We're learning coding.\n")
print("Program running")
try except 可以优雅的处理错误
try:
filename = "C:/Users/Administrator/Desktop/data.txt"
my_file = open(filename, "r")
# 读取文件的每一行 end=""不添加换行符
for text_line in my_file:
print(text_line, end="")
print("file opened")
my_file.close()
except OSError as err:
print("file couldn't be opened")
print(err)
# 或者
try:
filename = "C:/Users/Administrator/Desktop/data.txt"
with open(filename, "r") as my_file:
for text_line in my_file:
print(text_line, end="")
except OSError as err:
print("file couldn't be opened")
print(err)
read()方法可以读取文件的所有数据,并且放到text_data中。读取的是原始数据,包括换行符和其他常规文本汇总不可见的符号。一旦python读取文件后,它会自动关闭文件,不需要重复这一工作。
readlines()方法也可以,只不过返回的是一个列表,text_list是一个包含文件所有行的列表,text_list[0]包含第一行,text_list[1]包含第二行,以此类推。
filename = "C:/Users/Administrator/Desktop/data.txt"
text_data = open(filename, "r").read()
print(text_data)
text_list = open(filename, "r").readlines()
for text_line in text_list:
print(text_line, end="")
# 创建空白字典
employees = {}
try:
filename = "C:/Users/Administrator/Desktop/employees.txt"
my_file = open(filename, "r")
# 遍历文件每一行
for text_line in my_file:
my_list = text_line.split(",")
# rstrip()方法 删除该字符串后面多余的数据比如 换行符 空格等
employees[my_list[0]] = int(my_list[1].rstrip())
my_file.close()
print(employees)
except OSError as err:
print(err)
如果以纯文本格式打印“image.dat”的内容,只会看到毫无意义的数据和古怪的字符,因为这种文件不是以纯文本方式处理的。
# rb 以二进制模式读取文件
filename = "C:/Users/Administrator/Desktop/image.dat"
my_data = open(filename, "rb").read()
# 循环读取每一个字节 end=" " 打印每个字节的值(后面加上一个空格)
for x in my_data:
print(x, end=" ")
filename = "C:/Users/Administrator/Desktop/image.dat"
with open(filename, "rb") as my_file:
# 从文件中读取一个字节
byte = my_file.read(1)
# 如果是一个空字节,说明已到文件末尾 “b”是确认我们处理的是一个字节
while byte != b"":
# ord()以人类可读的方式打印包含在字节内的数值
print(ord(byte), end=" ")
byte = my_file.read(1)
import sys
# 从命令行获取文件名
# sys.argv 包含用户运行程序在命令行输入的一个参数列表
# sys.argv[0]是程序本身的名称,也就是“book.py” 更多的参数会依次保存在后面
if len(sys.argv) == 1:
print("No filename specified")
sys.exit(1)
try:
my_file = open(sys.argv[1], "r").read()
print(my_file)
except OSError as err:
print("File couldn't be opened")
print(err)
try:
filename = "C:/Users/Administrator/Desktop/data.txt"
# 将数据读入一个列表
my_list = open(filename, "r").readlines()
for counter, line in enumerate(my_list):
# line.lower.find()可以在查找的时候忽略大小写
loc = line.find("moon")
# 若location不等于-1,则表明已经找到该字符串
if loc != -1:
print("Found on line", counter+1, "position", loc)
except OSError as err:
print("File couldn't opened")
print(err)
try:
filename = "C:/Users/Administrator/Desktop/image.dat"
num = int(input("Enter a number to find in image.dat: "))
offset = int(input("Enter an offset to search from: "))
with open(filename, "rb") as my_file:
# seek可以更改文件中的当前位置
my_file.seek(offset)
# 使用read()函数后,python将更新自己内部的文件位置计数器,tell()函数可以返回位置
# 因为read递增文件位置,所以文件的当前位置在该数值之后,所以结果减去1才是数字的正确位置
byte = my_file.read(1)
while byte != b"":
if ord(byte) == num:
# 返回文件中的当前位置
print(num, "found at position", my_file.tell()-1)
byte = my_file.read(1)
except OSError as error:
print("File couldn't opened")
print(error)
在二进制文件中,如果每次读取一个字节,大小范围是0~255,如果想查找更大的数就需要每次读取两个字节。
try:
filename = "C:/Users/Administrator/Desktop/image.dat"
num = int(input("Enter a number to find in image.dat: "))
with open(filename, "rb") as my_file:
bytes = my_file.read(2)
while bytes != b"":
# 把两个字节合成一个整数, 将字节生成整数时,将字节顺序设置为little
if int.from_bytes(bytes, byteorder="little") == num:
# 返回文件中的当前位置 因为read(2)在返回数据之后将位置向后移动了两个字节,
# 所以减去2才能得到数据的原始位置
print(num, "found at position", my_file.tell()-2)
bytes = my_file.read(2)
except OSError as error:
print("File couldn't opened")
print(error)
如果想把python数据快速保存到磁盘,方便以后的读取,可以对数据进行“腌制”(Pickling)。就是它不能在常规文本编辑器中编辑“腌制”过得python数据,使用(读取)起来很方便。
# 在python中增加“腌制”功能
import pickle
employees = {"Bob": 1234, "Steve": 5678, "Mike": 9012}
try:
# 以二进制方式写入数据
with open("employees.p", "wb") as my_file:
# 在文件中创建字典
pickle.dump(employees, my_file)
except OSError as err:
print("File couldn't open")
print(err)
try:
with open("employees.p", "rb") as my_file:
# 从文件中获取数据
employees = pickle.load(my_file)
print(employees)
except OSError as err:
print("File couldn't open")
print(err)
import json
employees = {"Bob": 1234, "Steve": 5678, "Mike": 9012}
try:
# 以纯文本的方式写入数据
with open("employees.json", "w") as my_file:
json.dump(employees, my_file)
print(json.dumps(employees, indent=4))
except OSError as err:
print(err)
try:
# 以纯文本的方式写入数据
with open("employees.json", "r") as my_file:
employees = json.load(my_file)
print(json.dumps(employees, indent=4))
except OSError as err:
print(err)
import json
try:
with open("data.json", "r") as my_file:
goods = json.load(my_file)
id_to_find = int(input("Enter an item ID: "))
# 列表推导 即用一个列表生成另一个列表 reslut中的每个元素都是一个商品的所有信息
result = [my_item for my_item in goods if my_item["id"] == id_to_find]
if len(result) > 0:
# 因为result是包含单个字典的列表,所以要用result[0]
print("Name: ", result[0]["name"])
print("Price: ", result[0]["price"])
print("Games:", end=" ")
for game in result[0]["games"]:
print(game, end=" ")
print("")
else:
print("Not Found")
except OSError as err:
print(err
1.python中用哪一个字符序列表示换行符?
\n
2.当打开文件、以二进制模式写入时用什么代码?
open(filename, “rb”)
3.从文件读取二进制字节时,用哪个命令切换到文件中特定位置?
file.seek(offset)
4.当两个字节组合成一个字时,这时候值得范围是?
0~65535
5.如果用户在运行程序时输入一个文件名参数,如何用代码访问它?
import sys
sys.argv[1]
简单来说,模块就是保存在单独文件中的一段python代码。
模块需要导入才能用,python默认情况下是内存友好的,如果每次运行都需要加载所有模块,那么占据的内存就大的多。
导入模块,可以用import sys 或者按名称导入特定功能。如果按照名称导入特定功能,在使用这些函数时候不需要再“sys.”前缀,在某些情况下很实用。
from sys import argv, exit
if len(argv) == 1:
print("No filename specified!")
exit(1)
from sys import platform, version_info, exit
# version_info 包含如下信息的一个元组(主版本号、此版本号、小版本(修订)号、发行级别)
# 发行级别是一个字符串,内容为 alpha beta candidate 或者 final,前三个表示开发人员仍未完成的Python版本 所以如果想保证
# 在稳定的版本下运行,可以查看最后两行
print("Running on: ", platform)
# win32 表示Windows(即使是使用64位版本的Windows)、 linux表示Linux、darwin表示MacOS
print("Python version: ", end=" ")
# sep="."表示用点分隔版本号
print(version_info[0], version_info[1], version_info[2], sep=".")
if version_info[3] != "final":
print(version_info[3])
print("Error: please use a released version of Python")
exit(1)
“OS”模块是Python与操作系统的接口。通过该模块,可以让操作系统完成一些任务。但是,当我们想清除屏幕,这个指令在不同的系统下命令也不同,所以应该事先判断下是哪个系统。
当然, 自己也可以创建一个模块,方便代码复用,比如创建一个“mymodule.py”文件,在别的地方使用里面的函数或者变量的时候,直接import mymodule.py即可。
import sys
import os
if sys.platform == "win32":
os.system("cls")
else:
os.system("clear")
print("Done")
import os
width, height = os.get_terminal_size()
print("Window width: ", width)
print("Window height: ", height)
# %H小时 %M分钟 %S秒 %B月份名称 %m月份序号 %A周名称
my_time = time.strftime("%H:%M:%S")
hour = int(time.strftime("%H"))
print(my_time)
print(hour)
import math
radius = int(input("Enter circle radius: "))
# radius**2 求幂运算 2是舍入到小数点后两位
print("Area is", round((radius**2)*math.pi, 2))
随机数的典型应用之一是在生成某个数值时执行特定的操作。
import random
# 初始化Python随机数生成器
random.seed()
for x in range(1, 21):
print("Move", x, end="")
# randint可以用randrange()替换,其中有三个参数 一个开始值,一个结束值,一个是可能结果之间的的差值
my_random = random.randint(1, 5)
# 由于生成随机数的范围是1到5,所以生成1的概率是20%
if my_random == 1:
print(" - moving down")
else:
print(" - staying still")
print("100 random numbers between 1 and 10: ")
for x in range(0, 100):
# 产生1到10之间的随机数
print(random.randint(1, 10), end=" ")
import socket
# 准备一个网络套接字连接
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到NetBSD Web服务计算机的80端口
# 之所以用两重括号,是因为connect函数期待得到的参数是一个元组
my_socket.connect(("www.netbsd.org", 80))
# 发送主页请求
my_socket.send(b"GET/HTTP/1.0\n\n")
# 从服务器接受1024字节个数据
res = my_socket.recv(1024)
while res != b"":
print(res)
# 不断从网站接收和打印数据,直到没有更多数据传送为止
res = my_socket.recv(1024)
# 打印一张图像的原始信息
from PIL import Image
orig_pic = Image.open("image.png")
print("Format: ", orig_pic.format)
print("Width: ", orig_pic.size[0])
print("Height: ", orig_pic.size[1])
# 导入加载图像和添加图像滤镜的例程
from PIL import Image, ImageFilter
import sys
# 初始化缩略图的大小
thumbnail_size = (50, 50)
filename = input("Enter an image file: ")
# 尝试打开文件,如果失败则显示错误信息
try:
orig_pic = Image.open(filename)
print("Format: ", orig_pic.format)
print("Width: ", orig_pic.size[0])
print("Height: ", orig_pic.size[1])
except OSError as err:
print(err)
exit(1)
print("Progressing...")
# 在“blurred_pic”中制作一份“orig_pic”数据的拷贝,添加一个滤镜
blurred_pic = orig_pic.filter(ImageFilter.BLUR)
# 将数据缩小
blurred_pic.thumbnail(thumbnail_size)
# 把数据保存到扩展名为“.jpeg”的文件中
new_filename = filename.split(".")[0]
blurred_pic.save(new_filename + ".jpeg")
print("Format: ", blurred_pic.format)
print("Width: ", blurred_pic.size[0])
print("Height: ", blurred_pic.size[1])
import pygame
# 启动Pygame
pygame.init()
# 创建新的游戏屏幕,分辨率由一个新的元组指定
screen = pygame.display.set_mode((640, 480))
# 用RGB格式的颜色元组填充到屏幕 (红,绿,蓝)
screen.fill((0, 255, 0))
# 将所有颜色变化渲染到屏幕上
pygame.display.flip()
# 延时3秒
pygame.time.wait(3000)
import pygame
import sys
# 启动Pygame
pygame.init()
# 创建游戏屏幕,分辨率由一个新的元组指定
screen = pygame.display.set_mode((640, 480))
# 从文件加载图像,保存在“ball”对象中
ball = pygame.image.load("ball.bmp")
# 球的初始位置X和Y
ball_x = 100
ball_y = 100
# 每次循环中球的位置的增加量
ball_x_speed = 7
ball_y_speed = 7
while 1:
for event in pygame.event.get():
# 检查操作系统事件,如果窗口关闭则退出
if event.type == pygame.QUIT:
sys.exit(1)
ball_x += ball_x_speed
ball_y += ball_y_speed
# 边界条件
if ball_x > 610:
ball_x_speed = -7
if ball_y > 450:
ball_y_speed = -7
if ball_x < 0:
ball_x_speed = 7
if ball_y < 0:
ball_y_speed = 7
# 用RGB格式的颜色元组填充屏幕
screen.fill((90, 230, 90))
# 在指定的X和Y坐标处绘制球
screen.blit(ball, (ball_x, ball_y))
# 将所有变化渲染到画布上
pygame.display.flip()
# 延时10毫秒
pygame.time.wait(10)
from tkinter import *
# 创建主窗口
root_win = Tk()
# 创建新的文本标签
my_label = Label(root_win, text="Shiny GUI app!")
# 将标签放到窗口内
my_label.pack()
# 创建窗口大小
root_win.geometry("200x100")
# 运行程序,处理事件
root_win.mainloop()
import math
from tkinter import *
# 点击计算按钮时,运行该函数
def calc_area(*args):
area_result = (float(radius.get()) ** 2) * math.pi
# 保留小数点后两位
area.set(round(area_result, 2))
root_win = Tk()
# 设置标题
root_win.title("Area calculator")
# 设置窗口大小
root_win.geometry("200x100")
# 创建Tkinter字符串变量 记录半径和面积
radius = StringVar()
radius.set("0")
area = StringVar()
area_label = Label(root_win, text="Area: ").grid(column=1, row=1)
area_value = Label(root_win, textvariable=area).grid(column=2, row=1)
radius_label = Label(root_win, text="Radius: ").grid(column=1, row=2)
radius_value = Entry(root_win, width=7, textvariable=radius).grid(column=2, row=2)
calc_button = Button(root_win, text="Calculate", command=calc_area).grid(column=2, row=3)
root_win.mainloop()
1.Python程序如何确定运行的操作系统?
sys.platform
导入sys模块,并检查“sys.platform”,“Windows”为“win32”,Linux为“Linux”,MacOS为“darwin”。
2.如何让操作系统运行“test.exe”?
导入os模块,并执行os.system(“test.exe”)
3.如何产生20~90之间的随机数?
random.randint(20, 90)
4.使用Python时,我们在绘图操作之后必须做什么,才能始终确保结果显示在屏幕上?
pygame.display.flip()
5.如何制作自己的模块?
将变量和函数定义放在单独的文件(如“mymodule.py”)中,然后再主代码文件中使用“import mymodule”
类很像是一个函数,但是必须创建包含类中数据的对象,才能使用它们。
# 类定义
class Myclass:
# 类函数(方法)
def say_hello(self):
print("Hello")
# 对象
x = Myclass()
x.say_hello()
# 另一个对象
y = Myclass()
y.say_hello()
self用于引用对象自己的变量拷贝
class Employee:
# 这个方法在函数创建时,自动运行
def __init__(self, passed_name, passed_number):
self.name = passed_name
self.number = passed_number
def show(self):
print("Name: ", self.name)
print("Number: ", self.number)
first = Employee("Bob", 1234)
second = Employee("Steve", 5678)
first.name = "Stable"
first.number = 777
first.show()
second.show()
类变量—所有实例共有
class Employee:
employee_count = 0
def __init__(self, passed_name, passed_number):
self.name = passed_name
self.number = passed_number
Employee.employee_count += 1
def show(self):
print("Name: ", self.name)
print("Number: ", self.number)
first = Employee("Bob", 1234)
second = Employee("Steve", 5678)
print(Employee.employee_count)
可以通过first.number=9000这样来赋值,但是有时候如果类能够在为属性赋值之前进行一些检查,就会更实用。
class Myclass:
def __init__(self, num_passed):
self.number = num_passed
# 程序获取number时候调用的方法
@property
def number(self):
print("Getting number...")
# self.__num 私有变量,在类内部使用
return self.__number
# 程序设置number的时候调用的方法
@number.setter
def number(self, num_passed):
print("Setting number...")
if num_passed > 1000:
self.__number = 1000
else:
self.__number = num_passed
first = Myclass(123)
print(first.number)
first.number = 9000
print(first.number)
import pygame
import sys
class Ball:
# 设置小球的初始位置、速度和图像
def __init__(self, x, y):
self.ball_x = x
self.ball_y = y
self.ball_x_speed = 7
self.ball_y_speed = 7
self.ball_pic = pygame.image.load("ball.bmp")
def update(self):
self.ball_x += self.ball_x_speed
self.ball_y += self.ball_y_speed
if self.ball_x > 610: self.ball_x_speed = -7
if self.ball_y > 450: self.ball_y_speed = -7
if self.ball_x < 0: self.ball_x_speed = 7
if self.ball_y < 0: self.ball_y_speed = 7
# 在屏幕上绘制小球
def render(self):
screen.blit(self.ball_pic, (self.ball_x, self.ball_y))
pygame.init()
screen = pygame.display.set_mode((640, 480))
ball1 = Ball(10, 10)
ball2 = Ball(100, 150)
ball3 = Ball(70, 30)
ball4 = Ball(350, 200)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(1)
screen.fill((90, 230, 90))
ball1.update()
ball1.render()
ball2.update()
ball2.render()
ball3.update()
ball3.render()
ball4.update()
ball4.render()
pygame.display.flip()
pygame.time.wait(1)
class Vehicle:
def __init__(self, x, y):
self.x_pos = x
self.y_pos = y
self.x_speed = 0
self.y_speed = 0
def update(self):
print("Moving...")
self.x_pos += self.x_speed
self.y_pos += self.y_speed
def render(self):
print("Drawing")
# 从“Vehicle”类继承方法和属性
class Digger(Vehicle):
def __init__(self, x, y):
Vehicle.__init__(self, x, y)
def dig(self):
print("Digging...")
class Helicopter(Vehicle):
def __init__(self, x, y, height):
Vehicle.__init__(self, x, y)
self.z_pos = height
car = Vehicle(10, 20)
car.update()
car.render()
digger = Digger(30, 40)
digger.dig()
chopper = Helicopter(50, 60, 70)
chopper.update()
通常,在创建对象时,可以在程序中添加额外的属性,即使这些属性定义不在类定义中。
class Myclass:
def __init__(self, passed_number):
self.number = passed_number
x = Myclass(10)
print(x.number)
x.name = "Steven"
print(x.name)
#
print(x.__dict__)
对于许多程序,能够实时创建新属性是一种优势。但是这也有一些缺点:属性保持在一个字典中,需要花时间处理,内存的利用也不是很有效。这种对象特有的词典被称为_dict__
两边各有两个下划线。
为了改进性能,节约内存,我们可以告诉Python不要使用字典保存示例属性,并且可以指定允许创建哪些属性。通过“槽”可以实现。
class Myclass(object):
# 指定允许创建的属性
__slots__ = {"number", "name"}
def __init__(self, passed_number):
self.number = passed_number
x = Myclass(10)
print(x.number)
x.name = "Steven"
print(x.name)
1.如何调用类定义中的函数?
一个方法
2.如何快速分清函数调用和创建类的新实例?
一般来说,类名首字母大写。
3.__init__
方法有何特别之处?
实例化对象的时候自动调用
4.什么是赋值方法?
在进行赋值或者更改时,会自动调用
5.什么是“类变量”?
类变量是多有实例能共享的变量
import pygame
import sys
import random
# 启动pygame
pygame.init()
# 设计游戏屏幕,分辨率由一个元组组成
screen = pygame.display.set_mode((640, 480))
# 设置一种新字体
font = pygame.font.Font(None, 36)
score = 0
# 从文件中加载图像,保存在“ball”对象中
ball = pygame.image.load("ball.bmp")
# 从文件中加载图像,保存在“ball”对象中
bat = pygame.image.load("bat.bmp")
bat_x = 260
bat_y = 430
# 小球的初始坐标X Y 及其速度
ball_x = 10
ball_y = 10
ball_x_speed = 7
ball_y_speed = 7
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(1)
score += 1
# 检测左右光标键是否按下
# 对应地移动球拍
pressed = pygame.key.get_pressed()
if pressed[pygame.K_RIGHT] and bat_x < 512:
bat_x += 15
if pressed[pygame.K_LEFT] and bat_x > 0:
bat_x -= 15
ball_x += ball_x_speed
ball_y += ball_y_speed
# 碰撞检测代码
if ball_x > bat_x and ball_x < bat_x + 112 and ball_y > 400:
ball_y_speed = -(random.randint(5, 15))
if ball_x > 610:
ball_x_speed = -random.randint(5, 15)
if ball_y > 450:
break
if ball_x < 0:
ball_x_speed = random.randint(5, 15)
if ball_y < 0:
ball_y_speed = random.randint(5, 15)
# 用RGB格式的颜色元组填充到屏幕
screen.fill((90, 230, 90))
# 生成并呈现分数文本
scoretext = font.render("Score: " + str(score), 1, (30, 30, 30))
screen.blit(scoretext, (10, 10))
# 绘制小球
screen.blit(ball, (ball_x, ball_y))
# 绘制挡板
screen.blit(bat, (bat_x, bat_y))
# 刷新屏幕
pygame.display.flip()
# 延时
pygame.time.wait(20)
print("Your score is : ", score)
import sys
import os
import dill as pickle
class Employee(object):
def __init__(self, passed_name, passed_number, passed_comment):
self.name = passed_name
self.number = passed_number
self.comment = passed_comment
def find(self, search_term):
if self.name.lower().find(search_term.lower()) != -1:
return 1
elif self.number.lower().find(search_term.lower()) != -1:
return 1
elif self.comment.lower().find(search_term.lower()) != -1:
return 1
else:
return 0
def show(self):
print("Name: ", self.name)
print("Number: ", self.number)
print("Comment: ", self.comment)
def load_data(filename):
try:
global employees
file_data = open(filename, "rb")
employees = pickle.load(file_data)
input("\nData loaded - hit enter to continue...\n")
file_data.close()
except OSError as err:
print(err)
sys.exit(1)
def save_data(filename):
try:
global employees
file_data = open(filename, "wb")
pickle.dump(employees, file_data)
file_data.close()
input("\nData loaded - hit enter to continue...\n")
except OSError as err:
print(err)
sys.exit(1)
employees = []
choice = 0
# if len(sys.argv) == 1:
# print("No filename specified - starting with empty data")
# input("Hit enter to continue...")
# else:
# load_data(sys.argv[1])
while choice != 6:
if sys.platform == "win32":
os.system("cls")
else:
os.system("clear")
print("\n=====Employee Dictionary Manager 2.0 =====\n")
print("1.List employees")
print("2.Add employee")
print("3.Delete employee")
print("4.Search employee")
print("5.Save data")
print("6.Quit")
choice = int(input("Please enter your choice"))
if choice == 1:
for x in range(0, len(employees)):
print("\nEmployee number: ", x + 1)
employees[x].show()
input("\nHit enter to continue...")
elif choice == 2:
name = input("\nEnter the employee name: ")
number = input("\nEnter the employee number: ")
comment = input("\nEnter the employee comment: ")
employees.append(Employee(name, number, comment))
input("\nHit enter to continue...")
elif choice == 3:
number = input("\nEnter employee number to remove")
if number > len(employees):
input("No such employee!Hit enter to continue...")
else:
del employees[number - 1]
input("\nEmployee removed - hit enter to continue...")
elif choice == 4:
search_term = input("\nEnter a name, number, or comment: ")
for x in range(0, len(employees)):
result = employees[x].find(search_term)
if result == 1:
print("\nEmployee number: ", x + 1)
employees[x].show()
input("\nHit enter to continue...")
elif choice == 5:
filename = input("\nEnter a filename: ")
save_data(filename)
from tkinter import *
from tkinter import filedialog, messagebox, scrolledtext
import sys
def open_file():
file = filedialog.askopenfile(mode="r")
if file != None:
# 1.0表示从文本的第一个字符
text.delete("1.0", END)
text.insert("1.0", file.read())
file.close()
def save_file():
file = filedialog.asksaveasfile(mode="w")
if file != None:
file.write(text.get("1.0", END))
file.close()
def about_dialog():
messagebox.showinfo("About", "Version1.0\nEnjoy!")
def exit_app():
sys.exit(0)
# 创建窗口
root_win = Tk()
root_win.title("TextEditor")
root_win.geometry("640x480")
# 创建新菜单
main_menu = Menu(root_win)
root_win.config(menu=main_menu)
# 在菜单栏上创建一个新项目
file_menu = Menu(main_menu)
main_menu.add_cascade(label="File", menu=file_menu)
# 在File菜单中增加项目
file_menu.add_command(label="Open", command=open_file)
file_menu.add_command(label="Save", command=save_file)
file_menu.add_command(label="About", command=about_dialog)
file_menu.add_command(label="Exit", command=exit_app)
text = scrolledtext.ScrolledText(root_win, width=80, height=30)
text.pack(fill="both", expand="yes")
root_win.mainloop()
import feedparser, time
import sys, os
Subtitle = input("\nEnter the Subtitle(eg'pictures') to view")
no_of_items = int(input("\nHow many headlines do you want to show?"))
show_urls = input("Show URLs as well? y/n: ")
filter = input("\nEnter a word or term you want to filter out: ")
while 1:
if sys.platform == "win32":
os.system("cls")
else:
os.system("clear")
myfeed = feedparser.parse("https://www.news.cn/r/" + Subtitle + "/.rss")
if len(myfeed["entries"]) == 0:
print("Subtitle not valid!")
sys.exit(1)
x = 1
for post in myfeed.entries:
if len(filter) > 0:
if post.title.lower().find(filter.lower()) == -1:
print("* " + post.title)
if show_urls == "y":
print(" (" + post.link + ")")
else:
print("* " + post.title)
if show_urls == "y":
print(" (" + post.link + ")")
x += 1
if x > no_of_items:
break
time.sleep(60)