
January 15th, 2013, 06:21 AM
|
|
Registered User
|
|
Join Date: Jan 2013
Posts: 3
Time spent in forums: 41 m 26 sec
Reputation Power: 0
|
|
So So confused with this loop...
I am so confused here.
This loop is from Learn Python the Hard Way...
_________________________
def gold_room():
...indent....print "This room is full of gold. How much do you take?"
...indent....next = raw_input("> ")
...indent....if "0" in next or "1" in next:
...indent.......how_much = int(next)
...indent....else:
...indent........dead("Man, learn to type a number.")
...indent....if how_much < 50:
...indent.......print "Nice, you're not greedy, you win!"
...indent.......exit(0)
...indent....else:
...indent.......dead("You greedy bastard!")
_________________________
To simplify I write it like this.
_________________________
def gold_room():
...indent....print "This room is full of gold. How much do you take?"
...indent....next = raw_input(">")
...indent....if "0" in next or "1" in next:
...indent.......how_much = int(next)
...indent....else:
...indent.......print "aaaaaaaaaaaaa"
...indent....if how_much < 50:
...indent.......print "bbbbbbbbbbbbb"
...indent....else:
...indent.......print "cccccccccccccccccc"
gold_room()
_________________________
It makes sense how it works when I put 0, 1.
1. What doesn't make sense 1
"how_much" is getting unboundlocalerror when I put any number from 2 to 49.
It does make sense that it gets error, because "how_much" can not be assigned or defined without putting 0 or 1.
But I don't understand why he writes code like this and expecting how to make it work?
2. What doesn't make sense 2
How come the code prints out "cccccccccccc" when I put any number from 50, 51 ...
I have no idea how "how_much" comes to have a value even if I do not put 0 nor 1 so I thought it can't have access to the line "how_much = int(next)"
Without going through the line "how_much = int(next)"...
how the heck "how_much" gets a value assigned from "next"--see when I input 51, it goes through raw_input and be assigned to "next", not to "how_much"
Please help me. I am in a big chaos.
feel frustrated
|