以下是根据用户输入创建HTTP或FTP连接的代码。 if和elif条件总是以某种方式评估为FALSE。输入1和0两个打印'抱歉,错误答案'。
domain = 'ftp.freebsd.org'
path = '/pub/FreeBSD/'
protocol = input('Connecting to {}. Which Protocol to use? (0-http, 1-ftp): '.format(domain))
print(protocol)
input()
if protocol == 0:
is_secure = bool(input('Should we use secure connection? (1-yes, 0-no): '))
factory = HTTPFactory(is_secure)
elif protocol == 1:
is_secure = False
factory = FTPFactory(is_secure)
else:
print('Sorry, wrong answer')
import sys
sys.exit(1)
connector = Connector(factory)
try:
content = connector.read(domain, path)
except URLError as e:
print('Can not access resource with this method')
else:
print(connector.parse(content))
输出:
Connecting to ftp.freebsd.org. Which Protocol to use? (0-http, 1-ftp): 0 0 Sorry, wrong answer $ python abstractfactory.py Connecting to ftp.freebsd.org. Which Protocol to use? (0-http, 1-ftp): http http Sorry, wrong answer $ python abstractfactory.py Connecting to ftp.freebsd.org. Which Protocol to use? (0-http, 1-ftp): 1 1 Sorry, wrong answer $
请指教。我在这做错了什么? 感谢。
答案 0 :(得分:3)
Python 3中的输入,它看起来像你正在使用,以字符串形式出现。您需要通过int()
强制转换它(尽管这需要在输入错误的情况下谨慎处理并进行异常处理),以便将其与整数进行比较。
答案 1 :(得分:0)
Python input()将输入作为Unicode字符串,您需要显式地将输入作为整数与0比较,
if int(input) == 0:
# Do something
elif int(input) == 1:
# Do something