- 命令行模式
C:\>
和 Python交互模式>>>
- 在Python交互模式输入
exit()
退出 - 用 Python 打印指定字符
print('hello world')
- 执行 Python 文件:在命令行模式执行
python file_name.py
运行一个.py
文件 - 错误提示
No such file or directory
:当前目录找不到文件或文件不存在。 - 输入和输出
- 输出
print()
```pythonprint(‘hello, world’)
- 输出
接受多个字符串,用逗号隔开,print() 遇到逗号输出空格(类似于console.log())
print(‘The quick brown fox’, ‘jumps over’, ‘the lazy dog’) The quick brown fox jumps over the lazy dog
打印整数,打印计算结果
print(300) 300 print(100+200) 300 ```
- 输入
input()
让用户输入字符串,并存放到一个变量里。如输入用户的名字:
# 当输入 name = input() 并按下回车时,Python交互式命令就在等您的输入了。
# 你可以输入任意字符,然后回车完成输入
>>> name = input()
Michael
# 输入完成后不会有提示,Python交互命令又返回到 >>> 状态。
# 输入的内容存放到 name 变量里,可以输入 name 查看变量内容
>>> name
'Michael'
输入和输入结合
# 第一行代码会让用户输入任意字符串作为自己名字,并存入 name 变量
name = input()
# 第二行代码根据用户输入说 hello
print('hello', name)
input()
提供一个字符串来提示用户。
# 程序运行时先打印出 'please enter your name:' 这样用户可以根据提示输入。
name = input('please enter your name: ')
print('hello,', name)
输入是Input,输出是Output,因此,我们把输入输出统称为Input/Output,或者简写为IO。
print()
# 字符串可以使用 + 运算符串连接在一起,或者用 * 运算符重复:
print('str'+'ing', 'my'*3) # string mymymy
# print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=""
print(x, end=" ")
print(y, end=" ")
问题
local variable 'x' referenced before assignment
问题:
def createCounter():
n = 0
def counter():
n = n + 1
return n
return counter
# 运行会出错:UnboundLocalError: local variable 'x' referenced before assignment。
# 这是因为当在counter中对n进行修改时,会将n视为counter的局部变量,屏蔽掉fun1中对x的定义
解决办法:使用nonlocal
关键字
def createCounter():
n = 0
def counter():
nonlocal n
n = n + 1
return n
return counter
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xaf in position
with open('x.txt', 'r', encoding='UTF-8') as f:
print(f.read())
Python中as的三种用法
1. with…as..
第一种是和with结合使用,主要用于文件的读写操作,省去了关闭文件的麻烦。
with open('文件路径','读写方式') as 赋值变量:
执行代码块
实例:
# test.py
with open('1.txt', 'r') as f:
print(f.read())
# 1.txt(两个文件在同一目录下)
# 你用的什么编程语言?
# python
2. 导入模块起别名
3. except结合使用,将捕获到的异常对象赋值给e
第二种和第三种的实例代码:
#第二种,给traceback起别名为a
import traceback as a
try:
while 1/0 < 0:
print(True)
#第三种,将异常赋值给e
except Exception as e:
print("e=",e)
a.print_exc()