1. 命令行模式 C:\> 和 Python交互模式 >>>
  2. 在Python交互模式输入 exit() 退出
  3. 用 Python 打印指定字符 print('hello world')
  4. 执行 Python 文件:在命令行模式执行 python file_name.py 运行一个 .py 文件
  5. 错误提示No such file or directory:当前目录找不到文件或文件不存在。
  6. 输入和输出
    1. 输出 print() ```python

      print(‘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 ```

  1. 输入 input()

让用户输入字符串,并存放到一个变量里。如输入用户的名字:

  1. # 当输入 name = input() 并按下回车时,Python交互式命令就在等您的输入了。
  2. # 你可以输入任意字符,然后回车完成输入
  3. >>> name = input()
  4. Michael
  5. # 输入完成后不会有提示,Python交互命令又返回到 >>> 状态。
  6. # 输入的内容存放到 name 变量里,可以输入 name 查看变量内容
  7. >>> name
  8. 'Michael'

输入和输入结合

  1. # 第一行代码会让用户输入任意字符串作为自己名字,并存入 name 变量
  2. name = input()
  3. # 第二行代码根据用户输入说 hello
  4. print('hello', name)

input() 提供一个字符串来提示用户。

  1. # 程序运行时先打印出 'please enter your name:' 这样用户可以根据提示输入。
  2. name = input('please enter your name: ')
  3. print('hello,', name)

输入是Input,输出是Output,因此,我们把输入输出统称为Input/Output,或者简写为IO。

print()

  1. # 字符串可以使用 + 运算符串连接在一起,或者用 * 运算符重复:
  2. print('str'+'ing', 'my'*3) # string mymymy
  3. # print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=""
  4. print(x, end=" ")
  5. print(y, end=" ")

问题

local variable 'x' referenced before assignment问题:

  1. def createCounter():
  2. n = 0
  3. def counter():
  4. n = n + 1
  5. return n
  6. return counter
  7. # 运行会出错:UnboundLocalError: local variable 'x' referenced before assignment。
  8. # 这是因为当在counter中对n进行修改时,会将n视为counter的局部变量,屏蔽掉fun1中对x的定义

解决办法:使用nonlocal关键字

  1. def createCounter():
  2. n = 0
  3. def counter():
  4. nonlocal n
  5. n = n + 1
  6. return n
  7. return counter

UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xaf in position

  1. with open('x.txt', 'r', encoding='UTF-8') as f:
  2. print(f.read())

Python中as的三种用法

1. with…as..

第一种是和with结合使用,主要用于文件的读写操作,省去了关闭文件的麻烦。

  1. with open('文件路径','读写方式') as 赋值变量:
  2. 执行代码块

实例:

  1. # test.py
  2. with open('1.txt', 'r') as f:
  3. print(f.read())
  4. # 1.txt(两个文件在同一目录下)
  5. # 你用的什么编程语言?
  6. # python

2. 导入模块起别名

3. except结合使用,将捕获到的异常对象赋值给e

第二种和第三种的实例代码:

  1. #第二种,给traceback起别名为a
  2. import traceback as a
  3. try:
  4. while 1/0 < 0:
  5. print(True)
  6. #第三种,将异常赋值给e
  7. except Exception as e:
  8. print("e=",e)
  9. a.print_exc()