gpt4 book ai didi

python - 我在 Python 中编写了一段代码,即使我正在使用 break 语句并继续它仍然会进入 Python : 中的无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:41 25 4
gpt4 key购买 nike

下面的代码正在运行,但是当我试图退出代码时,它会进入无限循环,即使我输入 1 仍然不会跳出循环。我是 Python 的初学者,有人可以帮助我吗??

这是我的代码,

import urllib2
import sys

urlToRead = ('https://www.google.com')

crawledWebLinks = {}

while urlToRead !='':
try:
urlToRead = raw_input('Please enter the Next weblink to crawl')
if urlToRead == '':
print ('Ok Existing the Loop')
break
shortName = raw_input('Please enter a short Name for the Url to Read ' + urlToRead)
webfile = urllib2.urlopen(urlToRead).read()
crawledWebLinks[shortname] = webfile
except:
print (sys.exc_info()[0])
stopOrproceed = raw_input('You want to Stop or Continue, Please type in 1 to stop or anything else to Continue')
if stopOrproceed == 1:
print ('Okies we are stopping')
break
else:
print ('lets continue')
continue


print (crawledWebLinks.keys())

最佳答案

以下几行是导致问题的行,

stopOrproceed = raw_input('You want to Stop or Continue, Please type in 1 to stop or anything else to Continue')
if stopOrproceed == 1:
print ('Okies we are stopping')
break

您会看到 raw_input 获取输入并将其存储为字符串。所以在从用户那里获得值(value)之后。您的 stopOrproceed 变量将具有 "1"

当您检查 stopOrproceed==1 时 --> "1"==1。这在 Python 中绝对不相等。所以总是计算 false 因此控制永远不会进入 if 并且因此你永远不会 break

试着把它改成这样,

if stopOrproceed == "1":
print ('Okies we are stopping')
break

关于python - 我在 Python 中编写了一段代码,即使我正在使用 break 语句并继续它仍然会进入 Python : 中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44941067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com