我需要一个程序从用户(文本)获取1行输入,然后将输出作为文本(我在下面写一个例子)
我试过if但是它只接受一行代码,如果我写了一个没有定义的单词,它会破坏其余的。
class meaning():
def shortcutA (self):
print ("ice cream")
def shortcutB (self):
print ("Choclet cake")
def main():
m = meaning()
if input() == "a":
print("your code is: ")
m.shortcutA()
elif input() == "b":
print("your code is: ")
m.shortcutB()
else :
print ("unrecognized")
print ("Please enter the words :")
if __name__ == "__main__":
main()
我希望当我输入b时结果就像
ice cream
Choclet cake
谢谢。
我们可以使用for循环来输入单词中的输入。
class meaning():
def shortcutA (self):
print ("ice cream")
def shortcutB (self):
print ("Choclet cake")
def main():
m = meaning()
print_flag = False
for i in input():
if i in ['a', 'b'] and not print_flag:
print("your code is: ")
print_flag = True
if i == "a":
m.shortcutA()
elif i == "b":
m.shortcutB()
elif i == ' ':
continue
else :
print ("unrecognized")
print ("Please enter the words :")
if __name__ == "__main__":
main()
生产:
Please enter the words :
your code is:
ice cream
Choclet cake
您需要修改if
输入语句。如果你想根据输入用空格分隔输出,那么使用:
for x in input():
if(x=='a'):
print(m.shortcutA(),end=' ')
if(x=='b'):
print(m.shortcutB(),end=' ')
else:
print('unrecognised!')
希望这可以帮助..
我建议像这样的程序,
class meaning():
def shortcutA(self):
return "ice cream"
def shortcutB(self):
return "Chocolet cake"
def main():
m = meaning()
code = ''
for alphabet in user_input:
if alphabet == "a":
code += ' ' + m.shortcutA()
elif alphabet == "b":
code += ' ' + m.shortcutB()
if len(code) == 0:
print 'Unrecognized.'
else:
print 'The code is : ' + code
user_input = raw_input('Please enter the words : \n')
if __name__ == "__main__":
main()