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

liftword6个月前 (01-13)技术文章50

想学习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语言的理解。如果您有任何问题或需要更多示例,请随时提问。

相关文章

python字典中如何添加键值对

添加键值对首先定义一个空字典 1>>> dic={}直接对字典中不存在的key进行赋值来添加123>>> dic['name']='zhangsan'>>...

Python字典-无序的键值对集合

Python字典-无序的键值对集合字典允许管理和存储键值对集合字典是可改变的。字典不会保持增加键值对时的顺序,这个顺序毫无意义。字典长啥样?person = {'name':'...

字典操作(键值对) - 看这些就够了

1、初始化:大括号、dict、fromkeys初始化2、访问:单个访问、多个访问 单个访问-->[]、get; 多个访问-->items、keys、values;访问3、编辑:增加、修改、...

python 字典插入新的健值对的方法

在 Python 中,可以使用下标运算符([])或 update() 方法向字典中插入新的键值对。使用下标运算符插入键值对的语法如下所示:my_dict = {'apple': 1,...

Python字典的全面解析与应用

近来,于头条之上,我竟不知该发布何种内容。思来想去,还是发布些我所擅长的吧。我乃一名程序员,在抖音所从事的是情感类视频创作,然而于头条,我却不愿再发布情感类的内容了。毕竟,情感往往与悲伤相依为伴,此类...

教师资格证计算机专业课——考点(Python编程)

一、Python的基本数据类型Python3 中有六个标准的数据类型: Number(数字)、String(字符)、List(列表)、Tuple(元组)、Set(集合)以及 Dictionary (字...