Python知识全掌握:一篇文章带你飞
发表时间: 2024-03-08 12:57
# 打印 Hello Worldprint("Hello World")
# 输入两个数字num1 = input("输入第一个数字:")num2 = input("输入第二个数字:")# 求和sum = float(num1) + float(num2)# 显示计算结果print(f"{num1} + {num2} = {sum}")
# 输入一个数字num = int(input("输入一个数字:"))# 判断奇偶if num % 2 == 0: print(f"{num} 是偶数")else: print(f"{num} 是奇数")
# 打印9x9乘法表for i in range(1, 10): for j in range(1, i+1): print(f"{j}x{i}={i*j}", end="\t") print()
# 生成前10个整数的平方数列表squares = [i**2 for i in range(1, 11)]print(squares)
# 定义一个计算阶乘的函数def factorial(n): if n == 1: return 1 else: return n * factorial(n-1)# 使用函数num = 5print(f"{num} 的阶乘是 {factorial(num)}")
# 使用字典推导式创建一个字典,其中键为1到5,值为键的平方squares_dict = {i: i**2 for i in range(1, 6)}print(squares_dict)
# 写入文件with open('test.txt', 'w') as f: f.write("Hello Python!\n")# 读取文件with open('test.txt', 'r') as f: content = f.read() print(content)
# 尝试执行除法计算,捕获异常try: result = 10 / 0except ZeroDivisionError: print("除数不能为0")
# 定义一个简单的类class Dog: def __init__(self, name): self.name = name def speak(self): return f"{self.name} says Woof!"# 创建一个对象my_dog = Dog('Spot')print(my_dog.speak())
# 生成斐波那契数列的前N个数字def fibonacci(n): a, b = 0, 1 result = [] while len(result) < n: result.append(b) a, b = b, a+b return result# 调用函数print(fibonacci(10))
# 使用集合去除列表中的重复元素def remove_duplicates(lst): return list(set(lst))# 示例列表my_list = [1, 2, 2, 3, 4, 4, 5]print(remove_duplicates(my_list))
# 检查字符串是否为回文def is_palindrome(s): return s == s[::-1]# 测试字符串test_str = "madam"print(is_palindrome(test_str))
# 使用lambda函数对字典按值进行排序my_dict = {'apple': 5, 'banana': 1, 'orange': 3}sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))print(sorted_dict)
# 找出列表中的最大和最小值def find_max_min(lst): return max(lst), min(lst)# 示例列表my_list = [40, 1, 5, 200]print(find_max_min(my_list))
# 将字符串的每个单词的首字母大写def capitalize_string(s): return ' '.join(word.capitalize() for word in s.split())test_str = "hello python world"print(capitalize_string(test_str))
# 合并两个字典def merge_dicts(dict1, dict2): return {**dict1, **dict2}dict1 = {'a': 1, 'b': 2}dict2 = {'c': 3, 'd': 4}print(merge_dicts(dict1, dict2))
# 计算列表中各元素出现的次数from collections import Countermy_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']count = Counter(my_list)print(count)
# 使用requests和BeautifulSoup库进行简单的网页爬虫import requestsfrom bs4 import BeautifulSoupURL = "http://example.com"page = requests.get(URL)soup = BeautifulSoup(page.content, "html.parser")title = soup.find("title").textprint(title)
# 使用http.server库创建简单的HTTP服务器from http.server import HTTPServer, BaseHTTPRequestHandlerclass SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write(b'Hello, Python!')httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)httpd.serve_forever()
# 获取环境变量import os# 获取特定的环境变量值print(os.getenv('PATH'))
# 使用random和string库生成随机密码import randomimport stringdef generate_password(length): characters = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choice(characters) for i in range(length))print(generate_password(12))
# 使用time模块计算函数执行时间import timedef long_running_task(): time.sleep(2)start_time = time.time()long_running_task()end_time = time.time()print(f"Execution time: {end_time - start_time} seconds")
# 使用socket库创建一个简单的TCP客户端import socketHOST = '127.0.0.1' # The server's hostname or IP addressPORT = 65432 # The port used by the serverwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(b'Hello, server') data = s.recv(1024)print(f"Received {data.decode()}")
# 使用smtplib发送邮件import smtplibfrom email.mime.text import MIMETextfrom email.header import Headersender = 'your_email@example.com'receivers = ['receiver_email@example.com']msg = MIMEText('Python email test', 'plain', 'utf-8')msg['From'] = Header("Python Script", 'utf-8')msg['To'] = Header("Test User", 'utf-8')msg['Subject'] = Header('SMTP Email Test', 'utf-8')try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, msg.as_string()) print("Successfully sent email")except smtplib.SMTPException: print("Error: unable to send email")
# 使用csv库读取CSV文件import csvfilename = 'data.csv'with open(filename, mode='r') as file: csvReader = csv.reader(file) for row in csvReader: print(row)
# 使用json库写入JSON文件import jsondata = { "name": "John", "age": 30, "city": "New York"}with open('data.json', 'w') as f: json.dump(data, f)
# 使用argparse解析命令行参数import argparseparser = argparse.ArgumentParser(description='Process some integers.')parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')args = parser.parse_args()print(args.accumulate(args.integers))
# 使用qrcode库创建二维码import qrcodedata = "https://www.example.com"img = qrcode.make(data)img.save("website_qr.png")
# 使用openpyxl库操作Excel文件from openpyxl import Workbookwb = Workbook()ws = wb.active# 添加一行数据ws.append(["Name", "Age", "Gender"])ws.append(["John", 30, "Male"])# 保存到文件wb.save("sample.xlsx")
# 使用re模块进行正则表达式匹配import retext = "The rain in Spain"pattern = 'Spain'match = re.search(pattern, text)if match: print("Match found")else: print("No match")
# 使用tkinter创建简单的GUIimport tkinter as tkdef on_click(): label.config(text="Hello, Tkinter!")root = tk.Tk()root.title("Simple GUI")btn = tk.Button(root, text="Click Me", command=on_click)btn.pack()label = tk.Label(root, text="Welcome")label.pack()root.mainloop()
# 使用datetime模块进行日期和时间操作from datetime import datetime, timedeltanow = datetime.now()print("Current date and time:", now)new_date = now + timedelta(days=10)print("Date after 10 days:", new_date)
# 使用ElementTree生成和解析XMLimport xml.etree.ElementTree as ET# 创建XML数据data = '''<person> <name>John</name> <age>30</age> <city>New York</city></person>'''# 解析XMLroot = ET.fromstring(data)print("Name:", root.find('name').text)print("Age:", root.find('age').text)print("City:", root.find('city').text)
# 使用_thread启动新线程import _threadimport timedef print_time(thread_name, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print(f"{thread_name}: {time.ctime(time.time())}")try: _thread.start_new_thread(print_time, ("Thread-1", 2)) _thread.start_new_thread(print_time, ("Thread-2", 4))except: print("Error: unable to start thread")while 1: pass
# 使用shutil模块复制文件import shutilsource_file = 'source.txt'target_file = 'destination.txt'shutil.copy(source_file, target_file)
# 使用requests获取网页内容import requestsurl = 'http://example.com'response = requests.get(url)print(response.text)
# 使用argparse模块进行更高级的命令行参数解析import argparseparser = argparse.ArgumentParser(description="An advanced example.")parser.add_argument("--quiet", action="store_true", help="decrease output verbosity")parser.add_argument("square", type=int, help="display a square of a given number")args = parser.parse_args()answer = args.square**2if not args.quiet: print(f"The square of {args.square} is {answer}")
# 创建一个简单的服务器,使用socketsimport sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind(('localhost', 1234))s.listen(5)while True: clientsocket, address = s.accept() print(f"Connection from {address} has been established.") clientsocket.send(bytes("Welcome to the server!", "utf-8")) clientsocket.close()
# 使用Pandas库进行数据处理import pandas as pd# 创建DataFramedata = {'Name': ['John', 'Anna', 'Peter', 'Linda'], 'Age': [28, 34, 29, 32], 'City': ['New York', 'Paris', 'Berlin', 'London']}df = pd.DataFrame(data)# 显示DataFrameprint(df)