[Tutor] Help

Dave Angel davea at davea.name
Wed Mar 20 21:53:19 CET 2013


On 03/20/2013 03:57 PM, travis jeanfrancois wrote:
> Hello, I am a beginning python student and I am having trouble with a
> program I am writing  . The problem requires me to use "while" and that I
> create a function that allows the user to a create sentence by  inputing  a
> string and to end the sentence with a  period meaning inputing "." .The
> problem is while keeps overwriting the previuos input and it still asks for
> a string even after it prints out  .
>
> Here is the output I am getting
>
>
> Enter the first word in your sentence: I
> Enter the next word in your sentence: am
> Enter the next word in your sentence: a
> Enter the next word in your sentence: novice
> Enter the next word in your sentence: .
>     I . .
> Enter the next word in your sentence:
>
>
> Here is the desired output:
>                                                                :
> Enter the first word in your sentence: I
> Enter the next word in your sentence: am
> Enter the next word in your sentence: a
> Enter the next word in your sentence: novice
> Enter the next word in your sentence: .
> I am a novice.
>
> Here is my code:
>
>
>
>
>
> def B1():
>   #Creates a function called B1
>   period = "."
>   # The variable period is assigned
>   first = input("Enter the first word in your sentence ")
>   #The variable first is assigned
>   next1 = input("Enter the next word in you sentence or enter period:")
>   #The variable next 1 is assigned
>
>   # I need store the value so when while overwrites next1 with the next
> input the previous input is stored and will print output when I call it
> later along with last one
>   # I believe the solution is some how implenting this expression x = x+
> variable

You need a new variable that accumulates the whole sentence.  I'd use a 
list, but many people would use a string.  Since I don't know what 
concepts you know yet, I'll stick to string here.  Anyway, you have to 
initialize it before the loop, and then you can print it after the loop.

sentence = ""

>
>   while  next1 != (period) :
>
>      next1  = input("Enter the next word in you sentence or enter period:")

At this point, add the word to the sentence.
>
>      if next1 == (period):
>          next1 = next1 + period
>          print ("Your sentence is:",first,next1,period)

No need for these three lines inside the loop, since the loop will end 
when next1 is equal to the period.  So put the print after the end of 
the loop, and I'll let you figure out what it should print.

>
> PS : The" #"  is I just type so I can understand what each line does
>
>

-- 
DaveA


More information about the Tutor mailing list