[Tutor] Help

Robert Sjoblom robert.sjoblom at gmail.com
Wed Mar 20 21:39:35 CET 2013


> Hello, I am a beginning python student and I am having trouble with a
> program I am writing.
Hello, and welcome. Since you don't say if this is an assignment or
not, I will just point you in the right direction, and point out a few
things you might make use of.

> def B1():
>  period = "."

You don't actually need to store a period anywhere, because when your
while loop initiates, you can just do:
while next1 != "."
A word of advice: next is a keyword in python, so 'next1' might not be
a great variable name.

>  # 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
>  while  next1 != (period) :
>
>     next1  = input("Enter the next word in you sentence or enter period:")
>
>     if next1 == (period):
>         next1 = next1 + period
>         print ("Your sentence is:",first,next1,period)

Your code will never terminate, because:
program initiates. while loop begins.
Enter a few words, then decide to end with a period.
if-branch executes, because next1 is a period.
    next1 becomes next1 + period #which is ..
while loop checks to see if next1 is a period, which it isn't, and runs again.

Furthermore, you are continually overwriting next1 until you type a
period. Consider the following output (I have added some spaces to the
important parts, so as to make them stand out):
>>>
Enter the first word in your sentence I
Enter the next word in you sentence or enter period:am
    Entering while loop. next1 is: am
Enter the next word in you sentence or enter period:a
    next1 is: a
    Entering while loop. next1 is: a
Enter the next word in you sentence or enter period:novice
    next1 is: novice
    Entering while loop. next1 is: novice
Enter the next word in you sentence or enter period:.
    next1 is: .
    next1 is a period, now running next1 + period line:
..
    Entering while loop. next1 is: ..

If you don't have to use strings for this program, I would suggest you
check out lists, and especially list.append(). It is possible to write
a program that does what you want, but it'd be a convoluted solution.

-- 
best regards,
Robert S.


More information about the Tutor mailing list