• 1. 导入模块
  • 2. 缩进
  • 3. 注释
  • 4. 多行语句
  • 5. Print 输出
  • 6. 等待用户输入



1. 导入模块

模块实际上就是 以.py为结尾的文件
但自定义的模块尽量不要和系统模块重名

模块内部封装了很多实用的功能
有时在模块外部调用就需要将其导入
导入模块简单划分,实际上只有两种:

  • import ……
  • from …… import

细分的话,有五种:

  1. improt 模块名
    调用:模块名.功能名
import math

print("9的平方根:", math.sqrt(9))

# 9的平方根: 3.0
  1. import 模块名 as 别名
    调用:别名.功能名
import math as m

print("9的平方根:", m.sqrt(9))

# 9的平方根: 3.0
  1. from 模块名 import 功能名
    调用:直接功能名
from math import sqrt

print("9的平方根:", sqrt(9))

# 9的平方根: 3.0
  1. from 模块名 import 功能名 as 别名
    调用: 直接拿别名来用
from math import sqrt as s
        
print("9的平方根:", s(9))

# 9的平方根: 3.0
  1. from 模块名 import * (用 * 号 一次性导入所有功能)
    调用:直接功能名
from math import *

print("9的平方根:", sqrt(9))

# 9的平方根: 3.0

2. 缩进

Python 与其他语言最大的区别就是 用缩进来写模块
代替大括号 { } 来控制类,函数以及其他逻辑判断

if True:
    print("True")
else:
    print("False")

缩进的空白数量是可变的

if True:
    print("True")
else:
        print("False")

但是同一代码块语句必须包含相同的缩进空白数量

if True:
    print("True")
else:
        print("False")
    print("False")

# print("False")
#              ^
# IndentationError: unindent does not match any outer indentation level

不相同的缩进就会出现错误提示啦


3. 注释

python中单行注释采用 # 开头

# 第一个注释

print("Hello, world!")  # 第二个注释

多行注释使用 三个单引号’’’ 或 三个双引号"""

'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''

"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""

也可以作为输出函数的注释:

def a():
    '''这是文档的注释'''
    pass
print(a.__doc__)

# 这是文档的注释

4. 多行语句

  • 使用反斜杠 \ 来实现多行语句
a = 1 + 2 \
    + 3
print(a)

# 6
  • 在 [ ], { }, 或 ( ) 中的多行语句,不需要使用反斜杠 \
print(1 + 2
      + 3)
# 6

5. Print 输出

print 默认换行输出,因为其内置的结尾 end 默认设置为换行

print("Hello")
print("world!")

# Hello 
# world!

如果要实现不换行,令 end = “”,这样结尾就为空了

print("Hello", end="")
print("world!")

# Helloworld!

或者在显示多个变量时,在变量末尾加上逗号 , 就行了,此时默认会以一个空格隔开

print("Hello", "world!")

# Hello world!

6. 等待用户输入

使用函数input()时,Python将用户输入解读为字符串

name = input("Please intput your name:")
print('Hello', name)

# Please intput your name:

此时输入 H-H,敲击回车键结束,显示

# Hello H-H