Archive:Python/Operators
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.
Indexing
You have already learned how to index in lesson 2. When you typed x[3] you where indexing. You may also index a string without first making a variable represent it.
Type:
>>>"I Love Wikipedia"[5]
e
simple enough.
Slicing
Slicing is used to access a range of elements the way that indexing accessess one element.
Type:
>>>x = "Wikipedia and Python are awesome"
Now Type:
>>>print x[14:32]
Python are awesome
The numbers that you enter after the variable (the [14:32]) are called indices. The way the last one works is hard to understand at first. I'll do another example to make it clear.
Type:
>>>x = '1234'
Now type:
print x[1:3]'
23
It prints out the 2 because it starts numbering at 0, but the reason it prints out the 3 instead of the 4 is because it counts the [3] that you entered as the end point and does not include it. Seems wierd at first but easy to get used to.
You may also use negative numbers as the indices (x[-12:-]). If you only use one negative indice (x[-4:]) Python will print starting with the element selected and go until the end of the string, tuple or list. This works for positive indices as well (x[:3]). Python will print the first 2 elements of x.
Another thing that you can do when splicing is enter the step indice.
Type:
>>>x = "0123456789"
Now Type:
>>>x[1:-1:3]
'147'
You may also just use the step indice.
Type:
>>>x[::3]
'0369'
You can do this to find every other element or whatever your needs require. ==