-3

The Question is like Write a Python program that will ask the user to input a string (containing exactly one word).

user_input = input('Please Enter a word')
for line in range(len(user_input)):
print(user_input[0: line+1])  

OUTPUT: Please Enter a word DAD MOM. D DA DAD DAD DAD M DAD MO DAD MOM

(Here, i could give two words in input, so how to restrict it to one word)

  • The examples are missing. – lsrggr Mar 21 '21 at 12:47
  • 2
    Welcome to SO. input is a very basic command in python, you can find it in the python doc. Use it then split the result if needed. We cannot answer you if you do not include the code you wrote yet / sample data / and full error messages about your trial to solve this problem, so we can reproduce and help. See MRE here: https://stackoverflow.com/help/minimal-reproducible-example – Malo Mar 21 '21 at 12:56
  • Duplicate of https://stackoverflow.com/q/1450393/5506988 – Mark Mar 21 '21 at 12:59
  • Dear Sir, I have edited now. Please do try this one for me – Syed Tahin Mar 21 '21 at 14:52

1 Answers1

0

You can separate the input into a list (with the separator of a space) like so:

user_input = input('Please Enter a word').split()

With your example, user input now looks like this

user_input = ['DAD', 'MOM', 'D', 'DA', 'DAD', 'DAD', 'DAD', 'M', 'DAD', 'MO', 'DAD', 'MOM']

To get the first word, you would do

user_input[0]

and that would return 'DAD'.

You can detect how many words the user entered through:

len(user_input)

So what you can do is add a check that will ask the user for input again if the user enters more than 1 word:

user_input = input('Please Enter a word').split()
while len(user_input) > 1:
    user_input = input('Please Enter only one word').split()

This will continue running until the user enters a single word.

sortBot
  • 16
  • 3
  • Sir, I meant that, my code is okay according to the task. The question is that i can give the user many inputs like DAD MOM BROTHER SISTER etc. But i want the user to give only one string i.e only one word. – Syed Tahin Mar 21 '21 at 15:56
  • You cannot fully control what the user enters into a command line. For that you would need to implement a GUI text box. What I would suggest you do is to not allow the program to run if the user enters more than 1 word. See my example above – sortBot Mar 21 '21 at 16:09