免费的清晰思维导图见上传资源压缩包,也不需要积分。
目录
1 用户输入
1.1 获取字符串输入:函数input()
使用函数input()获取用户输入时,Python将用户输入解读为字符串。
#只有一条提示信息时
variable_name = input("promt")
print(variable_name)
#有多条提示信息时
promt = "promt_message_01"
promt += "\npromt_message_02"
…
variable_name = input(promt)
print(variable_name)
(1)函数input()让程序暂停运行,等待用户输入文本,并在用户按回车键后继续运行。
(2)函数input()接受一个参数:要向用户显示的清晰且易于明白的提示或说明,让用户知道该输入什么样的信息。
name = input("Please enter your name:") print("Hello," + name + "!")
(3)当提示超过一行时,可将提示存储在一个变量中,再将该变量传递给input()。
prompt = "Tell me your name" prompt += "\nPlease enter:" name=input(prompt) print("\n"+name)
运算符+=在存储在prompt中的字符串末尾附加一个字符串。
**(4)使用函数input()获取用户输入时,Python将用户输入解读为字符串,即使输入的是数字,也不能当数字使用(例如比大小等)。
age = input("How old are you?") >>How old are you? 21 age >= 18 >> File "D:/Pycharm/PyCharm Code/Python_Study_01/test.py", line 7, in <module> age >= 18 TypeError: '>=' not supported between instances of 'str' and 'int'
1.2 获取数值输入:函数int()
使用函数int()将用户输入的字符串转变为数值时,Python将用户输入视为数值。函数int()将数字的字符串表示转换为数值表示。
variable = input(promt)
variable = int(variable)
do something
将输入变为数值表示后可以用作后续与其他数值进行比较,执行所需的相应操作。如下示例:
age=input("How old are you?") age=int(age) if age<3: print("Cute baby!") else: print("Programming should start with children!")
2 求模运算符%
(1)求模运算符%将两数相除并返回余数。
(2)当一个数可以被另一个数整除,余数为0,因此求模运算符将返回0。
4 % 3
>> 1
5 % 3
>>2
6 % 3
>>0
可以应用求模运算符的性质,判断一个数是奇数还是偶数(也可以是其他的条件,比如某个数的整数倍等等),以此来作为条件测试或是循环的条件,以下为示例:
**这里需要先把number转换为数值int()进行比较,再将其转换成字符串str()进行输出。
#even_or_odd.py number = input("Enter a number,and I'll tell you if it's even or odd:") number = int(number) if number % 2 == 0: print("\nThe number " + str(number) + " is even.") else: print("\nThe number " + str(number) + " if odd.") >>Enter a number,and I'll tell you if it's even or odd: 5 The number 5 if odd.
3 while循环
3.1 while循环与for循环
for循环:用于针对集合中每个元素都使用一个代码块
while循环:不断运行,直到指定条件condition不满足为止
#普通while循环
while condition:
statements(do something)
#如果condition为False也有需要执行的代码块时,可以使用else语句执行其他代码块操作
while condition:
statements
else:
statements
3.2 让用户选择何时退出:用户输入与while循环的应用
(1)使用while循环可以让程序在用户愿意时不断运行,若在程序中设置退出值,只要用户输入的不是这个值,程序就接着运行;当用户输入退出值时,跳出while循环。
#初始变量为空,这样才能在开始while循环时有能与condition比较的值
variable = ""
#当用户未输入与退出条件相符合的值时,执行while循环
while variable != quit_condition:
variable = input(promt)
#如果用户输入的值不是退出值,则打印变量;若是退出值,则不打印,结束循环
if variable != quit_condition:
print(variable)
(2)如果不需要程序在结尾输出退出值可以使用if语句,如果不适用该if结构,用户在输入退出值时,退出值也会被打印出来。
if message != 'quit':
print(message)
该if结构程序在显示消息前做简单的检查,仅在消息不是退出值时才打印它。
这里给出一个书中的示例,便于理解。在程序中定义了一个退出值'quit',只要用户输入的不是这个值,程序就能接着运行。
#不加if结构时 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) print(message) >>Tell me something,and I will repeat it back to you: Enter 'quit' to end the program.input Tell me something,and I will repeat it back to you: Enter 'quit' to end the program.quit '''这里用户输入了quit,代码在打印quit后停止循环''' #加if结构 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) >>Tell me something,and I will repeat it back to you: Enter 'quit' to end the program.input Tell me something,and I will repeat it back to you: Enter 'quit' to end the program. '''这里用户输入了quit,代码不打印quit,退出循环'''
3.3 使用标志
(1)在要求很多条件都满足才继续运行的程序中,可以定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为标志。
(2)当标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。
sign = True
while sign:
variable = input(prompt)
if variable == quit_condition:
sign = False
else:
print(variable)
(3)这样做只需要在while中检查标志此时是否为True即可决定是否运行如下循环,并且将所有测试(是否发生了应将标志设置为False的事件)都放在其他地方,从而让程序变得更为整洁。
(4)可以给标志指定任何名称。
使用标志和3.2中所学的内容其实是一样的,在3.2中我们将条件测试放在了while语句中,例如while variable != 'quit',而在3.3中我们创建了一个标志,以此来指出程序是否处于活动状态,这样如果要添加测试(如elif语句)以检查是否发生了其他导致sign变为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)
在复杂的程序中,例如很多事件发生都会导致程序停止运行的游戏中,标志很有用;在其中的任何一个事件导致活动标志变成False时,主游戏循环将退出,此时可显示一条游戏结束消息,并让用户选择是否要重新玩。
3.4 使用break退出循环
(1)使用break语句可以不管条件测试的结果如何,立即退出while循环。
while condition:
statements
if condition:
break
else:
do something
(2)break语句用于控制程序流程,可以使用它来控制哪些代码行将执行,哪些代码行不执行。
(3)在任何Python循环中都可以使用break语句。例如,使用break语句来退出遍历列表或字典的for循环。
3.5 使用continue跳过本次循环
(1)使用break语句将会直接使程序退出整个循环而不执行余下代码,使用continue语句会跳回循环开头,进入下一个循环。
while condition:
statements
if condition:
continue
else:
do something
break跳出整个循环,continue跳过本次循环。
3.6 避免无限循环
(1)如果程序进入无限循环,可以按Ctrl+C停止运行,也可以直接关闭程序输出的终端窗口。如果是内嵌输出窗口的,只能关闭编辑器来结束无限循环。
(2)避免无限循环,需要对每个while循环进行测试,确保按预期结束。如果在测试过程中特定值没有使循环结束,则需要检查程序。
4 使用while循环来处理列表和字典
for循环可以用来遍历,while循环用来遍历并操作。
for循环时一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。
要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
4.1 列表之间移动元素
(1)使用方法pop()从原本的列表中弹出元素,再使用方法append()添加进新列表中。
(2)具体抽象结构见思维导图。
#首先,创建两个列表,此处示例将list_01中的值转入list_02中
list_01 = [value_01,value_02,value_03]
list_02 = []
#将list_01中的所有值都转入list_02中,直到list_01中没有值
while list_01:
variable = list_01.pop()
print("Pop-up value:" + variable)
list_02.append(variable)
#用for循环遍历输出list_02查看移动情况
print("list_02:")
for value in list_02:
print(value)
4.2 删除包含特定值的所有列表元素
(1)使用函数remove()可以删除列表中的特定值,如果列表中有多个需要删除的特定值,可以在循环中使用函数remove()。
(2)函数remove()要求输入需要删除的元素。
list = [value_01,value_02,value_01,value_01]
print(list)
while value_01 in list:
list.remove(value_01)
print(list)
>>[value_01,value_02,value_01,value_01]
[value_02]
4.3 使用用户输入来填充字典
#创建一个空字典
dictionary = {}
#设置一个标志,判断循环是否继续
active = True
while active:
#提示用户输入信息,存放在对应的键-值对中
key = input("\n" + prompt)
value = input(prompt)
#将键-值对存入字典中
dictionary[key] = value
#看看循环是否还需要继续
condition_repeat = input(prompt) '''prompt中可以写例如输入no或quit则退出循环'''
if condition_repeat == 'no': '''这里用no举例,其他的退出条件也可以'''
active = False
#输出结果
print("\n--- Results ---")
for key,value in dictionary.items():
print(key + ":" + value) '''这里举个简单的输出,其他复杂的同理'''
5 课后题
具体题目都在注释中打印出来了。
#课本例题7.1 函数input()的工作原理
print("\n课本例题7-1")
#parrot.py
message = input("Tell me something,and I will repeat it back to you:")
print(message)
#greeter.py
name = input("Please enter your name:")
print("Hello," + name + "!")
promt = "If you tell us who you are,we can personalize the message you see."
promt += "\nWhat is your first name?"
name = input(promt)
print("\nHello," + name + "!")
#rollercoaster.py
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.")
#even_or_odd.py
number = input("Enter a number,and I'll tell you if it's even or odd:")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " if odd.")
#课后习题7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如"Let me see if I can find you a Subaru"
print("\n课后习题7-1")
car = input("What kind of car would you want to rent?")
print("\nLet me see if I can find you a " + car + ".")
#课后习题7-2 餐馆订位:编写一个程序,询问用户有多少人用餐。
#如果超过8人,就打印一条消息,指出没有空桌
#否则指出有空桌
print("\n课后习题7-2")
diner = input("How many people are you having dinner with?")
diner = int(diner)
if diner > 8:
print("\nThere are no empty tables here.")
else:
print("\nThere is an empty table here.")
#课后习题7-3 10的整数倍:让用户输入一个数字,并指出这个数字是否是10的整数倍
print("\n课后习题7-3")
number = input("Enter a number please,and I will go to cheack if it's a multiple of 10:")
number = int(number)
if number % 10 == 0:
print("\n" + str(number) + " is a multiple of 10.")
else:
print("\n" + str(number) + "isn't a multiple of 10.")
#课本例题7.2 while循环
print("\n课本例题7.2")
#counting.py
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
#让用户选择何时退出:用户输入和while循环的结合
#parrot.py
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)
#标志
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退出循环
#cities.py
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跳出本次循环
#counting.py
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
else:
print(current_number)
print(current_number)
#课后习题7-4 比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入'quit'时结束循环
#每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料
print("\n课后习题7-4")
promt = "Please enter the ingredients you want on the pizza:"
ingredient = ""
while ingredient != 'quit':
ingredient = input(promt)
if ingredient != 'quit':
print("We will add " + ingredient + " to the pizza.")
#也可以不要这个else
else:
break
#课后习题7-5 电影票:有家电影院根据观众的年龄收取不同的票价
#不到3岁的观众免费;3~12岁的观众为10美元;超过12岁的观众为15美元
#请编写一个循环,在其中询问用户的年龄,并指出其票价
print("\n课后习题7-5")
prompt = "Please enter your age:"
prompt += "\n(Enter 'quit' when you are finished.)"
age = ""
while age != 'quit':
age = input(prompt)
if age != 'quit':
age = int(age)
if age < 3:
print("Your ticket price is $0.")
elif age <= 12:
print("Your ticket price is $10.")
else:
print("Your ticket price is $15.")
else:
break
#课后习题7-6 三个出口:以另一种方式完成习题7-4和习题7-5,在程序中采取如下所有做法
#在while循环中使用条件测试来结束循环
#使用变量active来控制循环结束的时机
#使用break语句在用户输入'quit'时退出循环
print("\n课后习题7-6")
#课后习题7-4(2)
promt = "Please enter the ingredients you want on the pizza:"
active = True
ingredient = ""
while active:
ingredient = input(promt)
if ingredient != 'quit':
print("We will add " + ingredient + " to the pizza.")
#也可以不要这个else
else:
active = False
break
#课后习题7-5(2)
prompt = "Please enter your age:"
prompt += "\n(Enter 'quit' when you are finished.)"
active = True
age = ""
while active:
age = input(prompt)
if age != 'quit':
age = int(age)
if age < 3:
print("Your ticket price is $0.")
elif age <= 12:
print("Your ticket price is $10.")
else:
print("Your ticket price is $15.")
else:
active = False
break
#课本例题7.3 使用while循环来处理列表和字典
#在列表之间移动元素
print("\n课本例题7.3")
#confirmed_users.py
#首先,创建一个待验证用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
#验证每个用户,直到没有未验证用户为止
#将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user:" + current_user.title())
confirmed_users.append(current_user)
#显示所有已验证用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
#删除包含特定值的所有列表元素
#pets.py
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
#使用用户输入来填充字典
#mountain_poll.py
responses = {}
#设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
#提示输入被调查者的名字和回答
name = input("\nWhat is your name?")
response = input("Which mountain would you like to climb someday?")
#将答卷存储在字典中
responses[name] = response
#看看是否还有人要参与调查
repeat = input("Would you like to let another person respond?(yes/no)")
if repeat == 'no':
polling_active = False
#调查结束,显示结果
print("\n--- Poll Results ---")
for name,response in responses.items():
print(name + " would like to climb " + response + ".")
#课后习题7-8 熟食店:创建一个名为sandwich_orders的列表,在其中包含各种三明治的名字,再创建一个名为finished_sandwiches的空列表
#遍历列表sandwich_orders,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich
#并将其移到列表finished_sandwiches
#所有三明治都制作好后,打印一条消息,将这些三明治列出来
print("\n课后习题7-8")
sandwich_orders = ['chicken sandwich','tuna sandwich','egg sandwich']
finished_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print("I made your " + current_sandwich + ".")
finished_sandwiches.append(current_sandwich)
for finished_sandwich in finished_sandwiches:
print(finished_sandwich.title() + " is already.")
#课后习题7-9 五香烟熏牛肉(pastrami)卖完了:以习题7-8的列表sandwich_orders为基础,并确保'pastrami'在其中至少出现了三次
#在程序开头附近添加这样的代码:
#打印一条消息,指出熟食店的五香烟熏牛肉卖完了
#再使用一个while循环将列表sandwich_orders中的'pastrami'都删除
#确认最终的列表finished_sandwiches中不包含'pastrami'
print("\n课后习题7-9")
sandwich_orders = ['chicken sandwich','pastrami','tuna sandwich','pastrami','egg sandwich''pastrami']
finished_sandwiches = []
print("Pastrami is sold out.")
print(sandwich_orders)
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
if current_sandwich == 'pastrami':
sandwich_orders.remove(current_sandwich)
else:
finished_sandwiches.append(current_sandwich)
print(finished_sandwiches)
#课后习题7-10 梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地
#使用类似于"If you could visit one place in the world,where would you go?"的提示,并编写一个打印调查结果的板块
print("\n课后习题7-10")
#创建一个空字典
favorite_places = {}
#创建一个标志,控制循环是否继续
place_active = True
#创建一个while循环来接受用户输入
while place_active:
#提示用户输入自己梦想的度假胜地
username = input("\nWhat's your name?")
favorite_place = input("If you could visit one place in the world,where would you go?")
#将答案存入字典中
favorite_places[username] = favorite_place
#看看是否还有人要参与调查
repeat = input("Would you like to let another person respond?(yes/no)")
if repeat == 'no':
place_active = False
#调查结束,输出结果
print("\n--- Results ---")
for username,favorite_place in favorite_places.items():
print(username + " want to go to " + favorite_place + ".")