请教各位大神,python初学者的三个问题:有关一些基本的方法(目前学到python编程从入门到实践第7章)(已解决)
刚刚学习书上7.3的内容,有些疑惑,希望大神们能帮忙解答一下!谢谢!
第一个问题:是不是经历过while过后,sandwich_orders就与最初的sandwich_orders不同了
sandwich_orders = ['pastrami','tuna','pastrami','sausage','lemon','pastrami','tuna','lemon']
finished_sandwiches = []
print("Pastrami is already sold out.")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
finished_sandwiches = sandwich_orders
for finished_sandwich in finished_sandwiches:
print(finished_sandwich)
第二个问题:finished_sandwiches.append(sandwich)在此是个什么含义?我能否用其他方式来表达?
sandwich_orders = ['吞拿鱼三明治','火腿肠三明治','金枪鱼三明治']
finished_sandwhiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop()
print(f"I made your {sandwich}.")
finished_sandwhiches.append(sandwich)
for finished_sandwhich in finished_sandwhiches:
print(finished_sandwhich)
第三个问题:为什么运行时会先问我What is your name等我做出回答才会有下一个问题出现,而不是两个问题一起呈现?responses[name] = response是什么意思?
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(f"{name} would like to climb {response}.")
remove()
方法用于移除列表中某个值的第一个匹配项。经历过while
过后,sandwich_orders
列表中所有'pastrami'
的项目都会被移除。append()
方法用于在列表末尾添加新的对象。相当于从sandwich_orders
取走最后一个元素, 放到finished_sandwhiches
最后一个元素, 其结果会反过来排列。input
函数会阻塞代码的执行, 直到输入完成, 才继续下一句代码 。response
是一个字典变量,responses [name] = response
是向字典添加新内容的方法, 增加新的或修改键/值对。