Python Concepts/Operators

From Wikiversity
Jump to: navigation, search

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


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

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.


>>> 9 % 3

Now Type:

>>> 9 % 2

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 indented greater than the last line. For example, we need to indent the code by at least one spaces or tab.

Attention yellow.svg You should note that you cannot use both the tab key and the spacebar while indenting. Mixing both of these keys will help you raise an indentation error. To avoid this, CPython's default IDE, IDLE, replaces the a tab space with four spaces.

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 "==".


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


>>> x = 1
>>> y = 5
>>> x + y

That is how the variable works.


>>> x = [1, 2, 3]
>>> x[1] + x[2]

This is how you use elements from a list to preform arithmetic operations. It should be clarified that x[0] = 1, x[1] = 2, and x[2] = 3.

You can also add and multiply strings, tuples, and lists. Type:

>>> x = {'a':1, 'b':2}
>>> x['a'] + x['b']

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.


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


>>> "Python" + " is awesome"
'Python is awesome"

You can do the same with variables referring to strings. Type:

>>> x = "Python"
>>> y = " is awesome"
>>> x + y
'Python is awesome'

You can do the same with tuples. Type:

>>> x = ('I', 'Love')
>>> y = ('Wikiversity',)
>>> print(x + y)
('I', 'Love', 'Wikiversity')

Attention yellow.svg Note: Don't forget the comma after 'Wikiversity'!

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

>>> x = ('I', 'Love')
>>> y = 'Python'
>>> print (x + y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple

Multiplying types[edit]

Multiplying is very easy and straight forward. Type:

>>> x = 'dog'
>>> x * 5

Now with a tuple. Type:

>>> x = ('dog',)
>>> x * 5
('dog', 'dog', 'dog', 'dog', 'dog')

You cannot do the same with dictionaries; that would make multiple keys with the same entry name, which isn't valid in Python.


>>> x = {'dog':1}
>>> x * 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'dict' and 'int'


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.


>>> "I Love Wikipedia"[5]

simple enough.


Slicing is used to access a range of elements the way that indexing accesses one element.


>>> x = "Wikipedia and Python are awesome"
>>> 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.


>>> x = '1234'
>>> print(x[1:3])

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. [1] Type:

>>> x = "0123456789"
>>> x[1:-1:3]

You may also just use the step index. Type:

>>> x[::3]

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.


>>> x='0123456789'
>>> x[-2:1:-1]

To reverse a string (or any sequence):

>>> x[::-1]

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.

The Format Specifier[edit]

You are going to use this versatile command constantly. Type:

>>> DOS = "DOS"
>>> 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.


  1. "5.6. Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange". Python Software Foundation. 8 May 2011. Retrieved 8 May 2011. Has a table that explains the syntax behind this kind of splicing.