python简单范例01

范例一:
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
	pets.remove('cat')
	print(pets)
print("###")
print(pets)
范例二:
responses = {}
polling_active = True
while polling_active:
	name = input("\nWhat is your name?")
	response1 = input("Which mountain would you like to climb someday? ")
	responses[name] = response1
	repeat = input("Would you like to let another person respond?(yes/no) ")
	if repeat == 'no':
		polling_active = False
		
print("\n---Poll Results ---")
for name,respon in responses.items():
	print(name + "would like to climb" + respon + ".")
范例三
sandwich_orders = ['tudou','doufu','kaoya']
finished_sandwiches = []
while sandwich_orders:
	sandwich_target = sandwich_orders.pop()
	print("I made your tuna sandwich:" + sandwich_target)
	finished_sandwiches.append(sandwich_target)
	
print(finished_sandwiches)

 

范例四:函数传参

#coding:gbk
def greet_user(username):
	#"""显示简单的问候语"""
	print("Hello, " + username.title() + "!")
	
greet_user('lihua')

范例五:函数位置实参|多次调用

#coding:gbk
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')
describe_pet('dog','willie')

范例六:函数关键字实参

#coding:gbk
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(animal_type = 'hamster',pet_name = 'harry')

 

范例七:函数的默认值 【默认形参不能在函数形参的第一位】

#coding:gbk
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')



#【由于显式地给animal_type 提供了实参,因此Python将忽略这个形参的默认值。】
describe_pet(pet_name='harry', animal_type='hamster')

范例七:函数返回值

#coding:gbk
def get_formatted_name(first_name,last_name):
	#返回整洁的姓名
	full_name = first_name + ' ' + last_name
	return full_name.title()
	
musician = get_formatted_name('yin','zitao')
print(musician)

范例八:对函数实参的有无进行判断

#coding:gbk
def get_formatted_name(first_name,last_name,middle_name=''):
	#返回整洁的姓名
	if middle_name:
		full_name = first_name + ' ' + middle_name + ' ' + last_name
		return full_name.title()
	else:
		full_name = first_name + ' ' + last_name
		return full_name.title()
	
musician = get_formatted_name('yin','tao','zi')
print(musician)

 

范例九:使用函数构建字典

#coding:gbk
def build_person(first_name,last_name):
	#返回一个字典,其中包含有关一个人的信息
	person = {'first':first_name,'last':last_name}
	return person
	
musician = build_person('jimi','hendrix')
print(musician)



#例二
#coding:gbk
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','23')
print(musician)

 

范例十:while循环与函数结合使用

#coding:gbk
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 + "!")

 

范例十一:使用函数遍历列表

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

 范例十二:在函数中修改列表

#coding:utf-8
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []

#模拟打印每个设计,直到没有未打印的设计为止
#打印每个设计后,都将其移到列表completed_models中

while unprinted_designs:
	current_design = unprinted_designs.pop()
	
	#模拟根据设计制作3D打印模型的过程
	print("Printing model: " + current_design)
	completed_models.append(current_design)
	
#显示打印好的所有模型
print("\nThe following models have been printed: ")
for completed_model in completed_models:
	print(completed_model)


#范例二
#coding:utf-8
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)



#切片开辟新的空间
#coding:utf-8
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 = []
unprinted_designs1 = unprinted_designs[:]
print_models(unprinted_designs,completed_models)
show_completed_models(unprinted_designs1)


#向函数传递列表副本,列表本身没有改变
#coding:utf-8
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 = []
unprinted_designs1 = unprinted_designs[:]
print_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)

 

范例十三:【函数接收多个传参*】

#coding:utf-8
def make_pizza(*toppings):
	#打印顾客点的所有配料
	print(toppings)
	
make_pizza('latiao','xiaoyugan','douya')


##遍历元组
#coding:utf-8
def make_pizza(*toppings):
	#打印顾客点的所有配料
	print("\nMaking a pizza with the following toppings:")
	for topping in toppings:
		print("-" + topping)
	
make_pizza('latiao','xiaoyugan','douya')


##函数同时接收实参、位置参数和多个形参
#coding:utf-8
def make_pizza(size,*toppings):
	#打印顾客点的所有配料
	print("\nMaking a " + str(size) + " -inch pizza with the following toppings:")
	for topping in toppings:
		print("-" + topping)
	
make_pizza('5','latiao','xiaoyugan','douya')



###函数接收多个参数,包括实参、形参,且将未知形参内容存储到字典中
#coding:utf-8
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)

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫是一种使用Python编程语言来获取网站上的数据的技术。下面是一个Python爬虫的范例: ```python # 导入所需的库 import requests from bs4 import BeautifulSoup # 发送HTTP请求并获取网页内容 url = 'https://www.example.com' # 设置要爬取的网页URL response = requests.get(url) # 发送HTTP请求并获取响应 html_content = response.text # 获取响应的文本内容 # 使用BeautifulSoup库解析网页内容 soup = BeautifulSoup(html_content, 'html.parser') # 创建BeautifulSoup对象 # 解析网页内容并提取所需的数据 data = soup.find('div', class_='data') # 假设要提取的数据在一个具有'data'类的<div>标签中 data_text = data.get_text() # 获取该<div>标签的文本内容 # 将提取的数据保存到本地文件或数据库 with open('data.txt', 'w') as file: file.write(data_text) # 打印提取的数据 print(data_text) ``` 上述范例首先使用`requests`库发送HTTP请求,并获取目标网页的HTML内容。接下来,使用`BeautifulSoup`库创建一个BeautifulSoup对象,并指定解析器为'html.parser'。然后,通过调用BeautifulSoup对象的`find()`方法来找到具有'data'类的`<div>`标签,并使用`get_text()`方法获取其中的文本内容。最后,可以选择将提取的数据保存到本地文件或数据库,并打印输出以便查看结果。 请注意,这只是一个简单的示例,实际的爬虫可能需要处理更复杂的网页结构、使用不同的解析器、处理JavaScript和动态内容等。同时,使用爬虫时应遵守网站的访问规则,并尊重合法权益。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值