下面的代码正在运行,但是当我试图退出代码时,它会进入无限循环,即使我输入 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
