1

I need a program that get a 1 line input from user(text) and then give the output as text(I write an example down below)

I tried for if but it's only accept one line code and if I write a word that is not defined, it ruin the rest.

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()

I expect when I enter a b the result be like

ice cream 
Choclet cake

Thank you.

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
zazuvahe
  • 33
  • 7
  • Possible duplicate of [How to print without newline or space?](https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space) – SuperKogito Apr 14 '19 at 10:55

3 Answers3

1

We can use a for loop to go through the input in a word.

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()

produces:

Please enter the words :
your code is: 
ice cream 
Choclet cake
Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
0

You need to modify your if input statements. If you want output according to input separated by spaces, then use this:

for x in input():
    if(x=='a'):
         print(m.shortcutA(),end=' ')
    if(x=='b'):
         print(m.shortcutB(),end=' ') 
    else:
         print('unrecognised!')

hope this helps..

Bully Maguire
  • 211
  • 3
  • 15
0

I would suggest a program like this,

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()