Python Concepts/Operators

Operations, The Format Specifier, and Other Commands

edit

Operations

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.

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

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
>>> x + y
6


That is how the variable works.

Type:

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

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

Concatenating

edit

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

Type:

>>> "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')


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
dogdogdogdogdog


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.

Type:

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

Indexing

edit

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:

>>> "ILove Wikipedia"[7]
'i'

simple enough.

Slicing

edit

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

Type:

>>> x = "Wikipedia and Python is awesome"
>>> print(x[14:31])
Python is 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'
>>> 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. [1] Type:

>>> x = "0123456789"
>>> x[1:-1:3]
'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'
>>> 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.

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.

References

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