当前位置: 首页 > news >正文

Python基础语法练习

本文涵盖了 Python 基础编程中的多个重要概念,从简单的输出语句到运算符、字符串操作、变量赋值等都有涉及。

图片

这些例子非常适合初学者学习和理解 Python 的基本语法。

1. Hello World
# 输出Hello Worldprint("Hello, World!")

图片

2. 变量赋值

# 创建变量并赋值name = "Python"age = 30height = 1.75print(f"语言: {name}, 年龄: {age}, 版本: {height}")
3. 用户输入

# 获取用户输入name = input("请输入您的姓名: ")print(f"您好, {name}!")
4. 数据类型检查

​​​​​​​

# 检查数据类型num = 42text = "Hello"flag = Trueprint(f"num的类型: {type(num)}")print(f"text的类型: {type(text)}")print(f"flag的类型: {type(flag)}")
5. 基本运算
# 基本数学运算a = 10b = 3print(f"加法: {a + b}")print(f"减法: {a - b}")print(f"乘法: {a * b}")print(f"除法: {a / b}")print(f"整除: {a // b}")print(f"取余: {a % b}")print(f"幂运算: {a ** b}")
6. 字符串操作
# 字符串基本操作text = "Python Programming"print(f"原字符串: {text}")print(f"转大写: {text.upper()}")print(f"转小写: {text.lower()}")print(f"字符串长度: {len(text)}")print(f"替换: {text.replace('Python', 'Java')}")

图片

7. 字符串格式化
# 字符串格式化的不同方法name = "张三"age = 25score = 95.5# 方法1: f-stringprint(f"姓名: {name}, 年龄: {age}, 分数: {score:.1f}")# 方法2: format方法print("姓名: {}, 年龄: {}, 分数: {:.1f}".format(name, age, score))# 方法3: %格式化print("姓名: %s, 年龄: %d, 分数: %.1f" % (name, age, score))
8. 注释练习
# 这是单行注释print("Hello")  # 行末注释"""这是多行注释可以写很多行用于详细说明"""print("World")
9. 常量定义
# Python中的常量约定(使用大写字母)PI = 3.14159MAX_SIZE = 100APP_NAME = "我的应用"print(f"圆周率: {PI}")print(f"最大尺寸: {MAX_SIZE}")print(f"应用名称: {APP_NAME}")
10. 多变量赋值
# 多变量同时赋值a, b, c = 1, 2, 3print(f"a={a}, b={b}, c={c}")# 交换变量值x, y = 10, 20print(f"交换前: x={x}, y={y}")x, y = y, xprint(f"交换后: x={x}, y={y}")
11. 转义字符
# 转义字符的使用print("第一行\n第二行")  # 换行print("制表符\t分隔")print("引号: \"Hello\"")print("反斜杠: \\")print("回车: \r覆盖")
12. 原始字符串
# 原始字符串(r-string)path = r"C:\Users\Documents\file.txt"regex = r"\d+\w*"print(f"文件路径: {path}")print(f"正则表达式: {regex}")
13. 字符串切片
# 字符串切片操作text = "Python Programming"print(f"前6个字符: {text[:6]}")print(f"后11个字符: {text[7:]}")print(f"中间部分: {text[7:18]}")print(f"每隔一个字符: {text[::2]}")print(f"反转字符串: {text[::-1]}")
14. 字符串判断
# 字符串内容判断text = "Python123"print(f"是否为数字: {text.isdigit()}")print(f"是否为字母: {text.isalpha()}")print(f"是否为字母数字: {text.isalnum()}")print(f"是否为小写: {text.islower()}")print(f"是否为大写: {text.isupper()}")
15. 输入类型转换
# 输入数据类型转换try:    age = int(input("请输入您的年龄: "))    height = float(input("请输入您的身高(米): "))    print(f"您今年{age}岁,身高{height}米")except ValueError:    print("输入格式错误!")
16. 布尔运算
# 布尔运算和逻辑操作a = Trueb = Falseprint(f"a and b: {a and b}")print(f"a or b: {a or b}")print(f"not a: {not a}")print(f"not b: {not b}")# 比较运算x, y = 5, 10print(f"{x} > {y}: {x > y}")print(f"{x} < {y}: {x < y}")print(f"{x} == {y}: {x == y}")print(f"{x} != {y}: {x != y}")
17. 成员运算符
# in 和 not in 运算符text = "Hello World"print(f"'Hello' in text: {'Hello' in text}")print(f"'Python' in text: {'Python' in text}")print(f"'Python' not in text: {'Python' not in text}")numbers = [1, 2, 3, 4, 5]print(f"3 in numbers: {3 in numbers}")print(f"6 in numbers: {6 in numbers}")
18. 身份运算符
# is 和 is not 运算符a = [1, 2, 3]b = [1, 2, 3]c = aprint(f"a == b: {a == b}")  # 值相等print(f"a is b: {a is b}")  # 不是同一个对象print(f"a is c: {a is c}")  # 是同一个对象x = Noneprint(f"x is None: {x is None}")print(f"x is not None: {x is not None}")
19. 运算符优先级
# 运算符优先级示例result1 = 2 + 3 * 4  # 乘法优先result2 = (2 + 3) * 4  # 括号改变优先级result3 = 2 ** 3 ** 2  # 幂运算从右到左result4 = 2 ** (3 ** 2)  # 明确优先级print(f"2 + 3 * 4 = {result1}")print(f"(2 + 3) * 4 = {result2}")print(f"2 ** 3 ** 2 = {result3}")print(f"2 ** (3 ** 2) = {result4}")
20. 简单计算器
# 简单的计算器程序def simple_calculator():    try:        num1 = float(input("请输入第一个数字: "))        operator = input("请输入运算符 (+, -, *, /): ")        num2 = float(input("请输入第二个数字: "))        if operator == '+':            result = num1 + num2        elif operator == '-':            result = num1 - num2        elif operator == '*':            result = num1 * num2        elif operator == '/':            if num2 != 0:                result = num1 / num2            else:                print("错误:除数不能为零!")                return        else:            print("错误:不支持的运算符!")            return        print(f"结果: {num1} {operator} {num2} = {result}")    except ValueError:        print("错误:请输入有效的数字!")# simple_calculator()  # 取消注释来运行

图片

图片

http://www.dtcms.com/a/321956.html

相关文章:

  • 力扣-56.合并区间
  • ESP32-menuconfig(4) -- Partition Table
  • [优选算法专题一双指针——三数之和]
  • Google再次颠覆自家模型,使用 MoR 模型打破 Transformer 模型壁垒
  • Java选手如何看待Golang
  • webapi项目添加访问IP限制
  • 根据字符出现频率排序
  • 【Bellman负环】Cycle Finding
  • (0️⃣基础)程序控制语句(初学者)(第3天)
  • 调用API接口返回参数缺失是什么原因导致的?
  • [3D数据存储] 对象 | OObject | IObject | 属性 | O<类型>Property | I<类型>Property
  • 安全基础DAY2-等级保护
  • linux-文件系统
  • AD8032ARZ-REEL7 ADI亚德诺 运算放大器 集成电路IC
  • 阿拉伯文识别技术:为连接古老智慧与数字未来铺设了关键道路
  • scratch笔记和练习-第11课:穿越峡谷
  • Cell-cultured meat: The new favorite on the future dining table
  • AR眼镜:能源行业设备维护的“安全守护者”
  • Shell脚本实现自动封禁恶意扫描IP
  • 考研复习-计算机组成原理-第四章-指令系统
  • nvm安装低版本的node失败(The system cannot find the file specified)
  • Mysql 如何使用 binlog 日志回滚操作失误的数据
  • 系统构成与 Shell 核心:从零认识操作系统的心脏与外壳
  • 物联网电能表在企业能耗监测系统中的应用
  • 人工智能与交通:出行方式的革新
  • Android 监听task 栈变化
  • 基于R语言,“上百种机器学习模型”学习教程 | Mime包
  • qt qtablewidget自定义表头
  • ubantu20.04 orin nx 显示器驱动
  • 【C++】类和对象--类中6个默认成员函数(2) --运算符重载