SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 293 | Next

Shon Harris, Allen Harper, Chris Eagle, and Jonathan Ness

"Gray Hat Hacking, Second Edition"

The syntax is just as you??™d expect:
>>> n1=5 # Create a Number object with value 5 and label it n1
>>> n2=3
>>> n1 * n2
15
>>> n1 ** n2 # n1 to the power of n2 (5^3)
125
>>> 5 / 3, 5 / 3.0, 5 % 3 # Divide 5 by 3, then 3.0, then 5 modulus 3
(1, 1.6666666666666667, 2)
>>> n3 = 1 # n3 = 0001 (binary)
>>> n3 << 3 # Shift left three times: 1000 binary = 8
8
>>> 5 + 3 * 2 # The order of operations is correct
11
Now that you??™ve seen how numbers work, we can start combining objects. What happens
when we evaluate a string + a number?
>>> s1 = 'abc'
>>> n1 = 12
>>> s1 + n1
Traceback (most recent call last):
File "", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
Error!We need to help Python understand what we want to happen. In this case, the
only way to combine ???abc??™ and 12 would be to turn 12 into a string. We can do that on
the fly:
>>> s1 + str(n1)
'abc12'
>>> s1.replace('c',str(n1))
'ab12'
Gray Hat Hacking: The Ethical Hacker??™s Handbook
142
Figure 6-2
Label1 is
reassigned to
point to a
different string.
When it makes sense, different types can be used together:
>>> s1*n1 # Display 'abc' 12 times
'abcabcabcabcabcabcabcabcabcabcabcabc'
And one more note about objects??”simply operating on an object often does not
change the object.


Pages:
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305