首页 > 编程知识 正文

Python程序设计学习笔记1

时间:2023-11-20 08:24:20 阅读:307724 作者:QDXL

Python程序设计学习笔记1是关于使用Python进行程序设计的学习笔记的第一部分。

一、基本语法

1、Python的注释

Python中使用#符号来表示注释,注释是对代码的解释和说明,不会被执行。

    # 这是一个注释
    print("Hello World")

2、Python的变量

Python中使用变量来存储数据,变量名需要遵循一定的命名规则,可以包含字母、数字和下划线,且不能以数字开头。

    x = 5
    y = "Hello"
    print(x)
    print(y)

3、Python的数据类型

Python中有不同的数据类型,包括整数(int)、浮点数(float)、字符串(str)、布尔值(bool)等。

    x = 5         # 整数
    y = 3.14      # 浮点数
    z = "Hello"   # 字符串
    is_true = True      # 布尔值
    print(type(x))      # 输出数据类型
    print(type(y))
    print(type(z))
    print(type(is_true))

二、条件语句

1、if语句

if语句用于根据条件执行不同的代码块。

    x = 10
    if x > 5:
        print("x大于5")
    else:
        print("x小于等于5")

2、elif语句

elif语句用于多个条件判断。

    x = 10
    if x > 5:
        print("x大于5")
    elif x == 5:
        print("x等于5")
    else:
        print("x小于5")

3、逻辑运算符

逻辑运算符用于对条件进行组合。

    x = 10
    y = 5
    if x > 5 and y > 3:
        print("x大于5且y大于3")
    if x > 5 or y > 3:
        print("x大于5或y大于3")
    if not(x > 5):
        print("x不大于5")

三、循环语句

1、for循环

for循环用于遍历序列或可迭代对象。

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

2、while循环

while循环用于在条件满足时重复执行代码块。

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

3、break和continue语句

break语句用于终止循环,continue语句用于跳过当前循环。

    i = 0
    while i < 5:
        if i == 3:
            break
        print(i)
        i += 1
    
    for x in fruits:
        if x == "banana":
            continue
        print(x)

四、函数

1、自定义函数

使用def关键字定义自定义函数,并在需要时调用。

    def greet(name):
        print("Hello, " + name)
    
    greet("Alice")
    greet("Bob")

2、返回值

函数可以返回一个值,使用return关键字。

    def add(x, y):
        return x + y
    
    result = add(3, 4)
    print(result)

3、函数的参数

函数可以接受多个参数,包括默认参数和可变参数。

    def multiply(x, y=2):
        return x * y
    
    result1 = multiply(3)
    print(result1)
    
    result2 = multiply(3, 4)
    print(result2)
    
    def sum(*args):
        total = 0
        for num in args:
            total += num
        return total
    
    result3 = sum(1, 2, 3, 4)
    print(result3)

五、模块和包

1、引入模块

使用import关键字来引入模块。

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

2、自定义模块

可以创建自己的模块并在其他程序中引入使用。

    # mymodule.py
    def greet(name):
        print("Hello, " + name)
    
    # main.py
    import mymodule
    
    mymodule.greet("Alice")
    

以上是关于Python程序设计学习笔记1的详细阐述,包括基本语法、条件语句、循环语句、函数以及模块和包的使用。 通过学习这些内容,可以更好地理解和掌握Python编程语言,为后续的学习和应用打下坚实的基础。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。