#本文章仅用于记录本人学习过程,当作笔记来用,如有侵权请及时告知,谢谢!
P15:
#循环中使用continue
number = 1
while number <= 5:
number += 1
if number % 2 == 0:
continue
print(number)
# 3
# 5
#首先创造一个待验证的用户列表
#和一个用来存储已经验证完的用户列表
unconfirmed_users = ['a', 'b', 'c']
confirmed_users =[]
#验证每个用户,如果用户通过验证,移到另一个列表
while unconfirmed_users:
t = unconfirmed_users.pop()
print('Verifying users: '+ t.title())
confirmed_users.append(t)
#显示所有已验证的用户
print('\nThe following users are confirmed: ')
for confirmed_user in confirmed_users:
print(confirmed_user.title())
# Verifying users: C
# Verifying users: B
# Verifying users: A
# The following users are confirmed:
# C
# B
# A
#删除包含特定值的所有列表元素 remove()
pets = ['a', 'b', 'c']
while 'b' in pets:
pets.remove('b')
print(pets)
#['a', 'c']
#使用用户输入来填充字典
responses = {}
#设置一个标志,来判断是否继续
Flag = True
#输入调查者的名字和答案
while Flag:
name = input('\nPlease put your name:')
answer = input("\nPlease put your answer:")
responses[name] = answer
#看是否还有人要回答
repeat = input("\nDo you want to answer?yes/no")
if repeat == 'no':
Flag = False
print("\n Results:")
for name,answer in responses.items():
print(name + "'s answer is " + answer + ".")
P16:
#显示简单的问候语
def greet_users():
print('hello world!')
greet_users()
#hello world!
#向函数传递信息
def greet_users(username):
print('Hello ' + username + '!')
greet_users('Steve')
#Hello Steve!
#传递实参
#位置实参
#显示宠物的信息
def describe_pet(animal_type,animal_name):
print('\nI have a ' + animal_type + '.')
print('My ' + animal_type +"'s name is " + animal_name + '.')
describe_pet('dog','pig')
# I have a dog.
# My dog's name is pig.
#关键字实参
describe_pet(animal_name = 'pig', animal_type = 'dog')
# I have a dog.
# My dog's name is pig.
#默认值
def describe_pet(animal_type,animal_name = 'pig'):
print('\nI have a ' + animal_type + '.')
print('My ' + animal_type +"'s name is " + animal_name + '.')
describe_pet('dog')
# I have a dog.
# My dog's name is pig.
P17:
#返回值 return语句
#返回完整的姓名
def get_formatted_name(first_name, middle_name, last_name):
full_name = first_name + ' ' + middle_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('Hu', '-','Steve')
print(musician)
#Hu - Steve
#让实参变成可选的
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()
musician = get_formatted_name('Hu', 'Steve')
print(musician)
#Hu Steve
#返回字典
def build_person(first_name, last_name):
person = {'first': first_name, 'last':last_name}
return person
musician = build_person('Hu','Steve')
print(musician)
#{'first': 'Hu', 'last': 'Steve'}
#结合使用函数和while循环:
def get_formatted_name(first_name,last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print('\nPlease tell me your name:')
print("(enter 'q' at anytime to quit)")
f_name = input('First name: ')
if f_name == 'q':
break
l_name = input('Last name: ')
if l_name == 'q':
break
full_name = get_formatted_name(f_name,l_name)
print('\nHello ' + full_name + ' !')
# Please tell me your name:
# (enter 'q' at anytime to quit)
# First name: Hu
# Last name: Seve
# Hello Hu Seve !
# Please tell me your name:
# (enter 'q' at anytime to quit)
# First name: q
# >>>
P18:
#传递列表
#向列表中的每位用户问好
def greet_users(names):
for name in names:
msg = 'Hello ' + name + '!'
print(msg)
names = ['a', 'b', 'c']
greet_users(names)
# Hello a!
# Hello b!
# Hello c!
#在函数中修改列表
#先是不修改函数版本
unprinted_names = ['a', 'b', 'c']
completed_names = []
while unprinted_names:
current_name = unprinted_names.pop()
completed_names.append(current_name)
print('\nThe following names have been printed: ')
for completed_name in completed_names:
print(completed_name)
# The following names have been printed:
# c
# b
# a
#使用函数
def fun1(unprinted_names,completed_names):
while unprinted_names:
current_name = unprinted_names.pop()
completed_names.append(current_name)
def fun2(completed_names):
print('\nThe following names have been printed: ')
for completed_name in completed_names:
print(completed_name)
unprinted_names = ['a', 'b', 'c']
completed_names = []
fun1(unprinted_names,completed_names)
fun2(completed_names)
# The following names have been printed:
# c
# b
# a
#禁止函数修改副本
#function_name(list_name[:])
def fun1(unprinted_names,completed_names):
while unprinted_names:
current_name = unprinted_names.pop()
completed_names.append(current_name)
unprinted_names = ['a', 'b', 'c']
completed_names = []
fun1(unprinted_names[:],completed_names)
print(unprinted_names)
# The following names have been printed:
# c
# b
# a
# ['a', 'b', 'c']
P19:
#传递任意数量的形参
def make_pizza(*toppings):
print(toppings)
make_pizza('a', 'b', 'c')
#('a', 'b', 'c')
#结合使用位置实参和任意数量实参
#一个星号代表元组,两个星号代表字典
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,'a', 'b', 'c')
# Making a 16 inch pizza with the following toppings:
# - a
# - b
# - c
#使用任意数量的关键字形参
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_info = build_profile('Hu', 'Steve',
location = 'CN',
Field = 'Finance'
)
print(user_info)
#{'First_name': 'Hu', 'Last_name': 'Steve', 'location': 'CN', 'Field': 'Finance'}
P20:
#将函数存储在模块中
#导入整个模块
import pizza
pizza.make_pizza(16,'a','b')
# Making a 16 inch pizza with the following toppings:
# - a
# - b
#导入特定的函数
from pizza import make_pizza
make_pizza(16,'a','b')
# Making a 16 inch pizza with the following toppings:
# - a
# - b
#使用as给函数指定别名
from pizza import make_pizza as mp
mp(16,'a','b')
# Making a 16 inch pizza with the following toppings:
# - a
# - b
#使用as给模块指定别名
import pizza as p
p.make_pizza(16,'a','b')
# Making a 16 inch pizza with the following toppings:
# - a
# - b
#导入模块中所有函数
#from pizza import *
P21:
创建和使用类
class dog():
""" 创建一个表示小狗的类 """
def __init__(self,name,age):
self.name = name
self.age = age
def sit(self):
模拟小狗蹲下
print(self.name.title() + ' is now sitting.')
def roll_over(self):
""" 模拟小狗打滚"""
print(self.name.title() + ' rolled over.')
my_dog = dog('steve', 6)
print("My dog's name is " + my_dog.name.title() + '.')
print("My dog is " + str(my_dog.age) + ' years old.')
# My dog's name is Steve.
# My dog is 6 years old.
my_dog.sit()
my_dog.roll_over()
# Steve is now sitting.
# Steve rolled over.