Python 基础语法

在本篇文章,我们快速给同学们介绍下 Python 的基础语法,主要包括内容如下:

  1. 数据变量
  2. 流程控制

1. 数据变量

这一部分我们快速掌握 Python 中关于变量定义、数据类型、注释语法、输入和输出、运算符相关的语法规则。下面是示例代码:

1.1 变量定义

字符串类型变量定义:

name1 = "obama";
name2 = 'smith';
content1 = """多行字符串数据
    多行字符串数据
    多行字符串数据
    多行字符串数据
"""

content2 = """多行字符串数据
    多行字符串数据
    多行字符串数据
    多行字符串数据
"""

print(name1)
print(name2)
print(content1)
print(content2)

程序输出结果:

obama
smith
多行字符串数据
    多行字符串数据
    多行字符串数据
    多行字符串数据

多行字符串数据
    多行字符串数据
    多行字符串数据
    多行字符串数据

其他类型变量定义:

acount = 1000
salary = 3.14
gender1 = True
gender2 = False

print(acount)
print(salary)
print(gender1)
print(gender2)

程序输出结果:

1000
3.14
True
False

1.2 注释语法

在Python中,注释用于在代码中添加说明和解释,对于程序员来说是非常重要的。Python支持两种类型的注释语法:

  1. 单行注释:使用 # 符号表示;
  2. 多行注释:使用三个连续的引号 ('''""") 表示。
# 单行注释
print("单行注释")


'''
多行注释一
'''
print("多行注释一")


"""
多行注释二
"""
print("多行注释二")

1.3 标准输出函数

在 Python 中,标准输出函数指的是 print 函数,该函数是使用频率极高,需要掌握其用法。我们主要讲解下面两方面内容:print 参数和格式化输出。

print 参数详解:

import sys


# 1. 设置字符串输出结尾字符
# 默认以换行符结尾
print("Hello World")
# 手动设置以!结尾
print("Hello World", end="!")

print()

# 2. 输出多个字符串设置分隔符
# 默认多个字符串之间使用空格隔开
print("Hello", "World")
# 手动设置字符串之间使用#隔开
print("Hello", "World", sep="#")


# 3. 设置输出目标设备
# 默认输出到标准输出设备
print("Hello World", file=sys.stdout)
# 手动设置文件作为输出设备
print("Hello World", file=open('demo.txt', 'w'))

程序输出结果:

Hello World
Hello World!
Hello World
Hello#World
Hello World

print 格式化字符串:

name = "smith"
age = 22
salary = 6888.88


# 1. % 格式化
format_string1 = "Name:%8s Age:%04d Salary:%10.4f" % (name, age, salary)
print(format_string1)

# 2. str.format 格式化
# 注意: > 表示右对齐,< 表示左对齐 ^表示居中对齐
format_string2 = "Name:{:>8} Age:{:04} Salary:{:10.4f}".format(name, age, salary)
print(format_string2)

# 3. f-string 格式化
format_string3 = f"Name:{name:>8} Age:{age:04} Salary:{salary:10.4f}"
print(format_string3)

程序输出结果:

Name:   smith Age:0022 Salary: 6888.8800
Name:   smith Age:0022 Salary: 6888.8800
Name:   smith Age:0022 Salary: 6888.8800

1.4 标准输入函数

标准输出函数指的是 input 函数,我们主要讲解下面两方面内容:input 参数和类型转换。

# 1. 输入字符串
value1 = input("请输入字符串:")
print(value1)

# 2. 输入整数
value2 = input("请输入整数:")
print("value2 类型:", type(value2))
value2 = int(value2)
print("value2 类型:", type(value2))

# 3. 输入小数
value3 = input("请输入小数:")
print("value3 类型:", type(value3))
value4 = float(value3)
print("value3 类型:", type(value4))

# 注意: 不能直接将字符串格式的小数转换为整数类型
# value5 = int(value3)

程序输出结果:

请输入字符串:hello world
hello world
请输入整数:666
value2 类型: <class 'str'>
value2 类型: <class 'int'>
请输入小数:3.14
value3 类型: <class 'str'>
value3 类型: <class 'float'>

1.5 运算符

  1. 算术运算符:
    • 加法:+
    • 减法:-
    • 乘法:*
    • 除法:/
    • 取余数:%
    • 幂运算:**
    • 整除://
  2. 比较运算符:
    • 等于:==
    • 不等于:!=
    • 大于:>
    • 小于:<
    • 大于等于:>=
    • 小于等于:<=
  3. 逻辑运算符:
    • 与:and
    • 或:or
    • 非:not
  4. 位运算符:
    • 按位与:&
    • 按位或:|
    • 按位异或:^
    • 按位取反:~
    • 左移:<<
    • 右移:>>
  5. 赋值运算符:
    • 简单赋值:=
    • 加法赋值:+=
    • 减法赋值:-=
    • 乘法赋值:*=
    • 除法赋值:/=
    • 取余赋值:%=
    • 幂运算赋值:**=
    • 整除赋值://=
a = 15
b = 2
c = 0

# 1. 整除运算
print("-------整除-------")
print("a /  2 = ", a / 2)
print("a // 2 = ", a // 2)

# 2. 幂运算
print("-------幂运算-------")
print("a ** 2 = ", a ** b)

# 3. 逻辑运算
print("-------逻辑运算-------")
print(f"{a} and {b} = {a and b}")
print(f"{b} and {a} = {b and a}")
print(f"{a} or {c} = {a and c}")
print(f"{c} or {a} = {a and c}")
print(f"not {a} = {not a}")
print(f"not {c} = {not c}")

# 4. 位运算
print("-------位运算-------")
# a = 1111
# b = 0010
print(f"{a} & {b} = {a & b}")

2. 流程控制

这一小节主要介绍 if 条件语句和 while、for 循环语法。

2.1 条件语句

username = "admin"
password = "123456"

# 1. 条件语句

# 1.1 场景一
if username == "admin" and password == "123456":
    print("登录成功")
elif username == "admin" and password != "123456":
    print("密码不正确")
elif username != "admin" and password == "123456":
    print("账号不正确")
else:
    print("账号和密码不正确")

# 1.2 场景二
age = 18

if age >= 1 and age < 18:
    print('未成年人')
else:
    print("成年人")

if 1 <= age < 18:
    print('未成年人')
else:
    print("成年人")


# 1.3 单行简化条件语句
result = True if age > 18 else False
print(result)


# 1.4 循环语句嵌套
a = 10
b = 20
if a > 10:
    if b > 20:
        print('满足条件')
    else:
        print("不满足条件")
else:
    print("不满足条件")

2.2 循环语句

在 Python 中主要有两种循环语法:while 和 for 循环。

# 1. while 语句
index = 0
while index < 5:
    print(index)
    index += 1  # Python 不存在 ++ 运算符

index = 0
while True:
    if index == 5:
        break
    print(index)
    index += 1


index = 0
while index < 5:
    if index == 2:
        index += 1
        continue
    print(index)
    index += 1


# 2. for 循环
# for 循环适合遍历容器
for index in range(5):
    print(index)

for ch in "Hello World":
    print(ch)

未经允许不得转载:一亩三分地 » Python 基础语法
评论 (0)

9 + 2 =