默认情况下,python3的源码文件以utf-8编码,所有字符串都是Unicode字符串,可以使用如下代码指定不同的编码:
# -*- coding: encoding name -*-
保留字即关键字,python的biaz标准库中tig提供了keywordmuku模块,keyword.kwlist可以输出所有的关键字:
>>>import keyword
>>>keyword.kwlist
输出结果:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'cla
ss', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from
', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pas
s', 'raise', 'return', 'try', 'while', 'with', 'yield']
#第一个注释
'''
第二个注释
第三个注释
'''
"""
第四个注释
第五个注释
"""
print("hello world!")
执行以上代码,输出结果为:
hello world!
在python中最具特色的就是使用缩进来表示代码块,而不需要使用{},同一个代码块必须使用相同的缩进空格数。出现缩进不一致的会导致报错:
IndentationError: unindent does not match any outer indentation level
python中如果语句过长,可使用反斜杠(\)来实现duoh多行语句。例如:
total = item_one + \
item_two + \
item_three
在(),[],{}中的多行语句不需要使用反斜杠(\)。例如:
total = ['item_one','item_two','item_three',
'item_four','item_five']
str = "student"
#输出字符串
print(str)
#输出第一个到倒数第二个字符串
print(str[0:-1])
#输出字符串第一个字符
print(str[0])
#输出第三个到第五个字符
print(str[2:5])
#输出第三个开始到最后的所有字符
print(str[2:])
#输出字符串两次
print(str * 2)
#连接字符串
print(str + "你好")
#使用\+n转义
print("hello python!\n")
#字符串前面添加r,不会发生转义
print(r"hello python\n")
执行以上代码,输出结果为:
student
studen
s
ude
udent
studentstudent
student你好
hello python!
hello python\n
input ("\n\n按下enter键后退出")
执行上面代码,用户输入按下回车,显示用户输入的内容之后退出。
print默认输出是换行的,如果要实现不换行需要在变量后加上end=" "
x = "a"
y = "b"
print(x)
print(y)
print(x,end = "")
print(y,end = "")
执行以上代码,结果如下:
a
b
ab
在python中用import和from...import来导入相应的模块
将整个模块(somemodule)导入,格式为:import somemodule
将模块中的某个函数导入,格式为:from somemodule import somefunction
将模块中的多个函数导入,格式为:from somemodule import firstfunc,secondfunc,thirdfunc
将某个模块中的全部函数导入,格式为:from somemodule import *