变量
命名规则
只能包含字母、数字、下划线
不能包含空格,不能以数字开头
不能为关键字或函数名
字符串
用单引号、双引号、三引号包裹 name = "ECLIPSE"
name.title()
name.upper()
name.lower()
name.rstrip()
name.lstrip()
name.strip()
数字
x = 1
message = "bla" + str(x) + "bla"
列表
bicycles = ['1th', '2th', '3th']
bicycles[-1]
bicycles.append('4th')
bicycles.insert(0, '5th')
del bicycles[0]
poped_bicycle = bicycles.pop()
poped_bicycle = bicycles.pop(0)
a = '2th'
bicycles.remove(a)
bicycles.sort()
bicycles.sort(reverse=True)
sorted(bicycles)
sorted(bicycles, reverse=True)
bicycles.reverse()
len(bicylces)
操作列表
for bicycle in bicycels:
print(bicycle)
不会打印出数字5
for v in range(1,5):
print(v)
even_numbers = list(range(2, 21, 2))
squares = []
for v in range(1,10):
squares.append(v**2)
print(squares)
max()
min()
sum()
squares = [v**2 for v in range(1,10)]
print(squares)
players = ['1th', '2th', '3th', '4th', '5th']
print(players[0:3])
print(players[:3])
print(players[1:])
print(players[-3:])
上面的那一种并没有创建两个数组
new_players = players
new_playerss = players[:]
元组
不可被修改的列表
if
if... elif... else
and
or
if '1th' in bicycles:
print('yes')
if '1th' not in bicylces:
print('no')
if bicycles:
if not bicycles:
字典
aliens = {}
aliens['1th'] = 1
del aliens['1th']
for k, v in aliens():
for k in aliens.keys():
for k in sorted(aliens.keys()):
for v in aliens.values():
用户输入
message = input('tell me something:')
print(message)
age = int(input('tell me your age:'))
print(age+1)
循环while
break
continue
pets = ['1th', '2th', '3th', '4th', '5th']
while pets
url = 'www.baidu.com'
while url:
print('urlis: %s' %url)
url = url[:-1]
函数
形参数
实参数
位置实参
关键字实参
默认值
等效的函数调用
让实参变成可选的
def get_formated_name(firstName, lastName, middleName=''):
if middleName:
fullName = firstName + ' ' + middleName + ' ' + lastName
else:
fullName = firstName + ' ' + lastName
return fullName.title()
function_name(list_name)
function_name(list_name[:])
允许收集任意数量的实参,并把其作为一个元组传入函数
def make_pizza(*toppings):
python先匹配位置实参和关键字实参,再将余下的实参收集到一个形参中
def make_pizza(size, weight=15, *toppings):
使用任意数量的关键字实参
def build_profile(first, last, **user_info):
import module_name
from module_name import function_name
from module_name import function_name as f_nick_name
import module_name as m_nick_name
from module_name import *
类
类名称首字母大写
class Dog();
def init():
属性
方法
给属性指定一个默认的值
def init(self):
fixed_num = 0
修改属性的值:
通过句点法直接访问并修改属性的值
通过方法修改属性的值
父类and子类
子类继承另父类时,自动获得父类所有属性and方法
同时也可以定义自己的属性and方法
class Car():
def __init__(self, make, model, year):
...
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
子类中和父类相同的方法(重写父类的方法)
可以将一个实例用作属性
from car import Car
from car import Car, ElectricCar
import car
from car import * 不推荐使用
from collections import OrderedDict
languages = OderedDict() // 有顺序的字典
文件
相对文件路径
绝对文件路径
file_path = 'text_file/filename.txt' // Linux and Mac
file_path = 'text_file\filename.txt' // Windows
with open(file_path) as file_object:
contents = file_object.read()
for line in file_object:
print(line.strip())
lines = file_object.readlines()
读取文本文件时,python将其中的所有文本都读为字符串
'r' 读取模式
'w' 写入模式
'a' 附加模式
'r+' 读取和写入文件模式
python只能将字符串写入文本文件
file_object.write('...') // 不会在文末添加换行符
异常
try:
answer = ...
except ZeroDivisionError:
print('erroe')
else:
print(answer)
title = 'alice is wonderland'
title.split()
def count_words(fileName):
--snip--
fileNames = ['1th', '2th', '3th']
for fileName in fileNames:
count_words(fileName)
pass
count()
import json
json.dump(numbers, file_object)
numbers = json.load(file_object)
网友评论