Python 是一种高级、解释型、交互式且面向对象的脚本语言,以其高可读性而著称。

Python语法摘要

Python 中文编码

在 Python 程序中处理中文字符通常使用 UTF-8 编码。

示例:

# -*- coding: UTF-8 -*-
print("你好,世界!")

Python 基础语法

Python 代码的基本结构,包括缩进、注释等。

示例:

# 这是单行注释
if True:
    print("True")  # 缩进表示代码块

Python 变量类型

Python 的基本数据类型,如整数、浮点数和字符串。

示例:

x = 10       # 整数
y = 3.14     # 浮点数
name = "Alice" # 字符串

Python 运算符

Python 中用于执行各种操作的符号,包括算术运算符、比较运算符和逻辑运算符。

示例:

a = 10
b = 5
print(a + b)  # 加法
print(a > b)  # 大于
print(True and False)  # 逻辑与

Python 条件语句

根据条件执行不同代码块的语句,包括 ifelifelse

示例:

age = 18
if age >= 18:
    print("成年")
else:
    print("未成年")

Python 循环语句

重复执行代码块的语句,包括 while 循环和 for 循环。

示例:

#While 循环
count = 0
while (count < 5):
   print ('The count is:', count)
   count = count + 1

#for 循环
for letter in 'Python':
   print ('Current Letter :', letter)

Python While 循环语句

只要条件为真,while 循环就会重复执行代码块。

示例:

count = 0
while count < 5:
    print(count)
    count += 1

Python for 循环语句

for 循环用于遍历序列(如列表、字符串)或其他可迭代对象。

示例:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Python 循环嵌套

循环嵌套是指在一个循环内部使用另一个循环。

示例:

for i in range(3):
    for j in range(2):
        print(i, j)

Python break 语句

break 语句用于跳出当前循环。

示例:

for i in range(10):
    if i == 5:
        break
    print(i)

Python continue 语句

continue 语句用于跳过当前循环的剩余部分,直接进入下一次循环。

示例:

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

Python pass 语句

pass 是一个空语句,用作占位符,表示不执行任何操作。

示例:

if True:
    pass  # 以后再添加代码

Python Number(数字)

Python 中的数字类型包括整数、浮点数和复数。

示例:

x = 10      # 整数
y = 3.14    # 浮点数
z = 2 + 3j  # 复数

Python 字符串

Python 中字符串用于表示文本,用单引号或双引号括起来。

示例:

message = "Hello, Python!"
print(message[0])  # 访问字符串中的字符
print(len(message))  # 获取字符串长度

Python 列表(List)

Python 列表用于存储有序元素集合,其中的元素可以是不同类型。

示例:

my_list = [1, "apple", 3.14]
my_list.append("banana")
print(my_list[1])

Python 元组

元组与列表类似,但元组是不可变的(创建后不能修改)。

示例:

my_tuple = (1, "apple", 3.14)
# my_tuple[0] = 2  # 错误:元组不可变

Python 字典(Dictionary)

Python 字典用于存储键值对。

示例:

my_dict = {"name": "Alice", "age": 30}
print(my_dict["name"])
my_dict["city"] = "New York"

Python 日期和时间

Python 提供了用于处理日期和时间的模块,如 datetime

示例:

import datetime

now = datetime.datetime.now()
print(now)

Python 函数

Python 函数是用于组织和重用代码的代码块。

示例:

def greet(name):
    print("Hello, " + name + "!")

greet("Bob")

Python 模块

Python 模块是包含一组函数和变量的文件,可以被其他程序导入和使用。

示例:

# my_module.py
def my_function():
    print("This is my function.")

# main.py
import my_module
my_module.my_function()

Python 文件 I/O

Python 提供了读写文件的操作。

示例:

with open("my_file.txt", "w") as f:
    f.write("Hello, file!")

with open("my_file.txt", "r") as f:
    content = f.read()
    print(content)

Python File 方法

Python file 对象提供了用于操作文件的方法,如 read()write()close() 等。(与 Python 文件I/O 示例相同)

Python 异常处理

Python 使用 tryexceptfinally 块来处理程序运行时可能出现的错误。

示例:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This will always execute.")

Python OS 文件/目录方法 Python os模块用于与操作系统交互,提供了创建目录和列出文件等函数。

示例:

import os
os.mkdir("my_directory")
print(os.listdir("."))

Python 内置函数

Python 解释器内置了许多可以直接使用的函数,如 print()len()type() 等。

示例:

print("Hello")
length = len("Python")
type(length)

print(type(length))

将百位数输出个十百各位

a=456
t=a//100
t1=a//10%10
t2=a%10
print(t,t1,t2)

输出:4 5 6

a,b,c=input()
print(a,b,c)

输入:456

输出:4 5 6

a=456

t,t1=divmod(a,100)
t3,t4=divmod(t1,10)
print(t,t3,t4)

输出:4 5 6

python divmod() 函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。

Python的注释采用“#”或者三单引号注释

# print("Hello world")
'''
print("Hello world")
'''

使用公式求解一元二次方程

import math

while True:
  try:
    a = int(input("请输入a的值:"))
    if a == 0:
      print("a不能为0,请重新输入")
    else:
      break
  except ValueError:
    print("输入错误,请输入整数")

b = int(input("请输入b的值:"))
c = int(input("请输入c的值:"))

delta = b*b - 4*a*c

if delta < 0:
  print("方程无实根")
elif delta == 0:
  x = -b / (2*a)
  print("方程有唯一实根:x =", x)
else:
  x1 = (-b + math.sqrt(delta)) / (2*a)
  x2 = (-b - math.sqrt(delta)) / (2*a)
  print("方程有两个实根:x1 =", x1, "x2 =", x2)

请输入a的值:1

请输入b的值:-3

请输入c的值:2

方程有两个实根:x1 = 2.0 x2 = 1.0

鸡兔同笼

def ji_tu_tong_long(heads, legs):
  """
  解决鸡兔同笼问题。

  Args:
    heads:  总头数。
    legs:   总腿数。

  Returns:
    一个元组 (chicken, rabbit),分别表示鸡和兔子的数量。
    如果无解,则返回 None。
  """

  for rabbit in range(heads + 1):
    chicken = heads - rabbit
    if (2 * chicken + 4 * rabbit) == legs:
      return (chicken, rabbit)

  return None  # 无解

# 获取用户输入
try:
  heads = int(input("请输入总头数:"))
  legs = int(input("请输入总腿数:"))
except ValueError:
  print("输入错误:请输入整数。")
  exit() # 退出程序

# 解决问题并打印结果
result = ji_tu_tong_long(heads, legs)

if result:
  chicken, rabbit = result
  print(f"鸡有 {chicken} 只,兔子有 {rabbit} 只。")
else:
  print("此问题无解。")

请输入总头数:3

请输入总腿数:10

鸡有 1 只,兔子有 2 只。

字符串内字符类型统计

s=input()
c1=c2=c3=c4=c5=0
for i in s:
  if i.isupper():
    c1=c1+1
  elif i.islower():
    c2=c2+1
  elif i.isdigit():
    c3=c3+1
  elif i.isspace():
    c4=c4+1
  else:
    c5=c5+1

print(c1,c2,c3,c4,c5)

输入:Lammy 2025 !

输出:1 4 4 2 1

求100内素数

import math

def is_prime(n):
  """
  判断一个数是否为素数。

  Args:
    n: 要判断的数。

  Returns:
    如果 n 是素数,返回 True;否则返回 False。
  """
  if n <= 1:
    return False  # 1 不是素数
  for i in range(2, int(math.sqrt(n)) + 1):
    if n % i == 0:
      return False  # 能被 i 整除,不是素数
  return True

# 遍历 1 到 100 (不包含100)
for i in range(1, 100):
  if is_prime(i):
    print(i)