[Tutor] Chapter 4 Help

Alan Gauld alan.gauld at btinternet.com
Sat Apr 27 02:47:55 CEST 2013


On 26/04/13 22:02, Mariel Jane Sanchez wrote:

> program should calculate the number of vowels in the phrase using a for
> loop. The second time, your program should use a while loop."
> My code:

> phrase = raw_input("Please enter a phrase: ")
> VOWELS = "aeiou"
> new = ""
> for letter in phrase:
>      if VOWELS in phrase :
>          print newv

Please send the actual code, don;t retype it. The newv should be 
throwing an error so presumably you don;t have that in your
real code.

The real problem is in your 'if' test. Think about the logic there.

> It keeps printing the phrase not the new string.

Not according to the code you posted, but in the real code it
may be different. Please post the real code.

> How would you do this?

You are almost there. But you should be calculating the number of vowels 
not printing them... And for that you could look at the count() method 
of strings...

And the while loop should just be a conversion of the for loop to a 
while - it hardly seems worth having as an exercise (and could even
be said to be teaching you bad habits!).

> 2. "Write a program that gets a message from the user and prints the
> message out backwards."
> For this one, i honestly don't have any idea how to make a word print
> backwards, I only do it with numbers. Here's my attempt code:"

If you use a while loop here you start at the highest index in the 
string and decrement the index each time.

Using a for loop you could investigate string slicing.
Or you could convert the string to a list, reverse the list and convert 
back again to a string.
Or you could use a for loop and the range function with range set to 
count backwards.

Lots of options.


> import random
> message = raw_input("Please enter you message:")
> raw_input("Please press the enter key to our message.")
> high = (message(len(100)))
> low = (message(len(0)))

No idea what you think those lines do but I'm pretty sure its
not what they really do!

> new = random.randrange (high, low)
> print new

And even less idea what you think this might be doing.

Can you write down in English how you would do this using
pen and paper? That might help you to craft a program.

> 3."Write a program that prints out a string representation of a random
> card from a deck of playing cards.

OK, this is a whole different can of worms, lets get the looping and 
string issues sorted out first!
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list