變量
命名規(guī)則
只能包含字母、數(shù)字、下劃線
不能包含空格蚪腐,不能以數(shù)字開頭
不能為關鍵字或函數(shù)名
字符串
用單引號、雙引號税朴、三引號包裹 name = "ECLIPSE"
name.title()
name.upper()
name.lower()
name.rstrip()
name.lstrip()
name.strip()
數(shù)字
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)
不會打印出數(shù)字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:])
上面的那一種并沒有創(chuàng)建兩個數(shù)組
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)
循環(huán)while
break
continue
pets = ['1th', '2th', '3th', '4th', '5th']
while pets
url = 'www.baidu.com'
while url:
print('urlis: %s' %url)
url = url[:-1]
函數(shù)
形參數(shù)
實參數(shù)
位置實參
關鍵字實參
默認值
等效的函數(shù)調(diào)用
讓實參變成可選的
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[:])
允許收集任意數(shù)量的實參回季,并把其作為一個元組傳入函數(shù)
def make_pizza(*toppings):
python先匹配位置實參和關鍵字實參,再將余下的實參收集到一個形參中
def make_pizza(size, weight=15, *toppings):
使用任意數(shù)量的關鍵字實參
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)