message = "Hello Python!"
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
title()
:首字母大写upper()
:全部大写lower()
:全部小写name = "ada lovelace"
print(name.upper())
print(name.lower())
print(name.title())
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")
print("Languages:\n\tPython\n\tC\n\tJavaScript")
rstrip()
:删除末尾的空白lstrip()
:删除头部的空白strip()
:删除两边的空白str()
:将非字符串表示为字符串bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles[0] = 'ducati'
append('元素')
insert(位置,'元素')
del
:删除某个位置的元素pop()
:删除末尾的元素pop(位置)
:删除某个位置的元素remove('值')
:根据值删除元素motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
popped_motorcycle = motorcycles.pop()
first_owned = motorcycles.pop(0)
motorcycles.remove('ducati')
sort()
:对列表进行排序(永久)sorted()
:对列表进行排序(临时)reverse()
:倒着打印列表len()
:获悉列表的长度cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
cars.sort(reverse=True)
print(sorted(cars))
cars.reverse()
len(cars)
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
range()
:生成一系列数字(左闭右开)
range(左,右,步长)
list()
:生成一个列表for value in range(1,5):
print(value)
numbers = list(range(1,6))
squares = []
for value in range(1,11):
square = value**2 # 平方
squares.append(square)
print(squares)
列表统计
min()
max()
sum()
列表解析:将for循环和创建新元素的代码合并成一行,自动附加新元素
squares = [value**2 for value in range(1,11)]
print(squares)
输出结果
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
输出结果
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
age_0 >= 21 and age_1 >= 21
age_0 >= 21 or age_1 >= 21
'mushrooms' in requested_toppings
'mushrooms' not in requested_toppings
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
alien_0 = {
'color': 'green', 'points': 5} # 新建一个字典
print(alien_0['color']) # 访问字典的值
alien_0['x_position'] = 0 # 添加一个键-值对
alien_0 = {
} # 创建一个空字典
alien_0['color'] = 'yellow' #修改一个键值对
del alien_0['points'] # 删除键值对
items()
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
keys()
for name in favorite_languages.keys():
print(name.title())
values()
set()
去重for language in favorite_languages.values():
print(language.title())
for language in set(favorite_languages.values()):
print(language.title())
aliens = []
for alien_number in range (0,30):
new_alien = {
'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
input()
:让程序暂停运行,等待用户输入。参数为输入提示。message = input("Tell me something, and I will repeat it back to you: ")
print(message)
int()
获取数值输入age = input("How old are you? ")
How old are you? 21
age = int(age)
%
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
pets.remove('cat')
responses = {
}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False
def greet_user(username):
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('jesse')
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='harry', animal_type='hamster')
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
describe_pet('willie')
describe_pet(pet_name='harry', animal_type='hamster')
def get_formatted_name(first_name, last_name, middle_name=''):
"""返回整洁的姓名"""
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
function_name(list_name[:]) # 切片表示法[:]创建列表的副本。
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
def build_profile(first, last, **user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {
}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
return
import pizza
pizza.make_pizza(16, 'pepperoni')
from module_name import function_name
from pizza import make_pizza as mp
import pizza as p
from pizza import *
__init__()
:每当创建新实例时自动调用。
self
:指向实例本身的引用,让实例访问类中的方法和属性。self会自动传递。只需传递其他的参数。class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now sitting.")
my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
my_dog.name
my_dog.sit()
__init()__
方法内指定初始值。class Car():
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print("This car has " + str(self.odometer_reading) + " miles on it.")
my_new_car.odometer_reading = 23
class Car():
--snip--
def update_odometer(self, mileage):
"""将里程表读数设置为指定的值"""
self.odometer_reading = mileage
my_new_car = Car('audi', 'a4', 2016)
my_new_car.update_odometer(23)
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
电动汽车的独特之处
初始化父类的属性,再初始化电动汽车特有的属性
"""
super().__init__(make, model, year)
self.battery_size = 70
class Car():
class Battery():
"""一次模拟电动汽车电瓶的简单尝试"""
def __init__(self, battery_size=70):
"""初始化电瓶的属性"""
self.battery_size = battery_size
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""
初始化父类的属性,再初始化电动汽车特有的属性
"""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
my_tesla.battery.describe_battery()
from car import Car
from car import ElectricCar
from car import Car, ElectricCar
import car
from module_name import *
with
:不再需要访问文件后将其关闭open()
:打开文件read()
:读取文件内容。到达文件末尾时返回一个空字符串。显示出来为一空行。
rstrip()
删除空行。with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
with open('text_files/filename.txt') as file_object:
with open('text_files\filename.txt') as file_object:
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
readlines()
:从文件中读取每一行,并将其存储在列表中。filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
open()
:
'w'
:写入模式'r'
:读取模式'a'
:附加模式'r+'
:读取和写入文件的模式filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
split()
方法filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
# 计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
pass
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
--snip--
except FileNotFoundError:
pass
else:
--snip--
json.dump()
:存储数组。实参:存储的数据和存储数据的文件对象json.load()
:读取jsonimport json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
numbers = json.load(f_obj)
assertEquals()
:参数为两个比较。unittest.main()
:运行测试。
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""测试name_function.py"""
test_first_last_name(self):
"""能够正确地处理像Janis Joplin这样的姓名吗?"""
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()
assertEqual(a, b)
:a == bassertNotEqual(a, b)
:a != bassertTrue(x)
:a为TrueassertFalse(x)
:x为FalseassertIn(item, list)
:item在list中assertNotIn(item, list)
:item不在list中import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""测试name_function.py """
def test_first_last_name(self):
"""能够正确地处理像Janis Joplin这样的姓名吗?"""
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
def test_first_last_middle_name(self):
"""能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?"""
formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
unittest.main()
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def test_store_single_response(self):
"""测试单个答案会被妥善地存储"""
--snip--
def test_store_three_responses(self):
"""测试三个答案会被妥善地存储"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = ['English', 'Spanish', 'Mandarin']
for response in responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response, my_survey.responses)
unittest.main()
setUp()
:只需创建测试对象一次,并在每个测试方法中使用他们。如果在TestCase类中包含了方法setUp()
:Python先运行它,再运行各个以test_打头的方法。这样每个测试方法都能使用setUp()
创建的对象。import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""针对AnonymousSurvey类的测试"""
def setUp(self):
"""
创建一个调查对象和一组答案,供使用的测试方法使用
"""
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
"""测试单个答案会被妥善地存储"""
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
"""测试三个答案会被妥善地存储"""
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
unittest.main()