Python 制作括号程序?我卡住了
这是Python。我正在尝试编写一个程序,要求用户在不使用全局变量的情况下输入字符串。如果字符串只有并排的括号,那么它是偶数。如果它有字母、数字或括号隔开,那么它是不均匀的。例如,and和是偶数,而and和pie和非偶数。下面是我到目前为止写的内容。我的程序一直在无限次地打印“输入字符串”,我现在被这个问题困住了Python 制作括号程序?我卡住了,python,loops,recursion,input,parentheses,Python,Loops,Recursion,Input,Parentheses,这是Python。我正在尝试编写一个程序,要求用户在不使用全局变量的情况下输入字符串。如果字符串只有并排的括号,那么它是偶数。如果它有字母、数字或括号隔开,那么它是不均匀的。例如,and和是偶数,而and和pie和非偶数。下面是我到目前为止写的内容。我的程序一直在无限次地打印“输入字符串”,我现在被这个问题困住了 selection = 0 def recursion(): #The line below keeps on repeating infinitely. myString =
selection = 0
def recursion():
#The line below keeps on repeating infinitely.
myString = str(input("Enter your string: "))
if not myString.replace('()', ''):
print("The string is even.")
else:
print("The string is not even.")
while selection != 3:
selection = int(input("Select an option: "))
#Ignore this.
if selection == 1:
print("Hi")
#This won't work.
elif selection == 2:
def recursion():
recursion()
这将输出正确的偶数/非偶数答案
selection = 0
def recursion():
myString = str(raw_input("Enter your string: ")) #Use raw_input or ( ) will be ()
paren = 0
for char in myString:
if char == "(":
paren += 1
elif char == ")":
paren -= 1
else:
print "Not Even"
return
if paren < 0:
print "Not even"
return
if paren != 0:
print "Not even"
return
print "Even"
return
while selection != 3:
selection = int(input("Select an option: "))
#Ignore this.
if selection == 1:
print("Hi")
#This won't work.
elif selection == 2:
recursion() #This isn't a recursive function - naming it as so is...
除非您使用的是Python3,否则您应该使用原始输入而不是输入,因为输入以与输入最匹配的任何类型返回结果,而原始输入总是返回字符串。在Python3中,输入总是返回一个字符串。还有,为什么要重新定义递归?从elif语句中调用它。例如:
selection = 0
def recursion():
#The line below keeps on repeating infinitely.
myString = raw_input("Enter your string: ") # No need to convert to string.
if not myString.replace('()', ''):
print("The string is even.")
else:
print("The string is not even.")
while selection != 3:
selection = int(raw_input("Select an option: "))
#Ignore this.
if selection == 1:
print("Hi")
#This won't work.
elif selection == 2:
recursion() # Just call it, as your program already
# recurs because of the if statement.
什么是def recursion:elif选择项下的递归==2。我的程序一直无限次地打印“输入字符串”。有趣的是,当我运行它时,它会一直打印选择一个选项:无限直到我输入3。这是您最新的代码吗?我不知道你怎么能达到输入字符串的提示。根据Kevin和我在运行你的程序时得到的结果,在我看来,如果你在elic selection==2:下取出def递归,然后放入递归,一切都会正常。剩下的就是修复递归中的if语句,以完成您希望它完成的任务