如何快速学习完python基本语法

该文详细介绍了Python编程的基础知识,包括变量与数据类型(如整数、浮点数、布尔值、字符串、列表、元组和字典),条件语句(if/else)、循环语句(for/while)、函数定义与调用,以及文件读写操作。此外,还涉及异常处理、模块导入、面向对象编程(类、对象、初始化方法、方法重写),以及封装、抽象、继承和接口的概念,是Python初学者的入门指南。
摘要由CSDN通过智能技术生成

如何快速的学习完python

# 1. 变量和数据类型
a = 1  # 整数
b = 2.0  # 浮点数
c = True  # 布尔值
d = "hello"  # 字符串
e = [1, 2, 3]  # 列表
f = (1, 2, 3)  # 元组
g = {"name": "Alice", "age": 20}  # 字典

# 2. 条件语句(if/else)
if a > b:
    print("a is greater than b")
else:
    print("b is greater than a")

# 3. 循环语句(for/while)
for i in range(5):
    print(i)

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

# 4. 函数定义和调用
def add(x, y):
    return x + y

result = add(3, 4)
print(result)

# 5. 列表、元组、字典等数据结构
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
my_dict = {"name": "Bob", "age": 30}

# 6. 文件读写操作
with open("file.txt", "w") as f:
    f.write("Hello, world!")

with open("file.txt", "r") as f:
    contents = f.read()
    print(contents)

# 7. 异常处理
try:
    result = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

# 8. 模块和包的导入和使用
import math

result = math.sqrt(16)
print(result)

# 9. 面向对象编程基础
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print("Hello, my name is", self.name)

person1 = Person("Alice", 20)
person1.say_hello()

# 10. 继承和多态
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

    def say_hello(self):
        print("Hello, my name is", self.name, "and I am in grade", self.grade)

student1 = Student("Bob", 18, 12)
student1.say_hello()

# 11. 封装和抽象
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if amount > self.__balance:
            print("Insufficient funds")
        else:
            self.__balance -= amount

    def get_balance(self):
        return self.__balance

account1 = BankAccount(1000)
account1.deposit(500)
account1.withdraw(200)
print(account1.get_balance())

# 12. 接口和多重继承
class Flyable:
    def fly(self):
        print("I am flying")

class Animal:
    def __init__(self, name):
        self.name = name

class Bird(Animal, Flyable):
    pass

bird1 = Bird("Eagle")
bird1.fly()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小野猫爱学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值