Learning Python the Hard Way

Status
Not open for further replies.

KingAZAZ

Ars Praetorian
418
Subscriptor
So I got turned on to the idea of learning Python the hard way at, well, http://learnpythonthehardway.org/book/ and as directed by the book I am now trying to figure out a few things that I don't understand. This post has ended up being fairly long, and I hope that it's not bothersome. I figure this is exactly what this forum is for, but I can envision some folks taking the time to tell me that I should choose a different book to learn from if this one is going to lead me to ask such involved questions of others.

Anticipating that suggestion, I'll say now that I like the way that these lessons are challenging me to figure things out on my own through careful analysis, and to ask about what I can't figure out. It forces me to articulate my thoughts, and I think that's a good thing.

Anywho . . .

The following code (as seen in the lesson here http://learnpythonthehardway.org/book/ex3.html:
print "I will now count my chickens:"

print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4

print "Now I will count the eggs:"

print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

print "Is it true that 3 + 2 < 5 - 7?"

print 3 + 2 < 5 - 7

print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7

print "Oh, that's why it's False."

print "How about some more."

print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2


Yields this:
python ex3.py
I will now count my chickens:
Hens 30
Roosters 97
Now I will count the eggs:
7
Is it true that 3 + 2 < 5 - 7?
False
What is 3 + 2? 5
What is 5 - 7? -2
Oh, that's why it's False.
How about some more.
Is it greater? True
Is it greater or equal? True
Is it less or equal? False


Again per the instructions, I'm adding comments to my code that describe what I'm learning by typing each line. Stuff like, what effect quotes have or how python deals with math. Here's what I'm not clear on. I can't seem to figure out the order of operations that python is going through for this code: print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

The first half of the modulus (that is, what is in front of the % symbol . . . just to clarify my way of reference) is easy peasy. The second half is confusing me. The result of the whole string ("string" may or may not be how I should refer to that line) is 7. I understand how the % works, but not the order of operations for 2-1/4+6.

It seems like it should be super obvious. I know the order for 100-25*3%4 is 100-((25*3)%4). Could someone add parentheses to the line in question to clarify this point?

Second, I'm assuming that the commas after a printed sentence are not decorative, and that they let python know that what follows is another instruction, yes?

I had more questions, but writing this post led me to the answers. Sweet!

Any help shall be greatly appreciated. Thanks!
 

agifford

Ars Tribunus Militum
2,142
If you look at: Python operator precedence (lowest to highest) you'll get an idea of what operators run first. Grouping parentheses arent in the chart that i see, but the contents of a group are processed and replace the group in the operation.

In the chart, since multiplication, division, and modulus are equal priority and higher than addition and subtraction, you do the modulo and division first like:

3 + 2 + 1 - 5 + (4 % 2) - (1 / 4) + 6 (1/4 is zero though, 1.0/4 is 0.25. (at least in python 2.7, i thought it worked differently). )
which becomes
3 + 2 + 1 - 5 + 0 - 0 + 6



For operations of equal precedence, you just go left to right, which is why 25*3%4 is (25*3) % 4.

print is an oddball command, they changed it to a function in python 3. The commas are there to separate arguments to the print command. it will print the first argument, then the second, separated by a space. If the argument is an expression (formula) it will evaluate it first.
I don't do python3, but i imagine the python 2 "print x, y" command corresponds to "python(x,y)" if you want to think of it that way.

And lastly, you will probably run into % used as an operator on strings too, its not modulo then, its the string formatting operator.
http://docs.python.org/library/stdtypes.html#string-formatting Although ive never used it with the optional keys. I usually just do print "%s some text(%s)" % (1,2) #which yields "1 some text (2)"
 

KingAZAZ

Ars Praetorian
418
Subscriptor
Yanno, I just had to laugh. When I read your reply it dawned on me that I was stuck in a mental rut regarding the way that I was trying to evaluate the problem. For some reason I was treating the % similar to an = in an equation, trying to solve each side. That strikes me as pretty humorous. :p

Thanks for the response!

As for this:
(1/4 is zero though, 1.0/4 is 0.25. (at least in python 2.7, i thought it worked differently). )
which becomes
3 + 2 + 1 - 5 + 0 - 0 + 6

I take it you are describing floating point . . . notation? Anyway, I'm working on understanding why 1/4 is zero. Not getting it yet, but I'm still at the office and can't really hunker down and try to grasp it.

Thanks again.
 

agifford

Ars Tribunus Militum
2,142
KingAZAZ":11tpmtc4 said:
I take it you are describing floating point . . . notation? Anyway, I'm working on understanding why 1/4 is zero. Not getting it yet, but I'm still at the office and can't really hunker down and try to grasp it.

Thanks again.

Yes "1" is an integer, or whole number, while "1.0" is a floating point number, which can have a fractional component. Its not an exact decimal number, but an approximate version that the computer can deal with, you can have small math errors/issues in floating point arithmetic. You can read more here: http://download.oracle.com/docs/cd/E199 ... dberg.html but its fairly technical.

http://docs.python.org/reference/expres ... operations
http://docs.python.org/reference/expres ... onversions

If you read both of those, it says that if both arguments in a division are integers, then the result is an integer using "floor" division. "Floor" division is notated with // since you can specifically request it even if you have floating point numbers. It says do the division as normal, then take the Floor(greatest whole number value less than the value) of the result.

Code:
>>> 1.0 //4 #floor division
0.0 # floating point
>>> 1.0 / 4 # regular division
0.25 # floating point
>>> 1 / 4 #implicitly floor division, since both arguments are integers
0 #integer
>>> 1 // 4 #floor division
0 # integer
 
This information might be too early for you, but IME Python's scoping rules can be confusing:
Code:
i = 0
if True:
   i = 42
print i # prints 42; flow control blocks don't create new scope
(lambda i: i)(0xdeadbeef)
print i # prints 42; functions create new scope
[ i for i in xrange(0, 10) ]
print i # prints 9; list comprehensions don't create new scope
( i for i in xrange(43) )
print i # prints 9; but generators do
list( i for i in xrange(43) )
print i # prints 9; even after I forced evaluation

Also, Python doesn't translate most signals to exceptions:
Code:
$ echo -e 'import time\ntry: time.sleep(100)\nfinally: print "done"' | python - &
[1] 1533
$ kill -INT %1
done
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
[1]+  Exit 1                  echo -e 'import time\ntry: time.sleep(100)\nfinally: print "done"' | python -
$ echo -e 'import time\ntry: time.sleep(100)\nfinally: print "done"' | python - &
[1] 1543
$ kill -TERM %1
[1]+  Terminated              echo -e 'import time\ntry: time.sleep(100)\nfinally: print "done"' | python -
$ # No traceback, but more importantly the finally block is not executed

Finally, learn how to use pdb early, unless you really want to learn Python the hard way.
 

bk0

Ars Tribunus Militum
1,801
As has been said, print is a function not a statement. Also learn to use new string formatting rather than the old style:

Code:
> foo = "Hello {a}, my name is {b}".format(a="friend", b="Mike")
> print(foo)
Hello friend, my name is Mike

Don't worry about "old" and "new" classes. Just use "class FooClass:" and forget about it.

All of this is supported in Python 2.7.x, btw, so you don't have to only use 3.x for it to be applicable.
 
Status
Not open for further replies.