Python编程:从入门到时间 第七、八章学习笔记

用户输入与while循环

用户输入

  • 函数input( )
name = input("Please enter your name:")
prompt = "If you tell us who you are,we can personalize the message you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("Hello," + name + "!")
  • int( )获取数值输入

函数 int() 将数字的字符串表示转换为数值表示。

age = input("How old are you?")
age = int(age)
age >= 18

Python 2.7,应使用函数 raw_input() 来提示用户输入。

while循环

prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
message = ""	#初始化
while message != 'quit':
	message = input(prompt)
	
	if message != 'quit':
		print(message)

多种情况导致程序结束时定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志。让程序在标志为 True 时继续运行,并在任何事件导致标志的值为 False 时让程序停止运行。

prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
active = True
while active:
	message = input(prompt)
	
	if message != 'quit':
		active =False
	else:
		print(message)
  • break退出循环
  • continue

while循环处理列表与字典

要在遍历列表的同时对其进行修改,可使用 while 循环。

  • 列表间移动元素
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []

while uncomfirmed_users:
	current_user = uncomfirmed_users.pop()
	
	print("Vertifying user:" + current_user.title())
	comfirmed_users.append(current_user)
	
print("\nThe following users have been confirmed:")
for confirmed_user incomfirmed_users:
	print(confirmed_user.title())
  • 删除包含特定值的所有列表元素
numbers = [1,2,3,4,5,6,1,1,1]

while 1 in numbers:
	numbers.remove(1)
  • 使用用户输入填充字典
responses ={}
polling_active = True

while polling_active:
    name = input("\nWhat's your name?")
    response = input("\nwhich m would you like to climb?")

    responses[name] = response

    repeat = input("\nwould you like to repeat?")
    if repeat == 'no':
        polling_active = False

print("\n---Poll Results---")
for name,response in responses.items():
    print(name + response)

函数

函数定义

def greet_user():
	"""显示简单的问候语"""	#文档字符串的注释,用于生成函数文档
	print("Hello!")
	
greet_user()	#函数调用

实参与形参

形参

实参:调用函数时传递给函数的信息。

传递实参

位置实参

def de(a_type,b_type):
	print("")
de(a,b)
  1. 调用函数多次
  2. 位置实参的顺序很重要

关键字实参

关键字实参是传递给函数的名称 — 值对。关键字实参的顺序无关紧要。

def de(a_type,b_type)
	print("")
de(a_type = 'a',b_type = 'b')

默认值

编写函数时,可给每个形参指定默认值。(位置实参,将默认值对应的形参放在最后)

def de(a_type,b_type = 'b'):
	print("")
de(a_type = 'a')

返回值

返回简单值

def get_formatted_name(first_name,last_name):
	"""返回整洁的姓名"""
	full_name = first_name + ' ' + last_name
	return full_name.title()
	
musician = get_formatted_name('jimi','hendrix')
print(muscician)

调用返回值的函数时,需要提供一个变量,用于存储返回的值。

实参变成可选

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('jimi','hendrix')
print(musician)

musician = get_formatted_name('john','hooker','lee')
print(musician)

返回字典

def build_person(first_name, last_name, age=''):
	"""返回一个字典,其中包含有关一个人的信息"""
	person = {'first': first_name, 'last': last_name}
	if age:
		person['age'] = age
	return person

musician = build_person('jimi', 'hendrix', age=27)
print(musician)

结合使用函数与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 any time to quit)")
	
	f_name = input("first name:")
	if f_name == 'q':
		break
		
	l_name = input("last name:")
	if l_name == 'q':
		break
	formatted_name = get_formatted_name(f_name,l_name)
	print("\nHello, " + formatted_name +"!")

传递列表

def greet_users(names):
	"""向列表中每位用户都发出简单的问候"""
	for name in names:
		msg = "Hello," + name.title() +"!"
		print(msg)
usernames = ['hannah','ty','margot']
greet_users(usernames)

在函数中修改列表

列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的。

def print_models(unprinted_designs, completed_models):
	"""
	模拟打印每个设计,直到没有未打印的设计为止
	打印每个设计后,都将其移到列表completed_models中
	"""
	while unprinted_designs:
		current_design = unprinted_designs.pop()
		# 模拟根据设计制作3D打印模型的过程
		print("Printing model: " + current_design)
		completed_models.append(current_design)
		
def show_completed_models(completed_models):
	"""显示打印好的所有模型"""
	print("\nThe following models have been printed:")
	for completed_model in completed_models:
		print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)		

每个函数都应只负责一项具体的工作。第一个函数打印每个设计,而第二个显示打印好的模型;这优于使用一个函数来完成两项工作。

禁止函数修改列表

向函数传递列表的副本而不是原件。切片表示法 [:]创建列表的副本function_name(list_name[:])

传递任意数量的实参

def make_pizza(*toppings):
	""""打印顾客的所有配料"""
	print(toppings)
	
make_pizza('p1')
make_pizza('p1','p2','p3')

形参名 *toppings中的*让Python创建一个名为 toppings 的空元组,并将收到的所有值都封装到这个元组中。

结合使用位置实参和任意数量实参

要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

使用任意数量的关键字实参

函数编写成能够接受任意数量的键 — 值对。

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'
							filed = 'physics')
							
print(user_profile)

形参**user_info 中的**让Python创建一个名为 user_info 的空字典,并将收到的所有名称 — 值对都封装到这个字典中。

混合使用位置实参、关键字实参和任意数量的实参。

将函数存储在模块中

将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。 import 语句允许在当前运行的程序文件中使用模块中的代码。

导入整个模块

模块是扩展名为.py的文件,包含要导入到程序中的代码。import将代码复制到导入的程序中。

调用被导入的模块中的函数,可指定导入的模块的名称函数名 ,并用句点分隔它们。

import pizza

pizza.make_pizza(16,'p1')

导入特定函数

from module_name import function_0,function_1,function_2
from pizza import make_pizza

make_pizza(16,'p1')	#不需要再使用模块名

使用as给函数指定别名

导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名。

from pizza import make_pizza as mp
mp(16,'p1')	 #直接使用别名

使用as给模块指定别名

import pizza as p
p.make_pizza(16,'p1')

导入模块中所有函数

使用*可以导入模块中所有函数。

from pizza import *
make_pizza(16,'p1')	#直接通过函数名调用函数

使用并非自己编写的大型模块时,最好不要采用这种导入方法:如果模块中有函数的名称与你的项目中使用的名称相同,多个名称相同的函数或变量会覆盖函数。

函数编写指南

  1. 函数和模块指定描述性名称,且只在其中使用小写字母和下划线
  2. 每个函数都应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字符串格式
  3. 形参指定默认值时,等号两边不要有空格。函数调用中的关键字实参,也应遵循这种约定。
def function_name(parameter_0,parameter_1='default value')
function_name(value_0,parameter_1='value')
  1. 函数代码行太长可在函数定义中输入左括号后按回车键,并在下一行按两次Tab键,从而将形参列表和只缩进一
    层的函数体区分开来。
def function_name (
		parameter_0 , parameter_1 , parameter_2 ,
		parameter_3 , parameter_4 , parameter_5 ):
	function body...
  1. 程序或模块包含多个函数,可使用两个空行将相邻的函数分开
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值