-1

I need the code to ask the user to enter a word and print them out in a sentence once stop is entered. I have the following code:

`a = input("Enter a word: ")
 sentence = () 
 while a != ("stop"):
 sentence = sentence , a
 a = input("Enter a word: ")
 print (sentence)`

However I don't know how to set the variable 'Sentence' so that nothing prints at the start. How can I rectify this?

Kth
  • 1
  • 1
  • 4
  • Can you explain a bit better what you would like to do? – Daniel Dec 05 '15 at 14:52
  • I want the program to prompt the user to enter words until the word "stop" is entered. As the words are entered they should be added to the variable 'sentence'. When the loop finishes due the word "stop" being entered, the variable 'sentence' should be printed. – Kth Dec 05 '15 at 15:02
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – ruohola May 04 '19 at 14:21

2 Answers2

1

In order to get a string, you need to use raw_input() instead input() (input saves as int, double etc...).

Replace input() to raw_input().

In addition, sentence = () - saves tuple and sentence = sentence , a - adds more tuples and not a string as i think you want.

Try to explain again what you mean.

Omer Paz
  • 21
  • 8
  • I want the program to prompt the user to enter words until the word "stop" is entered. As the words are entered they should be added to the variable 'sentence'. When the loop finishes due the word "stop" being entered, the variable 'sentence' should be printed. – Kth Dec 05 '15 at 15:11
  • Yes I do want a string and not a tuple. How can I do this? – Kth Dec 05 '15 at 15:39
  • Do sentence = "" and sentence += a. – Omer Paz Dec 05 '15 at 16:00
0

You can try the following:

a = input("Enter a word: ")
sentence = "" 
while a != "stop":
    sentence = sentence + " " + a
    a = input("Enter a word: ")
print (sentence)

input (raw_input in python 2) will allow you to write strings without the need for quotes. Sentence has to be initialized to an empty string "", and concatenated as a string (here with a simple + ).

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Daniel
  • 11,332
  • 9
  • 44
  • 72
  • If the initial space bothers you, you can use `print (sentence[1:])` to skip it. – Daniel Dec 05 '15 at 15:16
  • 'raw_input' is not defined in my version of python. I am using python 3.3.2. – Kth Dec 05 '15 at 15:41
  • I have used 'input' instead of 'raw_input' and it has worked. Thank you for your help. – Kth Dec 05 '15 at 15:43
  • True, there is an answer for that here [raw_input python 3](http://stackoverflow.com/questions/954834/how-do-i-use-raw-input-in-python-3-1) – Daniel Dec 05 '15 at 15:52