Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52100 > unrolled thread

new to While statements

Started bykrismesenbrink@gmail.com
First post2013-08-06 20:38 -0700
Last post2013-08-07 20:21 -0700
Articles 13 — 7 participants

Back to article view | Back to comp.lang.python


Contents

  new to While statements krismesenbrink@gmail.com - 2013-08-06 20:38 -0700
    Re: new to While statements snakeinmyboot <mikelhamer@gmail.com> - 2013-08-06 21:09 -0700
      Re: new to While statements krismesenbrink@gmail.com - 2013-08-06 21:13 -0700
    Re: new to While statements snakeinmyboot <mikelhamer@gmail.com> - 2013-08-06 21:17 -0700
    Re: new to While statements Joshua Landau <joshua@landau.ws> - 2013-08-07 05:37 +0100
    Re: new to While statements Vito De Tullio <vito.detullio@gmail.com> - 2013-08-07 07:20 +0200
    Re: new to While statements Dan Sommers <dan@tombstonezero.net> - 2013-08-07 05:35 +0000
      Re: new to While statements snakeinmyboot <mikelhamer@gmail.com> - 2013-08-06 22:42 -0700
        Re: new to While statements Dan Sommers <dan@tombstonezero.net> - 2013-08-07 05:52 +0000
          Re: new to While statements krismesenbrink@gmail.com - 2013-08-06 23:26 -0700
      Re: new to While statements Vito De Tullio <vito.detullio@gmail.com> - 2013-08-07 20:05 +0200
      Re: new to While statements Dave Angel <davea@davea.name> - 2013-08-08 01:31 +0000
    Re: new to While statements Larry Hudson <orgnut@yahoo.com> - 2013-08-07 20:21 -0700

#52100 — new to While statements

Fromkrismesenbrink@gmail.com
Date2013-08-06 20:38 -0700
Subjectnew to While statements
Message-ID<69a10630-98dc-4a31-89ef-2770b3c1fd70@googlegroups.com>
import random



def room ():

    hp = 10
    while hp != 0:

        random_Number = random.randint(1, 2)

        #asking if you want to roll/play
        des = input("Would you like to roll the die?")

        if des == ("y"):
            print ("Rolling the die...")
            print ("You rolled a...")
            print (random_Number)

            #a "monster" appers if you roll a 1""
            if random_Number == 1:
                monster_hp = 10
                print ("Oh no a Monsster!")
                print ("would you like to attack?")
                answer = input("y or n?")
                if answer == "y":
                    #if you choose to battle this is what happens
                    while monster_hp >=0:
                        print ("you attack")
                        damage_done = random.randint(0,5)
                        print ("You do ",damage_done,"damage")
                        monster_hp = monster_hp - damage_done
                        print ("the monster takes a hit, it has ", monster_hp,
                        "left")


                elif answer == ("n"):
                    print ("you run away")

                else:
                    print ("You and the monster just stare at one another")
            else:
                print ("You find nothing")
        # if you decisde to not play it will kill you
        elif des == ("no"):
            hp = 0
            print ("Maybe next time!")
        else:
            print ("please enter yes or no")

room()


this is the code i'm making. as the subject says im new to while statements. i am having problems with the monster battle part, it takes health away from the "monster" but as soon as it gets to 0 or less i'd like the code to start from the top and ask you to roll the die again. any help on this would be greatly appreciative

[toc] | [next] | [standalone]


#52101

Fromsnakeinmyboot <mikelhamer@gmail.com>
Date2013-08-06 21:09 -0700
Message-ID<b2b4786a-4ee2-42fa-ae6f-2521bf2988e3@googlegroups.com>
In reply to#52100
Hey there, cool idea you've got going on here! As far as I can tell though...what you want to happen, is indeed actually happening. Did you mean something else? Everytime I run the script and defeat a monster, it asks me if I want to roll the dice again. 

[toc] | [prev] | [next] | [standalone]


#52102

Fromkrismesenbrink@gmail.com
Date2013-08-06 21:13 -0700
Message-ID<8b57b60b-074a-4060-b53e-174278b7d9b8@googlegroups.com>
In reply to#52101
and it seems you are right about that, i don't know what was wrong with my IDE before, i closed it and opened it up again,seemed to fix the problem. thanks for taking the time to look at it anyway! 

[toc] | [prev] | [next] | [standalone]


#52103

Fromsnakeinmyboot <mikelhamer@gmail.com>
Date2013-08-06 21:17 -0700
Message-ID<e73f7a3e-fba4-461a-9f1d-ea15507af2ec@googlegroups.com>
In reply to#52100
yea no problem. heres a little tip though so you atleast get something out of the post.

monster_hp = monster_hp - damage_done

can be simplified by writing

monster_hp -= damage_done

the -= means equal to whatever is on the left, minus whatevers on the right. this can be done with addition, multiplication, division, etc etc etc.

[toc] | [prev] | [next] | [standalone]


#52106

FromJoshua Landau <joshua@landau.ws>
Date2013-08-07 05:37 +0100
Message-ID<mailman.295.1375850769.1251.python-list@python.org>
In reply to#52100
On 7 August 2013 04:38,  <krismesenbrink@gmail.com> wrote:
> import random
>
>
>
> def room ():

No need for the space after "room".

>     hp = 10
>     while hp != 0:

"while hp:" would be idiomatic, but you probably want "while hp > 0"
if you allow negatives.

>         random_Number = random.randint(1, 2)

You meant "random_number", I'm sure ;).

>         #asking if you want to roll/play

Don't comment lines unless the comment says more than the line.

>         des = input("Would you like to roll the die?")
>
>         if des == ("y"):

You don't need the brackets. Try to avoid redundant brackets where
they don't clarify anything.

Additionally, you should probably be more lenient and consistent with
answers. Maybe something like:

    if des.casefold() in ("y", "yes"):

and its counterpart

    if des.casefold() in ("n", "no"):

>             print ("Rolling the die...")
>             print ("You rolled a...")
>             print (random_Number)

You should avoid spaces between the function and the brackets.

>             #a "monster" appers if you roll a 1""
>             if random_Number == 1:
>                 monster_hp = 10
>                 print ("Oh no a Monsster!")
>                 print ("would you like to attack?")
>                 answer = input("y or n?")
>                 if answer == "y":
>                     #if you choose to battle this is what happens
>                     while monster_hp >=0:

Think carefully here -- do you want to have a round when monster_hp is
greater *or equal* to 0? Maybe you would rather only if it's alive (hp
> 0)?

>                         print ("you attack")
>                         damage_done = random.randint(0,5)
>                         print ("You do ",damage_done,"damage")
>                         monster_hp = monster_hp - damage_done

monster_hp -= damage_done

>                         print ("the monster takes a hit, it has ", monster_hp,
>                         "left")
>
>                 elif answer == ("n"):
>                     print ("you run away")
>
>                 else:
>                     print ("You and the monster just stare at one another")
>             else:
>                 print ("You find nothing")
>         # if you decisde to not play it will kill you
>         elif des == ("no"):
>             hp = 0

Gah! You just kill him off? Are you sure you don't want to use a
"break" or "return" to quit the loop or function?

>             print ("Maybe next time!")
>         else:
>             print ("please enter yes or no")
>
> room()


As a whole, +1 for the good naming, decent attempt at spacing and a
mostly-sane layout.


> this is the code i'm making. as the subject says im new to while statements. i am having problems with the monster battle part, it takes health away from the "monster" but as soon as it gets to 0 or less i'd like the code to start from the top and ask you to roll the die again. any help on this would be greatly appreciative


PS: I'd use a state machine for times like this, eg.

    import random

    def prompt(action, retort_invalid=None):
        while "asking for reponse":
            response = input("Would you like to {}?".format(action)).casefold()

            if response in ["y", "yes"]:
                return True

            elif response in ["n", "no"]:
                return False

            else:
                if retort_invalid is not None:
                    print(retort_invalid)

    def room():
        state = "wandering"

        while "adventuring":

            if state == "idle":
                if prompt("wander around")
                    print("Rolling the die...")

                    roll = random.randint(1, 2)

                    print("You rolled a {}.".format(roll))

                    if roll == 1:
                        monster_hp = 10
                        print("Oh no! A Monster!")
                        state = "facing monster"

                    else:
                        print("You find nothing")

                else:
                    print("Maybe next time!")
                    return

            elif state == "facing monster":
                will_attack =

                if prompt("attack", "You and the monster just stare at
one another"):
                    state = "attacking"

                else:
                    print("you run away")
                    state = "idle"

            elif state == "attacking":
                damage_done = random.randint(0, 5)
                monster_hp -= damage_done

                print("You attack to do", damage_done, "damage")
                print("The monster takes a hit, it has", monster_hp, "hp left")

                if monster_hp <= 0:
                    state = "idle"

    room()


The advantage of this is everything sits at the same level so you know
whether you've covered all options and permutations of options. It's
only longer because I made the "prompt" function which is more
rigorous than the current method.

[toc] | [prev] | [next] | [standalone]


#52107

FromVito De Tullio <vito.detullio@gmail.com>
Date2013-08-07 07:20 +0200
Message-ID<mailman.296.1375852843.1251.python-list@python.org>
In reply to#52100
Joshua Landau wrote:


>         while "asking for reponse":

>         while "adventuring":

that's a funny way to say `while True:`...


-- 
By ZeD

[toc] | [prev] | [next] | [standalone]


#52108

FromDan Sommers <dan@tombstonezero.net>
Date2013-08-07 05:35 +0000
Message-ID<90lMt.30102$907.25512@fx17.iad>
In reply to#52100
On Wed, 07 Aug 2013 07:20:28 +0200, Vito De Tullio wrote:

> Joshua Landau wrote:
> 
> 
>>         while "asking for reponse":
> 
>>         while "adventuring":
> 
> that's a funny way to say `while True:`...

Funny, perhaps, the first time you see it, but way more informative than
the other way to the next one who comes along and reads it.

-- 
Dan

[toc] | [prev] | [next] | [standalone]


#52109

Fromsnakeinmyboot <mikelhamer@gmail.com>
Date2013-08-06 22:42 -0700
Message-ID<5159c8f0-9053-425d-91d0-798cb429303e@googlegroups.com>
In reply to#52108
I wish I understood half of what you posted Dan. Time to hit the books

[toc] | [prev] | [next] | [standalone]


#52110

FromDan Sommers <dan@tombstonezero.net>
Date2013-08-07 05:52 +0000
Message-ID<fglMt.7994$KF3.7621@fx14.iad>
In reply to#52109
On Tue, 06 Aug 2013 22:42:42 -0700, snakeinmyboot wrote:

> I wish I understood half of what you posted Dan. Time to hit the books

So think about the "while" statement:  it takes an expression (the part
before the colon) and a suite (the part after the colon and before the
next statement at the same indent level as the while statement),
evaluates the truthiness of that expression, and executes its suite if
the expression is true.

So "while True" evaluates True, discovers that it's true, and executes
its suite.

So "while 'some string'" evaluates 'some string,' discovers that it's
true, and executes its suite.

The language sees both literals the same way, but one of them is much
more useful to a human reader.

Statements like "while True," "while x < 0," and "while object.method()
!= False" are more conventional, but really no different from "while y"
and "while 'a description of what this loop does.'"

[toc] | [prev] | [next] | [standalone]


#52113

Fromkrismesenbrink@gmail.com
Date2013-08-06 23:26 -0700
Message-ID<182eaf32-4148-44fd-a3d2-39f283cc4c23@googlegroups.com>
In reply to#52110
wow everyone thanks for the feed back! i'll have to rewrite this with everything you guys taught me. this makes ALOT more sense. :D

[toc] | [prev] | [next] | [standalone]


#52145

FromVito De Tullio <vito.detullio@gmail.com>
Date2013-08-07 20:05 +0200
Message-ID<mailman.325.1375898730.1251.python-list@python.org>
In reply to#52108
Dan Sommers wrote:

>>>         while "asking for reponse":
>> 
>>>         while "adventuring":
>> 
>> that's a funny way to say `while True:`...
> 
> Funny, perhaps, the first time you see it, but way more informative than
> the other way to the next one who comes along and reads it.

While I understand that it's syntactically and semantically correct, my nose 
still doesn't like it.

It's not that's just not common... I just think it's a mishmash... it's not 
a "rule" thing, more a "feeling wrong" one.

Maybe it's better if I try to explain in another way...

My first instinct about it it's to think why the author choose this way to 
talk to the reader.

This message it's clearly meant to be read by another programmer, not by the 
user. But in my mind it should be a comment. In my mind code explain "what" 
is happening, comment say "why". (Sometimes talking to my colleagues we say 
comment is a way to ask to forgiveness for a particular obscure code, as in 
"sorry, I needed to flip-this and flop-that for such-and-such reason") 

Following this reasoning, I will found more readable something like

    # asking for response
    while True:
        ...

that

    while 'asking for response':
        ...

because in the latter case the "why" and the "how" are mixed. It's like 
you're talking with the interpreter, but the message is for the programmer..

I hope I explained myself...




-- 
By ZeD

[toc] | [prev] | [next] | [standalone]


#52158

FromDave Angel <davea@davea.name>
Date2013-08-08 01:31 +0000
Message-ID<mailman.333.1375925491.1251.python-list@python.org>
In reply to#52108
Vito De Tullio wrote:

> Dan Sommers wrote:
>
>>>>         while "asking for reponse":
>>> 
>>>>         while "adventuring":
>>> 
>>> that's a funny way to say `while True:`...
>> 
>> Funny, perhaps, the first time you see it, but way more informative than
>> the other way to the next one who comes along and reads it.
>
> While I understand that it's syntactically and semantically correct, my nose 
> still doesn't like it.
>

Neither does mine.  There's no need for a trick here.   "while True"
reads better, and a comment (on the same line, preferably) can explain
what the loop is for.


-- 
DaveA

[toc] | [prev] | [next] | [standalone]


#52162

FromLarry Hudson <orgnut@yahoo.com>
Date2013-08-07 20:21 -0700
Message-ID<VfCdnYWxAuw5k57PnZ2dnUVZ_j2dnZ2d@giganews.com>
In reply to#52100
On 08/06/2013 08:38 PM, krismesenbrink@gmail.com wrote:
> import random
>
>
>
> def room ():
>
>      hp = 10
>      while hp != 0:
>
>          random_Number = random.randint(1, 2)
>
>          #asking if you want to roll/play
>          des = input("Would you like to roll the die?")
>
<snip>

One very trivial comment...  Add one or two spaces to the end of your prompt string, (I like to 
use two).

No biggie, but it just looks nicer if the answer doesn't butt up directly against the end of the 
prompt.

      -=- Larry -=-

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web