编写一个程序来调查用户的梦想假期。编写类似于以下内容的提示:如果您可以访问世界上的一个地方,您会去哪里? 包含一段打印民意调查结果的代码。
# Empty dictionary where we'll store the results of the poll.
poll = {}
polling_active = True
while polling_active:
prompt_1 = "\nWhat is your name? "
response_1 = input(prompt_1)
prompt_2 = "If you could visit one place in the world, where would you go? "
response_2 = input("Hello" + " " + response_1 + "!" + " " + prompt_2)
# store name/place in dictionary.
poll[response_1] = response_2
prompt_3 = "Would you like to let another person respond? (yes/no) "
response_3 = input(prompt_3)
while response_3 == 'yes':
# if response_3 == 'no':
polling_active = True
print(f"\n {poll}")
我注意到在这种情况下程序无法编译(我的意思是当行
if response_3 == 'no':
被注释掉时)。但是,如果我取消注释并注释掉 while response_3 == 'yes':
行,它就可以正常工作。我对此很困惑。谁能向我解释为什么 while
循环在这里没有给出所需的结果?我不明白为什么“if”在这里不起作用,但“while”却起作用。
我花了大约30分钟试图解决这个问题,终于解决了。但是,我无法理解为什么
while
循环在这里给出错误,而 if
工作得很好。如果我的问题看起来太简单,我很抱歉,因为我大约一周前才开始编码。
for
循环旨在循环遍历序列(如列表或数字序列),而while
循环旨在不断重复代码,直到它检查的条件不再为真(在本例中为当response_3 == 'yes'
时) 。我假设您为 response_3
提供的测试输入是 yes
。对于 while
循环情况,条件 response_3 == 'yes'
为 true,因此进入循环,但会处于无限循环状态,因为 if 条件检查 if response_3 == 'no'
始终为 false。该代码在唯一 if response_3 == 'no'
情况下有效,因为它不会陷入无限循环,并将继续上层 while
循环中的下一次迭代
我假设你的目标是如果
while
等于while polling_active
则退出上层response_3
循环(no
),在这种情况下,你只需要删除下层while
语句并保留if
语句但将里面的代码改为polling_active = False
,这样上面的while循环中的条件就会为假并退出循环
# Empty dictionary where we'll store the results of the poll.
poll = {}
polling_active = True
while polling_active:
prompt_1 = "\nWhat is your name? "
response_1 = input(prompt_1)
prompt_2 = "If you could visit one place in the world, where would you go? "
response_2 = input("Hello" + " " + response_1 + "!" + " " + prompt_2)
# store name/place in dictionary.
poll[response_1] = response_2
prompt_3 = "Would you like to let another person respond? (yes/no) "
response_3 = input(prompt_3)
if response_3 == 'no':
polling_active = False
print(f"\n {poll}")
创建一个 while 循环,以便如果用户想要给出另一个响应,可以询问相同的问题。
如果 while 条件需要执行循环过程,则创建一个变量 i,其初始值为 0。要继续循环,应该有像
i += 1
这样的行
while 循环以
while polling_active == True:
开始。因此,如果用户不想给出其他响应,则 if statement
应为 if if response_3 == 'no': polling_active == False
。只有这样循环才会停止。现在检查您的代码。你会找到 while 循环不起作用的原因。
poll = {}
polling_active = True
i = 0
while polling_active:
prompt_1 = "\nWhat is your name? "
response_1 = input(prompt_1)
prompt_2 = "If you could visit one place in the world, where would you go? "
response_2 = input("Hello" + " " + response_1 + "!" + " " + prompt_2)
poll[response_1] = response_2
prompt_3 = "Would you like to let another person respond? (yes/no) "
response_3 = input(prompt_3)
if response_3 == 'no':
polling_active = False
i += 1