Python基础之基本语法

it2022-05-05  152

Python基础之基本语法

Python标识符Python关键字Python注释关于行与缩进多行语句简单的输入与输出读取键盘输入print输出 导入模块一些有用的内置函数(built-in)

Python标识符

第一个字符必须是字母 或下划线_标识符的其它部分由字母、数字、与下划线组成标识符对大小写敏感

Python关键字

关键字不能用于任何标识符名;在Python标准库中提供了keyword模块,可以输出当前版本所有的keyword

import keyword print(keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Python注释

使用#用于单行或多行注释

#注释 #注释

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

''' 多行注释 多行注释 ''' """ 多行注释2 多行注释2 """

关于行与缩进

由于python取消了用大括号 { } 来表示代码块,由此我们用不同的缩进来表示代码块, 注意要严格区分缩进数,否则会导致错误

if a==1: print("it's true") else: print("it's false")

多行语句

1.当一条代码太长时可以用反斜杠\来实现多行语句

b = 10 c = 2 + \ b + \ 4

输出结果:

16

在 [], {}, 或 () 中的多行语句,不需要使用反斜杠 2.当我们需要在一行语句中实现多条语句时可用;

d=5;e=100;f=9; print(d);print(e);print(f)

输出结果

5 100 9

简单的输入与输出

读取键盘输入

Python提供了input()内置函数从标准输入读入一行文本,默认的标准输入是键盘;

input 可以接收一个Python表达式作为输入,并将运算结果返回。

str = input("Please Input an object :") print("the object is :" + str)

输出结果:

Please Input an object :apple the object is :apple

print输出

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上end=""

print(1,end=" ") print(2,end="") print("Hello")

输出结果:

1 2Hello

导入模块

在python中我们使用import或import...from来导入模块 将整个模块(somemodule)导入,格式为:import module1 从某个模块中导入某个函数,格式为:from module1 import function1 从某个模块中导入多个函数,格式为:from module1 import func1, func2, func3 将某个模块中的全部函数导入,格式为:from module1 import *

一些有用的内置函数(built-in)

1.help函数 help函数可用来查看函数使用方法

help(pow) Help on built-in function pow in module builtins: pow(x, y, z=None, /) Equivalent to x**y (with two arguments) or x**y % z (with three arguments) Some types, such as ints, are able to use a more efficient algorithm when invoked using the three argument form. None

2.id()用来查看每个对象的内存地址 3.type()查看对象类型 4.dir()查看当前模块下包含的工具或类等


最新回复(0)