Python日记

血来潮学习Python!本文以Windows 7 + Python 2.7.1为蓝本。

     Python是一种解释执行的语言(更恰当的,应该称之为脚本),需要专门的解释器解释运行。支持模块化编程,支持GUI界面。可以很简单、有效地 开发用于文件I/O、socket、GUI等等的程序。并且Python具有良好的扩展性,可以修改解释器,使它支持用户自定义的内置模块。如果你需要计 算机自动地处理一些底层的任务,而自己专注于高层功能的开发,Python is just the recipe for you!

     Python程序的运行必须通过Python解释器。解释器通过命令行调用,有三种调用方式:

  1. python py文件 [参数 参数 …] 这是最常用的一种方式,自己先编写好一个python脚本文件,然后用解释器解释运行它
  2. python -c 语句 直接在命令行中写入需要执行的语句,语句中如有空格,则语句应加双引号,适用于比较简短的测试情形
  3. python 不加任何参数,在解释器运行过程中交互式地编写脚本

     下面正式Python语言的学习!本人初学,如有疏漏错误之处还请高手指教!

一、常量、变量

1.1 常量

     Python中的常量有三种:数字(Number)、字符串(String),以及Unicode字符串(Unicode String)。

     数字根据书写形式的不同,可分为整型、浮点型和复数型。它们之间可以进行混合运算,并自动进行类型的转换 (int->float->complex)。同时,用户也可以强制类型转换函数在整型、长整型和浮点型之间强制转换。对于复数,没有强制类 型转换的函数。不过,可以用z.real和z.imag的形式取z的实部和虚部。复数常量书写的形式是 a+bJ 或 a+bj。

     字符串是一串用单引号或双引号括起来的串。两者完全等价。但是,在单引号括起来的字符串中使用单引号,需要用转义字符“\”;而在双引号括起来的字符串中使用双引号,则需要转义。对于大段的字符串,可以用三个连续的      ''' 或      """ 做为开始和结束的标记。这个也常常用来做注释。

     Unicode字符串类似于普通的字符串,仅仅是在存储时,每个字符占用两个字节的空间。在常量的表示上,需要在原有的字符串常量前加上一个“u”,如 u'Hello' 就是一个Unicode字符串。在Unicode字符串中,可以使用"\uNNNN"来对任意Unicode字符进行转义。Unicode字符串和普通字 符串之间可以使用unicode()和str()函数进行相互转换。对于存在无法用0-127之间的ASCII码表示的Unicode串,需要用 encoder()函数,将其编码为字符串。

     字符串和Unicode的长度可以用len()这个内置函数来获得。如果要获取字符串或Unicode字符串中某个字符,可以用取下标运算:

1 'Hello World!'[1] #值为'e'
2 'Hello World!'[6:11] #值为'World'
3 'Hello World!'[3:] #值为'lo World!'
4 'Hello World!'[-3:] #值为'ld!'
5 'Hello World!'[:3] #值为'Hel'
6 'Hello World!'[:-3] #值为'Hello Wor'
7 'Hello World!'[:] #值为'Hello World!'
8 u'你好'[1] #值为'\xe3'(“你”的第二个字节)


     鉴于这里的下标运算与一般的C语言有较大区别,需要做一些解释。A[m:n]中的m、n分别表示在字符串A中所要取的第一个字符和停止取的第一个字符。当m、n是非负数时,这个下标从字符串头部开始计算;当m、n为正数时,下标从尾部开始算。

1.2 变量

     在Python中,变量的使用不需要预先定义。只要对一个标识符进行了赋值,就等于定义了这个变量。使用del命令可以删除一个变量。例如

1 a=1
2 b='Hello'
3 c=u'Python日记'
4 del a, b, c

     在交互模式下,有一个特殊的变量:“_”,它仅仅是一个下划线,表示了上一个命令回显的结果。

     变量除了可以是上述的数字、字符串、Unicode字符串之外,还有一些更高层的数据结构。其中最简单是列表(List)。列表类似与C语言中的结构体,它的每一个成员都可以是不同的数据类型。成员之间用逗号隔开,整个列表用中括号括起来。例如

1 a = [1, 'test']
2 b = [12, ['apple', u"pear"]]

     对列表中成员的引用,可以使用如下的格式:

1 a[0] #取a的第一个成员
2 b[1][0] #取a的第二个成员的第一个成员
3 b[0:1] #取b的下标大于等于0,小于1的所有元素组成的列表

     列表的长度也可以用len()函数来获得。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的Python日记本程序,包括了新建、打开、关闭、保存和另存为等文件操作功能,以及日记编辑功能和附加信息的显示功能。同时,程序还可以为日记本设置密码,保护日记的隐私。 ```python import tkinter as tk import tkinter.filedialog as filedialog import tkinter.messagebox as messagebox import datetime import requests from cryptography.fernet import Fernet class Diary: def __init__(self, password=None): self.password = password self.title = '' self.content = '' self.additional_info = '' def set_password(self, password): self.password = password def save(self, file_path): if self.password: key = Fernet.generate_key() cipher_suite = Fernet(key) self.title = cipher_suite.encrypt(self.title.encode()) self.content = cipher_suite.encrypt(self.content.encode()) self.additional_info = cipher_suite.encrypt(self.additional_info.encode()) with open(file_path, 'wb') as f: f.write(key) f.write(self.title) f.write(self.content) f.write(self.additional_info) else: with open(file_path, 'w') as f: f.write(self.title) f.write(self.content) f.write(self.additional_info) def open(self, file_path): if self.password: with open(file_path, 'rb') as f: key = f.read(32) cipher_suite = Fernet(key) self.title = cipher_suite.decrypt(f.read()) self.content = cipher_suite.decrypt(f.read()) self.additional_info = cipher_suite.decrypt(f.read()) else: with open(file_path, 'r') as f: self.title = f.readline() self.content = f.readline() self.additional_info = f.readline() def close(self): self.title = '' self.content = '' self.additional_info = '' class DiaryEditor: def __init__(self): self.root = tk.Tk() self.diary = Diary() self.create_widgets() def create_widgets(self): self.root.title('Diary Editor') self.root.geometry('800x600') # 菜单栏 menubar = tk.Menu(self.root) filemenu = tk.Menu(menubar, tearoff=0) filemenu.add_command(label='New', command=self.new_diary) filemenu.add_command(label='Open', command=self.open_diary) filemenu.add_command(label='Save', command=self.save_diary) filemenu.add_command(label='Save As', command=self.save_as_diary) menubar.add_cascade(label='File', menu=filemenu) self.root.config(menu=menubar) # 标题 tk.Label(self.root, text='Title:').pack() self.title_entry = tk.Entry(self.root) self.title_entry.pack() # 内容 tk.Label(self.root, text='Content:').pack() self.content_text = tk.Text(self.root) self.content_text.pack() # 附加信息 tk.Label(self.root, text='Additional Info:').pack() self.additional_info_text = tk.Text(self.root, height=5) self.additional_info_text.pack() # 天气信息 self.weather_label = tk.Label(self.root, text='') self.weather_label.pack() # 保存按钮 tk.Button(self.root, text='Save', command=self.save_diary).pack() def new_diary(self): self.diary.close() self.title_entry.delete(0, tk.END) self.content_text.delete('1.0', tk.END) self.additional_info_text.delete('1.0', tk.END) def open_diary(self): file_path = filedialog.askopenfilename(filetypes=[('Text Files', '*.txt'), ('Encrypted Files', '*.enc')]) if file_path: password = None if messagebox.askyesno('Password', 'Do you want to open a password-protected diary?'): password = messagebox.askstring('Password', 'Please enter the password:') self.diary.set_password(password) self.diary.open(file_path) self.title_entry.delete(0, tk.END) self.title_entry.insert(0, self.diary.title.decode()) self.content_text.delete('1.0', tk.END) self.content_text.insert('1.0', self.diary.content.decode()) self.additional_info_text.delete('1.0', tk.END) self.additional_info_text.insert('1.0', self.diary.additional_info.decode()) def save_diary(self): if not self.title_entry.get(): messagebox.showerror('Error', 'Title cannot be empty!') return self.diary.title = self.title_entry.get() self.diary.content = self.content_text.get('1.0', tk.END) self.diary.additional_info = self.additional_info_text.get('1.0', tk.END) if self.diary.password: file_path = filedialog.asksaveasfilename(filetypes=[('Encrypted Files', '*.enc')]) else: file_path = filedialog.asksaveasfilename(filetypes=[('Text Files', '*.txt')]) if file_path: self.diary.save(file_path) messagebox.showinfo('Info', 'Diary saved successfully!') def save_as_diary(self): if not self.title_entry.get(): messagebox.showerror('Error', 'Title cannot be empty!') return self.diary.title = self.title_entry.get() self.diary.content = self.content_text.get('1.0', tk.END) self.diary.additional_info = self.additional_info_text.get('1.0', tk.END) if self.diary.password: file_path = filedialog.asksaveasfilename(filetypes=[('Encrypted Files', '*.enc')]) else: file_path = filedialog.asksaveasfilename(filetypes=[('Text Files', '*.txt')]) if file_path: self.diary.save(file_path) messagebox.showinfo('Info', 'Diary saved successfully!') def update_weather_info(self): try: response = requests.get('https://api.seniverse.com/v3/weather/now.json', params={ 'key': 'your_key', 'location': 'your_location', 'language': 'zh-Hans', 'unit': 'c' }, timeout=1) json_data = response.json() weather = json_data['results'][0]['now']['text'] temperature = json_data['results'][0]['now']['temperature'] self.weather_label.config(text='Weather: {} {}°C'.format(weather, temperature)) except: self.weather_label.config(text='Failed to get weather information') def run(self): # 更新天气信息 self.update_weather_info() # 更新附加信息中的时间信息 current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.additional_info_text.insert(tk.END, 'Time: {}\n'.format(current_time)) # 运行程序 self.root.mainloop() if __name__ == '__main__': editor = DiaryEditor() editor.run() ``` 在这个程序中,我们使用了`tkinter`库实现了GUI界面,并使用了`filedialog`和`messagebox`模块来实现文件操作和提示框功能。程序中的`Diary`类代表一个日记,包括了标题、内容和附加信息等属性,同时可以使用`set_password()`、`save()`和`open()`方法来设置密码、保存和打开日记。在程序中的`DiaryEditor`类中,我们创建了GUI界面,并实现了各种按钮的响应函数,包括新建、打开、保存和另存为等文件操作功能,以及日记编辑功能和附加信息的显示功能。在程序中,我们还使用了`requests`库来获取天气信息,并使用了`datetime`模块来获取当前时间信息。 需要注意的是,程序中的加密功能使用了`cryptography`库中的`Fernet`,需要先安装该库才能正常运行。同时,程序中的天气信息需要使用自己的API Key和地理位置信息才能获取到正确的天气信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值