初学编程100个代码大全python
理解编程的基本概念并掌握 Python 语法是初学者的关键。打印 "Hello, World!":
pythonprint("Hello, World!")
变量和基本数据类型:
pythonname = "John"
age = 25
height = 1.75
is_student = True
print(name)
print(age)
print(height)
print(is_student)
输入和输出:
pythonuser_input = input("Enter your name: ")
print("Hello, " + user_input + "!")
条件语句:
pythonnumber = int(input("Enter a number: "))
if number > 0:
print("Positive number")
elif number == 0:
print("Zero")
else:
print("Negative number")
循环:
pythonfor i in range(5):
print(i)
while i < 10:
print(i)
i += 1
列表和循环遍历:
pythonfruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
函数:
pythondef add_numbers(a, b):
return a + b
result = add_numbers(3, 4)
print(result)
字典:
pythonperson = {"name": "Alice", "age": 30, "city": "New York"}
print(person["name"])
文件操作:
pythonfile_path = "example.txt"
with open(file_path, "w") as file:
file.write("Hello, file!")
with open(file_path, "r") as file:
content = file.read()
print(content)
异常处理:
pythontry:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
这些代码片段涵盖了一些基本的编程概念,包括变量、数据类型、输入输出、条件语句、循环、函数、列表、字典、文件操作和异常处理。请尝试理解这些示例,并在实践中逐步应用这些概念。
类和对象:
pythonclass Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
my_dog = Dog("Buddy", 3)
print(my_dog.name)
my_dog.bark()
模块和包:
python# 创建一个名为 utils.py 的模块
# utils.py
def add(a, b):
return a + b
# 在另一个文件中导入模块
# main.py
import utils
result = utils.add(10, 5)
print(result)
正则表达式:
pythonimport re
text = "Hello, my email is user@example.com"
match = re.search(r'[\w.-]+@[\w.-]+', text)
if match:
print("Email found:", match.group())
else:
print("Email not found")
多线程:
pythonimport threading
import time
def print_numbers():
for i in range(5):
time.sleep(1)
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
Web 请求:
pythonimport requests
response = requests.get("https://www.example.com")
print(response.status_code)
print(response.text)
数据库连接:
pythonimport sqlite3
# 连接到数据库
conn = sqlite3.connect("example.db")
# 创建一个游标对象
cursor = conn.cursor()
# 执行 SQL 查询
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
# 插入数据
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
# 提交更改
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
conn.close()
Flask Web 应用:
pythonfrom flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
这些示例覆盖了一些更高级的主题,如类和对象、模块、正则表达式、多线程、Web 请求、数据库连接和简单的 Web 应用。逐步尝试这些示例,以建立更深入的 Python 编程知识。同时,记得查阅 Python 官方文档和其他学习资源,以便更全面地理解 Python 编程语言。