程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

python基础语法,零基础新手入门

hfteth 2024-12-27 17:32:26 技术文章 13 ℃

想学习python的朋友们,今天整理了一份python基础语法入门教程,新手友好,欢迎收藏。

1. 变量与数据类型

# 整数
x = 10
print(x)  # 输出: 10

# 浮点数
y = 3.14
print(y)  # 输出: 3.14

# 字符串
name = "Alice"
print(name)  # 输出: Alice

# 布尔值
is_student = True
print(is_student)  # 输出: True

2. 列表(List)

# 定义列表
fruits = ["apple", "banana", "cherry"]
print(fruits)  # 输出: ['apple', 'banana', 'cherry']

# 添加元素到列表
fruits.append("orange")
print(fruits)  # 输出: ['apple', 'banana', 'cherry', 'orange']

# 访问列表元素
print(fruits[1])  # 输出: banana

3. 元组(Tuple)

# 定义元组
coordinates = (10.0, 20.0)
print(coordinates)  # 输出: (10.0, 20.0)

# 访问元组元素
print(coordinates[0])  # 输出: 10.0

4. 字典(Dictionary)

# 定义字典
person = {"name": "Alice", "age": 25}
print(person)  # 输出: {'name': 'Alice', 'age': 25}

# 访问字典元素
print(person["name"])  # 输出: Alice

# 添加新键值对
person["city"] = "New York"
print(person)  # 输出: {'name': 'Alice', 'age': 25, 'city': 'New York'}

5. 集合(Set)

# 定义集合
unique_numbers = {1, 2, 3, 4, 4, 5}
print(unique_numbers)  # 输出: {1, 2, 3, 4, 5}

6. 条件语句(if-else)

# 定义一个变量
age = 18

# 使用if-else进行条件判断
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

7. 循环(for和while)

# 使用for循环遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# 使用while循环
count = 0
while count < 5:
    print(count)
    count += 1

8. 函数(Functions)

# 定义一个简单的函数
def greet(name):
    return f"Hello, {name}!"

# 调用函数
message = greet("Alice")
print(message)  # 输出: Hello, Alice!

9. 类(Classes)

# 定义一个简单的类
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

# 创建类的实例
person = Person("Alice", 25)
print(person.greet())  # 输出: Hello, my name is Alice and I am 25 years old.

10. 文件操作(File Handling)

# 写入文件
with open("example.txt", "w") as file:
    file.write("Hello, World!")

# 读取文件
with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # 输出: Hello, World!

这些示例展示了Python中一些更高级的功能,如条件语句、循环、函数、类和文件操作。通过练习这些代码,您可以进一步加深对Python语言的理解。如果您有任何问题或需要更多示例,请随时提问。

最近发表
标签列表