python基础快速入门

python基础快速入门Python 是一种简单易学且功能强大的编程语言 适合初学者入门学习 不论是就业还是做副业赚钱或者是提高自己办公效率都是不错的选择 1 安装 Python 下载 Python 前往 Python 官方网站 Welcome to Python

欢迎大家来到IT世界,在知识的湖畔探索吧!

Python 是一种简单易学且功能强大的编程语言,适合初学者入门学习,不论是就业还是做副业赚钱或者是提高自己办公效率都是不错的选择。

1. 安装 Python

  • 下载 Python :前往 Python 官方网站Welcome to Python.org,获取最新版本的 Python 以供下载。
  • 安装 Python:按照安装向导完成安装,确保勾选“Add Python to PATH”选项。
  • 验证安装:打开命令行(Windows 上是 cmd,Mac/Linux 上是 Terminal),输入 python –version,查看是否显示 Python 版本。

2. 选择开发工具

  • IDLE:Python 自带的简易开发环境,适合初学者。
  • VS Code:轻量级且功能强大的代码编辑器,支持 Python 插件。
  • PyCharm:专业的 Python IDE,适合中高级开发者。
  • Jupyter Notebook:适合数据分析和交互式编程。

3. 基础知识

  • 变量与数据类型
# 整数 num_int = 10 # 浮点数 num_float = 3.14 # 字符串 str_example = "Hello, Python!" # 布尔值 bool_example = True print("整数:", num_int) print("浮点数:", num_float) print("字符串:", str_example) print("布尔值:", bool_example)

欢迎大家来到IT世界,在知识的湖畔探索吧!

  • 列表
欢迎大家来到IT世界,在知识的湖畔探索吧!list_example = [1, 2, 3, "four", 5.0] print("列表:", list_example)
  • 元组
tuple_example = (1, 2, 3, "four", 5.0) print("元组:", tuple_example)
  • 字典
欢迎大家来到IT世界,在知识的湖畔探索吧!dict_example = {"name": "Alice", "age": 25, "city": "New York"} print("字典:", dict_example)
  • 条件语句
age = 18 if age >= 18: print("你已成年") else: print("你未成年")
  • 循环语句
欢迎大家来到IT世界,在知识的湖畔探索吧!# for 循环 for i in range(5): print(i) # while 循环 count = 0 while count < 5: print(count) count += 1
  • 函数
def add_numbers(a, b): return a + b result = add_numbers(3, 5) print("函数结果:", result)
  • 类与对象
欢迎大家来到IT世界,在知识的湖畔探索吧!class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print(f"{self.name} 正在汪汪叫!") my_dog = Dog("Buddy", 3) my_dog.bark()

以下是一个小示例

import random # 猜数字小游戏函数 def guess_number_game(): # 生成 1 到 100 之间的随机整数 secret_number = random.randint(1, 100) attempts = 0 print("欢迎来到猜数字小游戏!我已经想好了一个 1 到 100 之间的整数,你可以开始猜啦。") while True: try: # 获取用户输入 user_guess = int(input("请输入你猜的数字: ")) attempts += 1 if user_guess < secret_number: print("猜的数字太小了,再试试!") elif user_guess > secret_number: print("猜的数字太大了,再试试!") else: print(f"恭喜你,猜对了!你一共用了 {attempts} 次尝试。") break except ValueError: print("输入无效,请输入一个整数。") # 调用猜数字小游戏函数 guess_number_game()

4. 文件操作与异常处理

  • 读取一个文本文件的内容并打印
欢迎大家来到IT世界,在知识的湖畔探索吧!try: with open('test.txt', 'r', encoding='utf-8') as file: content = file.read() print(content) except FileNotFoundError: print("文件未找到。")
  • 向一个文本文件写入内容
try: with open('output.txt', 'w', encoding='utf-8') as file: file.write("这是写入的内容。") except Exception as e: print(f"写入文件时出错: {e}")
  • 向一个文本文件追加内容
欢迎大家来到IT世界,在知识的湖畔探索吧!try: with open('output.txt', 'a', encoding='utf-8') as file: file.write("\n这是追加的内容。") except Exception as e: print(f"追加文件时出错: {e}")
  • 处理除零错误和类型错误
try: a = 10 b = 0 result = a / b except ZeroDivisionError: print("除数不能为零。") except TypeError: print("类型错误。")
  • 自定义异常类
欢迎大家来到IT世界,在知识的湖畔探索吧!class MyError(Exception): def __init__(self, message): self.message = message def __str__(self): return self.message try: raise MyError("这是一个自定义异常。") except MyError as e: print(e)
  • 简单的日志系统
import os class Logger: def __init__(self, log_file): self.log_file = log_file def log(self, message): try: if not os.path.exists(self.log_file): with open(self.log_file, 'w', encoding='utf-8') as file: file.write(f"{message}\n") else: with open(self.log_file, 'a', encoding='utf-8') as file: file.write(f"{message}\n") except Exception as e: print(f"写入日志时出错: {e}") logger = Logger('app.log') logger.log("程序启动") logger.log("执行操作...") logger.log("程序结束") 

5. 标准库

  • datetime 模块
欢迎大家来到IT世界,在知识的湖畔探索吧!# 获取当前日期和时间,并进行日期计算 import datetime now = datetime.datetime.now() print(f"当前日期和时间: {now}") tomorrow = now + datetime.timedelta(days=1) print(f"明天的日期和时间: {tomorrow}")
  • random 模块
# 生成随机数和随机选择元素 import random # 生成 1 到 10 之间的随机整数 random_num = random.randint(1, 10) print(f"随机整数: {random_num}") # 从列表中随机选择一个元素 fruits = ["apple", "banana", "cherry"] random_fruit = random.choice(fruits) print(f"随机选择的水果: {random_fruit}")
  • json 模块
欢迎大家来到IT世界,在知识的湖畔探索吧!import json data = {"name": "Frank", "age": 35} # 将 Python 字典转换为 JSON 字符串 json_str = json.dumps(data) print(f"JSON 字符串: {json_str}") # 将 JSON 字符串保存到文件 with open('data.json', 'w', encoding='utf-8') as file: json.dump(data, file) # 从文件中读取 JSON 字符串并转换为 Python 字典 with open('data.json', 'r', encoding='utf-8') as file: loaded_data = json.load(file) print(f"加载的 Python 字典: {loaded_data}")
  • os 模块
import os # 查看当前工作目录 current_dir = os.getcwd() print(f"当前工作目录: {current_dir}") # 创建文件夹 new_folder = "test_folder" if not os.path.exists(new_folder): os.mkdir(new_folder) print(f"创建文件夹: {new_folder}") # 删除文件 file_to_delete = "test.txt" if os.path.exists(file_to_delete): os.remove(file_to_delete) print(f"删除文件: {file_to_delete}")

待办事项管理系统

欢迎大家来到IT世界,在知识的湖畔探索吧!import json def load_tasks(): try: with open('tasks.json', 'r', encoding='utf-8') as file: return json.load(file) except FileNotFoundError: return [] def save_tasks(tasks): with open('tasks.json', 'w', encoding='utf-8') as file: json.dump(tasks, file) def add_task(tasks, task): tasks.append(task) save_tasks(tasks) print(f"添加任务: {task}") def remove_task(tasks, task): if task in tasks: tasks.remove(task) save_tasks(tasks) print(f"删除任务: {task}") else: print(f"任务 {task} 不存在。") def show_tasks(tasks): if tasks: print("待办事项列表:") for index, task in enumerate(tasks, start=1): print(f"{index}. {task}") else: print("待办事项列表为空。") tasks = load_tasks() while True: print("\n1. 添加任务") print("2. 删除任务") print("3. 显示任务列表") print("4. 退出") choice = input("请输入你的选择: ") if choice == '1': task = input("请输入要添加的任务: ") add_task(tasks, task) elif choice == '2': task = input("请输入要删除的任务: ") remove_task(tasks, task) elif choice == '3': show_tasks(tasks) elif choice == '4': break else: print("无效的选择,请重新输入。")

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/125537.html

(0)
上一篇 39分钟前
下一篇 9分钟前

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们YX

mu99908888

在线咨询: 微信交谈

邮件:itzsgw@126.com

工作时间:时刻准备着!

关注微信