python 基础心得

常见问题

  • 循环是for x in a:,中间用in而不是冒号
  • 数组测长度用len(a),而不是a.len

数组、字典定义

cars = ["Ford", "Volvo", "BMW"]
l = len(cars)

# remove & insert
cars.append("Benz")
cars.remove("Volvo") # only delete the first one

# iteration
for x in cars:
	print(x)

# !!!!!!!!!!
# Most functions would throw exception if they fail to find something.
# !!!!!!!!!!

其他函数:

  • clear() :清除至空数组
  • index(content) :返回第一个该内容的坐标
  • pop(index) :删除该元素,后面的元素坐标前移
  • extend(arr) :数组末尾接上另一个数组的元素

有关raw string

使用方法r"content",即在字符串前加r
这种情况下斜杠\加大部分字母的组合无效,包括回车和双斜杠本身。但\'\"依旧有效。

函数内用全局变量的原则

若有变量a在函数作用域外定义:

  • 如果在使用a前声明global a,则当做全局变量读写
  • 如果第一次调用a用了句型a = val,则当做局部变量,不对函数外部的a作任何改变
  • 如果第一次调用a是读取其中的值,或操作a的内部变量(e.g.a[2] = "car"a.size += 1)则将其作“只读”的全局变量,之后不能有类似a = val的句型
  • 可以直接global一个新变量

其他

  • eval()转字符串到任何类型
  • str()转其他类型到字符串
  • 输出小数时可用round(num, digits)保留尾数

文件输入输出

fo = open("foo.txt", "w")
fo.write("some content in string\n")
fo.close()

fi = open("foo.txt", "r")
content = fi.read()
fi.close()

你可能感兴趣的:(python,编程)