Python3:基本语法之四(输入、循环、函数)

本文详细介绍了Python编程的基础知识,包括如何接收用户输入、处理数值输入、使用循环结构、定义和调用函数、处理列表和字典,以及如何导入和使用模块。通过实际代码示例,读者可以了解Python的基本语法和常用功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用户输入

message = input("Tell me something, and I will repeat it back to you: ")
print(message)

函数 input() 接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。

Tell me something, and I will repeat it back to you:  Hello everyone!
Hello everyone!

使用 int() 来获取数值输入

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

使用while循环

current_number = 1
while current_number <= 5:
	print(current_number)
	current_number += 1

使用 break 退出循环

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
	city = input(prompt)
	if city == 'quit':
		break
	else:
		print("I'd love to go to " + city.title() + "!")

在循环中使用 continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用 continue 语句,它不像 break 语句那样不再执行余下的代码并退出整个循环。

current_number = 0
while current_number < 10:
	current_number += 1
	if current_number % 2 == 0:
		continue
	print(current_number)

删除包含特定值的所有列表元素

pets  = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
	pets.remove('cat')

print(pets)

输出结果:

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

函数

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')

输出结果:

I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.

关键字实参

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')

默认值

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')

返回值

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(musician)

返回字典

函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。

def build_person(first_name, last_name):
	person = {'first': first_name, 'last': last_name}
	return person

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

传递列表

def greet_users(names):
	for name in names:
		msg = "Hello, " + name.title() + "!"
		print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

输出结果:

Hello, Hannah!
Hello, Ty!
Hello, Margot!

在函数中修改列表

在函数中对这个列表所做的任何修改都是永久性的。

def print_models(unprinted_designs, completed_models):
	while unprinted_designs:
		current_design = unprinted_designs.pop()
		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('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

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

必须将该形参放在形参 *toppings的前面。

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')

输出结果:

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- 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)

输出结果:

{'first_name': 'albert', 'last_name': 'einstein',
'location': 'princeton', 'field': 'physics'}

导入整个模块

只需编写一条 import 语句并在其中指定模块名,就可在程序中使用该模块中的所有函数。

导入模块中的特定函数

from  module_name import  function_name

通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数:

from  module_name import  function_0 ,  function_1 ,  function_2

使用 as 给函数指定别名

如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名——函数的另一个名称,类似于外号。

from pizza import make_pizza as mp

使用 as 给模块指定别名

import pizza as p

导入模块中的所有函数

使用星号"*"运算符可让Python导入模块中的所有函数:

from pizza import *

使用并非自己编写的大型模块时,最好不要采用这种导入方法:如果模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果:Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。最佳的做法是,要么只导入你需要使用的函数,要么导入整个模块并使用句点表示法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

R-QWERT

你的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值