我正在尝试创建一个代码库,我可以在其中存储随着时间的推移找到的代码片段并检索它们。到目前为止,这是我的代码。
# Python Code Library User Interface
import sys
class CodeLib:
codes = []
option = ['help (-h)', 'list (-l)', 'import (-i)', 'quit (-q)']
#What does the user want to do?
print "Welcome to the Code Library"
print "What would you like to do? \n %s" % option
choice = raw_input()
print choice
if choice == 'quit' or '-q':
sys.exit()
length = len(choice)
# Getting name of file to import if user chooses import before
# viewing the code list
if choice[0] == 'i':
_file_ = choice[6:length]
elif choice[:2] == '-i':
_file_ = choice[2:length]
# imports file if user chose import before viewing code list
if choice[0:5] == 'import' or choice [0:2] == '-i':
import _file_
# If user chose option other than import at beginning
# then perform option chosen then give ability to do something else
while choice != 'quit' or '-q':
# provides basic help menu
if choice == 'help' or '-h':
print
print '''(list or -l) brings up a list of code snippet names
(import or -i)/file_name brings up the code snippet you chose \n'''
# provides list of code files
elif choice == 'list' or '-l':
print codes
print option[2], "file name"
_file2_ = raw_input()
import _file2_
# imports code file
else:
_file2_ = raw_input()
import _file2_
# Next user option
print "What would you like to do?"
choice = raw_input
现在我知道到目前为止还不完整。但我遇到的问题是无论我作为选择输入什么。程序执行第一个if语句,退出程序。我已经注释掉了第一个if语句并再次尝试。但无论我输入什么作为选择。它在while循环中执行第一个if语句,而我只是陷入循环中。所以我不确定有什么问题,但有人可以帮助我吗?
答案 0 :(得分:7)
“或'-q'”部分检查字符串'-q'是否为false,对于任何非空字符串都是如此。将此行更改为:
if choice == 'quit' or choice == '-q':
答案 1 :(得分:3)
条件choice == 'quit' or '-q'
(和类似的)总是返回True,因为'-q'
传播为True,而(True或Something)始终为True。
你很可能想要像
这样的东西choice == 'quit' or choice == '-q'
或
choice in ['quit', '-q']
答案 2 :(得分:0)
首先,您正在创建一个我不相信标准的对象。通常,您为def func(self,arg):
块中具有class foo:
块的类定义方法。初始化方法由名称__init__(self,args)
表示。请注意,init之前和之后有两个'_'字符。
如果你只想在一个简单的python脚本中运行一些代码,你不需要它在任何块内。你可以这样做:
print "Welcome to the Code Library"
print "What would you like to do? \n %s" % option
choice = raw_input()
print choice
if choice == 'quit' or '-q':
sys.exit()
length = len(choice)
#More code goes here