Python 编程指南4_python编程初学者指南 在线阅读

Python 编程指南4_python编程初学者指南 在线阅读

编码文章call10242025-02-25 11:13:0534A+A-

1. Lambda 函数

lambda 函数是 Python 中的一个小的匿名函数。它可以接受多个参数,但仅限于单个表达式。Lambda 函数通常用于短期任务,并且以单行编写。

Lambda 参数:表达式

# Adding 10 to a number
number = lambda num: num + 10
print(number(5))  # Output: 15

# Multiplying two numbers
x = lambda a, b: a * b
print(x(5, 6))  # Output: 30

异常处理

异常处理可确保您的程序在发生错误时不会崩溃。Python 允许您正常处理错误并继续运行程序,而不是突然停止。

异常处理的关键组件:

  1. try:测试代码块是否有错误。
  2. except:如果发生错误,则处理错误。
  3. else:如果没有错误,则执行代码。
  4. finally:无论是否发生错误,都执行代码。

示例:基本异常处理

try:
    print(x)  # 'x' is not defined
except:
    print("An exception occurred")  # Output: An exception occurred

例:处理特定错误

try:
    print(x)
except NameError:
    print("Variable x is not defined")  # Output if NameError occurs
except:
    print("Something else went wrong")  # Output for other errors

示例:使用else

else 块仅在 try 块中没有发生错误时运行。

try:
    print("Hello")
except:
    print("Something went wrong")
else:
    print("Nothing went wrong")  # Output: Nothing went wrong

示例:使用finally

finally 块无论如何都会运行。

try:
    print(x)  # 'x' is not defined
except:
    print("Something went wrong")
finally:
    print("The 'try except' block is finished")  # Always executes

文件处理

文件处理允许您在 Python 中创建读取写入附加删除文件

使用open()打开文件

open() 函数用于处理文件。它需要两个参数:

  1. 文件名:文件的名称。
  2. 模式:指定用途(读取、写入等)。

文件模式:

  • r:读取模式(如果文件不存在,则出错)。
  • a:附加模式(如果文件不存在,则创建文件)。
  • w:写入模式(如果文件不存在,则创建文件)。
  • x:创建模式(如果文件已存在,则出错)。

示例:读取文件

file = open("textfile.txt", "r")
print(file.read())
file.close()  # Always close the file after working with it

例:追加到文件

file = open("textfile.txt", "a")
file.write("Now the file has more content!")
file.close()

# Reading the updated file
file = open("textfile.txt", "r")
print(file.read())

示例:删除文件

要删除文件,您需要 os 模块。

import os

# Deleting a file
os.remove("textfile.txt")

要点:

  • 使用 file.close() 处理文件后,始终关闭文件。
  • 可以使用异常处理来管理文件处理错误,以实现更顺畅的工作流程。
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4