Python operators

From Wikiversity
Jump to: navigation, search

Contents

[edit] Operations, The Format Specifier, and Other Commands

[edit] 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.

[edit] Simple Math

Math is very straightforward in Python. + adds, - subtracts, / divides, and believe it or not * multiplies. The main thing to comment on is %.  % performs a division and then returns the remainder. This is called the modulus operation.

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 may be a little advanced for you right now. Just type it in and know that within a couple of lessons you will understand it fully. When you type "print a is even" it must be 4 spaces to the right of the i in if.

Like C++ or JAVA, Python knows 2 different types of "Equality" ("="): Equality as a command or assignment of a value ("a = 2" meaning make Variable "a" equal 2); and Equality in conditions or tests ("if a == 2 ..." meaning that variable a is checked and not assigned). In the first case, use the single equal-sign "="; in the second case use the double equal-sign "==".

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 arithmetic.

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 arithmetic.

Type:

>>> x = {'a':1, 'b':2} =You can also add and multiply strings, tuples, and lists. Now type:

>>> x['a'] + x['b']

3

That is how you do arithmetic 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. You may also add strings, tuples, and lists.

[edit] Concatenating

To add two strings together - to do this you just type the first string, an addition sign, the second string.

Type:

>>> "Python" + " is awesome"

You can do the same with variables referring to strings.

Type:

>>> x = "Python"

>>> y = " is awesome"

Now Type:

>>> x + y

'Python is awesome'

You can do the same with tuples.

Type:

>>> x = ('I', 'Love')

>>> y = ('Wikiversity',) DON'T FORGET THE COMMA AFTER WIKIVERSITY

Now Type:

>>> print x + y

('I', 'Love', 'Wikiversity')

It works the same with lists. What you cannot do is combine two different kinds of types.

Type:

>>> x = ('I', 'Love')

>>> y = 'Python'

Now Type:

>>> print x + y

Traceback (most recent call last):

File "<pyshell#91>", line 1, in ?

print x + y

TypeError: can only concatenate tuple (not "str") to tuple

[edit] Multiplying types

Multiplying is very easy and straight forward.

Type:

>>> x = 'dog'

Now type:

>>> x * 5

'dogdogdogdogdog'

Now with a tuple.

Type:

>>> x = ('dog',)

Now type:

>>> x * 5

('dog', 'dog', 'dog', 'dog', 'dog')

Now with a dictionary.

Type:

>>> x = {'dog':1}

Now type:

>>> x * 5

Traceback (most recent call last):

File "<pyshell#5>", line 1, in ?

x * 5

TypeError: unsupported operand type(s) for *: 'dict' and 'int'

You can't do it with dictionaries, that would make more than one of the same key, remember.

[edit] Indexing

You have already learned how to index in lesson 2. When you typed x[3] you were indexing. You may also index a string without first making a variable represent it.

Type:

>>> "I Love Wikipedia"[5]

e

simple enough.

[edit] Slicing

Slicing is used to access a range of elements the way that indexing accesses 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 weird 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 index(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 3 elements of x.

Another thing that you can do when splicing is enter the step index.

Type:

>>> x = "0123456789"

Now Type:

>>> x[1:-1:3][1]

'147'

You may also just use the step index.

Type:

>>> x[::3]

'0369'

You can do this to find every other element or every third or whatever your needs require. You may also make the step index negative. By doing so you make the elements return starting with the last one.

Type:

>>> x='0123456789'

Now Type:

>>> x[-2:1:-1]

'8765432'

To reverse a string (or any sequence):

>>> x[::-1]

'9876543210'

When the step index is negative it is important to remember to make sure that the first index is calling an element that comes later in the string, tuple or list than the second element. Just as in the last example -2 is representing 8 while 1 is representing 2.

[edit] The Format Specifier

You are going to use this versatile command constantly.

Type:

>>> print 'I Love %s' % 'DOS'

I Love DOS

What the percent sign does is hold the place in the string and let you tell Python what to put there at the end of the string. The s behind the % tells Python to expect any input. If you neglect the s, Python will automatically assume it to be %d, which causes Python to expect a numerical value. Be sure to define it correctly, or the script won't work.

[edit] References

  1. Script error Has a table that explains the syntax behind this kind of splicing.