Archive:Python/Operators: Difference between revisions
wikademia>ArrowStomper |
wikademia>ArrowStomper |
||
| Line 68: | Line 68: | ||
That is how you do math with values from a dictionary. Don't forget to use quotations around the keys unless you use integers as the keys. Spend a couple of minutes messing around with this stuff, its fun and it'll help you remember it better. | That is how you do math with values from a dictionary. Don't forget to use quotations around the keys unless you use integers as the keys. Spend a couple of minutes messing around with this stuff, its fun and it'll help you remember it better. | ||
==Indexing== | |||
Revision as of 06:27, 11 October 2006
Operations
There are certain things that you can do with all of the types. You can do simple math, index, slice, and check for membership. You can also use the Format Specifier in strings.
Simple Math
Math is very straight forward in Python. + adds, - subtracts, / divides, and believe it or not * multiplies. The main thing to comment on is %. % divides a problem and then returns the remainder.
Type:
>>>9 % 3
0
Now Type:
>>>9 % 2
1
The % command can be used to find out if something is even or odd or if it is a multiple of some number. Here is some code that is a little advanced for you right now. Just type it in and now that within a couple of lessons you will know what you did.
Type:
>>>a = 4
>>>if a % 2 = 0:
"print a is even"
a is even
You can also use variables, and elements and values in simple math.
Type:
>>>x = 1 >>>y = 5
Now Type:
>>>x + y 6
That is how the variable works.
Type:
>>>x = [1, 2, 3]
Now Type:
>>>x[1] + x[2] 5
That is how you use elements from a tuple or list to do math.
Type:
>>>x = {'a':1, 'b':2}
Now Type:
>>>x['a'] + x['b']
3
That is how you do math with values from a dictionary. Don't forget to use quotations around the keys unless you use integers as the keys. Spend a couple of minutes messing around with this stuff, its fun and it'll help you remember it better.