内容关于用户输入,while循环以及函数
今天所学内容部分需要输入,所以不附运行结果,欢迎大家自己尝试
以下内容为用户输入和while循环
# input()工作原理,本质是输入字符串
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
name = input("Please enter your name: ")
print("Hello, " + name + "!")
# int()工作原理,本质是将输入视为数值
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enough to ride! ")
else:
print("\nYou'll be able to ride when you're a little older.")
# 求模运算符%,省略
# 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,满足条件时不再执行接下里的程序,进入下一循环
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
以下内容为函数
# 向函数传递信息
def greet_user(username):
# 形参username
print("Hello, " + username.title() + "!")
greet_user('jesse') # 实参'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') # 位置实参,最基本的是基于实参顺序,不能随意调换
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 get_formatted_name(first_name, middle_name, last_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','lee','hendrix')
print(musician)
# 返回字典
def build_person(first_name, last_name):
person = {'first':first_name, 'last':last_name}
return person
person = build_person('jimi', 'hendrix')
print(person)
# 传递列表
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[:]) #用切片表示法[:]创建列表的副本
# 传递任意数量的实参
# 使用形参名*names,创建一个空元组,放入所有收到的值
# 可以和普通实参结合使用
# 将函数存储在模块中,使用import module_name
# 调用模块中的某个函数,module_name.function_name
# 只导入特定的函数,from module_name import function_1,function 2
# 使用as指定别名,from module import function as anothername;import module as anothername
# 导入模块中所有的函数,from module import *
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。