[Tutor] Problems with Looping

Joel Goldstick joel.goldstick at gmail.com
Mon Mar 26 09:56:30 EDT 2018


On Mon, Mar 26, 2018 at 9:45 AM, David Brown <david.brown.rrt at gmail.com> wrote:
> Hello all,
>
> I am trying to teach myself Python by working through a book on Safari
> Books. One of the examples in the chapter on Loops states:
>
> *"Write a program that simulates a fortune cookie. The program should
> display one of five unique fortunes, at random, each time it’s run."*
>
> The program below does that just fine. However, I wanted to take it to the
> next level and allow the user to select another fortune if desired. I've
> tried a variety of "While" loops, but they end up with infinite loops, or
> not generating a fortune. I've tried to add continue, after each "if, elif"
> statement, but I usually get an error stating that it's not in the correct
> place in the loop.
>
> Can any one give me a hint? I'd like to figure it out on my own, but am
> stuck.
>
> This is NOT for a graded assignment. It is purely for self study.
>
> # Fortune Cookie
> # Displays Random Fortune
>
> import random
>
> # Generate one of five fortunes randomly
>
> print("\t\tCyber Fortune Cookie")
> input(" \n\tHit ENTER to see your fortune")
>
> # Set the initial values
> prefix = "Your fortune is: "
> number = random.randrange(5) + 1
>
> if number == 1:
>     print("\n", prefix,"When much wine goes in very bad things come out.")
>
> elif number == 2:
>     print("\n", prefix,"You will be hungry in one hour.")
>
> elif number == 3:
>     print("\n", prefix,"Order another egg roll and you will be happy.")
>
> elif number == 4:
>     print("\n", prefix,"You will love the spicy shrimp and garlic.")
>
> elif number == 5:
>     print("\n", prefix,"You will meet an old friend soon.")
>
> #input("\n\nPress the enter key to get another fortune.")
> --
> *David*
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


set a variable, say 'another_fortune' to True.
surround your code in a while loop, checking the value of another_fortune

At the end of your code, ask if the user wants another, and check
input for 'y' or 'Y', and if you don't get that, set another_fortune =
False
-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays


More information about the Tutor mailing list