Python 循环的问题:`for` 和 `while`

问题描述 投票:0回答:1

编写一个程序来调查用户的梦想假期。编写类似于以下内容的提示:如果您可以访问世界上的一个地方,您会去哪里? 包含一段打印民意调查结果的代码。

# 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
循环在这里没有给出所需的结果?也许我不明白
for
while
循环之间的真正区别。

我花了大约30分钟试图解决这个问题,终于解决了。但是,我无法理解为什么

while
循环在这里给出错误,而
for
循环却完美运行。如果我的问题看起来太简单,我很抱歉,因为我大约一周前才开始编码。

python loops for-loop while-loop
1个回答
0
投票

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}")
© www.soinside.com 2019 - 2024. All rights reserved.