Python Tuple – Another Python Collection

There are lists, dictionaries, and tuples. These are all Python collections.

A Python tuple is like a non-changeable list. Instead of the square brackets that are used for lists, for tuples you use the regular parenthesis.

You are not able to use many of the methods on a Python tuple, because they are immutable. For example, you can not use sort, reverse, or append.

You can use the dir function to check what you can do with tuples, compared to lists.

Python tuple versus list
Compare what you can do with a Python tuple versus a list.

Why would you use tuples if they are not as capable as lists? You would use a Python tuple because it is more efficient, and they require less memory. You should use Python tuples when creating a collection that is temporary.

Two Way TuplesA nice thing about Python is you can do two things in one by placing a tuple on both the left and right side of an assignment statement.

Two Way Tuples 2Please note, the left-hand side must contain variables. Also, you can omit parenthesis on the left-hand side.

If you remember, the ‘items’ method for a Python dictionary returns a (key, value) pair. This pair is a Python tuple, so you can use a tuple as an iteration variable to loop through a dictionary.

Another nice thing about tuples is they are comparable. Comparison operators work with tuples. The first element will be compared first. If they are equal, then Python will move to the next element. It stops when it finds elements that differ.

Comparable Tuples

Compare and Sort a Python Tuple

This ability to compare Python tuples is a nice feature, because things that can be compared can also be sorted. You can use the built-in sorted function to do this, like in the following example.

#Create a dictionary. A dictionary can not be sorted.
>>>d = {‘alpha’:5, ‘charlie’:3, ‘beta’:4}
#Assign to variable x a sorted list of tuples.
>>>x = sorted(d.items())
>>>x
[(‘alpha’, 5), (‘beta’, 4), (‘charlie’, 3)]

 

Notice it only sorts the key. You can loop through this to print in sorted key order.

>>>for k, v in sorted(d.items()):
… print k, v

alpha 5
beta 4
charlie 3

 

Do you remember finding the most common word program? What if you want to find the five most common words? Rather than sort through the key, you will want to sort the value in descending order.

#Create a dictionary. A dictionary can not be sorted.
>>>d = {‘alpha’:5, ‘charlie’:3, ‘beta’:4}
#Creat a temporary list.
>>>temp_list = list()
#Loop through the dictionary, but append the value first!
>>>for k, v in d.items():
… temp_list.append( (v,k) )

>>>print temp_list
[(3, ‘charlie), (4, ‘beta’), (5, ‘alpha’)]
#Reverse the sorted order of values.
>>>temp_list.sort(reverse=True)
>>>print temp_list
[(5, ‘alpha’), (4, ‘beta’), (3, ‘charlie’)]

 

The following is a program that will find the ten most common words in a text file.

10 most common words program
A Python program for finding the 10 most common words.

Once you become comfortable with this program, you can begin to understand ways to condense your code. The concept of list comprehension can make a dynamic list in one line.

# Start with the dictionary.
>>> d = {‘alpha’:5, ‘charlie’:3, ‘beta’:4}
# Use list comprehension to make a dynamic list.
>>> print sorted( [(v, k) for k, v in d.items()] )
[(3, ‘charlie), (4, ‘beta’), (5, ‘alpha’)]

 

The syntax inside the parenthesis serves as the list comprehension. It dynamically creates a list of the pair (v, k) as it itereates through the key, value pairs inside the dictionary. This syntax is rather dense, but you can use it as you become more comfortable programming in Python.

Python Dictionary – Powerful Data Collection

A collection, in Python, is like a piece of luggage that we can put things in. A variable is not a collection, because it stores only one value. Once a new value is assigned, the old value goes away. A Python dictionary, however, is considered a collection.

A Python dictionary allow us to store many things. The work like a variable that serves as an aggregate of many values.

The difference between a list and a dictionary is how the values are stored. A list is a linear collection, indexed by a value starting at zero. A Python dictionary is more like a bag of things. The things are not stored in any particular order, but each thing has its own label. We call the label a ‘key’, and the thing is its ‘value’.

A Python Dictionary are considered the most powerful data collection in Python. In other programming languages they are called different names like associative arrays, hash maps, or property bags.

You can create a Python dictionary as follows:

>>>suitcase = dict()
>>>suitcase[‘socks’] = 5
>>>suitcase[‘shirts’] = 3
>>>suitcase[‘pants’] = 2
>>>print suitcase
{‘socks’: 5, ‘shirts’: 3, ‘pants’: 2}

The socks, shirts, and pants are the ‘keys’ and the quantities are their ‘values’.

>>>suitcase[‘shirts’] = suitcase[‘shirts’] + 1
>>>print suitcase[‘shirts’]
4

That’s right! You just added to the value of shirts. However, unlike a Python list, there is no preserved order in a Python dictionary. Lists preserve order, dictionaries do not. Therefore, when you print the contents of a dictionary, do not expect it to come out in the same order you added the ‘key’: ‘value’ pairs.

You will get a traceback error if you reference a ‘key’ that is not in your dictionary. You check to see if the ‘key’ exists.

>>> print ‘underwear’ in suitcase
False

You can make an empty dictionary using curly brackets.

>>>empty_dic = {}

A common use for Python dictionaries is counting how often we see something.

counts = dict()
names = [‘bob’, ‘ted’, ‘bill’, ‘ted’, ‘bob’]
for name in names:
++++if name not in counts:
++++++++counts[name] = 1
++++else:
++++++++counts[name] = counts[name] + 1
++++print counts

The above Python script should print {‘bob’: 2, ‘ted’: 2, ‘bill’: 1}

This pattern is so common that Python has a built-in method called ‘get()’ that does it for us. For example, print counts.get(name, 0) will return the name and its value, but if the name does not exist then it starts the value at zero. It’s a very valuable method.

Using this ‘get() method, the above Python script can be condensed as follows:

counts = dict()
names = [‘bob’, ‘ted’, ‘bill’, ‘ted’, ‘bob’]
for name in names:
++++counts[name] = counts.get(name, 0) + 1
print counts

The following script will count the occurrence of each word in a line of text.

counts = dict()
print ‘Enter a line of text:’
line = raw_input(”)

words = line.split()
print words

for word in words:
++++counts[word] = counts.get(word, 0) + 1

print counts

Another common task is to use a definite loop on Python dictionaries.

for key in counts:
++++print key, counts[key]

The key is the actual word, and counts[key] is how many times the word was counted.

You can retrieve lists of keys and values with other built-in methods. For example, counts.keys() or counts.values(). There is counts.items(). This will return both keys and values. Each pair is referred to as a tuple. You can then loop through each key-value pair using two iteration variables.

for x, y in counts.items():
++++print x, y

Note, x is the ‘key’ and y is the ‘value’.

Now you should be able to fully understand the following script. It returns the most used word from a text file.

name = raw_input(‘Enter file:’)
handle = open(name, ‘r’)
text = handle.read()
words = text.split()
counts = dict()

for word in words:
++++counts[word] = counts.get(word, 0) + 1

bigcount = None
bigword = None
for word,count in counts.items():
++++if bigcount is None or count > bigcount:
++++++++bigword = word
++++++++bigcount = count

The Python List – Delve Into Data Science

Knowing how to manipulate a Python List is where you can really delve into data science. A Python list has square brackets. It is a collection wherein we assign multiple values to one variable. It is important to know how to find certain values within your lists.

Lists do not have to be of a single value type. However, converting a list to a numpy array will coerce the list to a single data type. A Python List should be converted to a numpy array if, for example, you want to make a scatter plot.

Lists can exist inside of a list.

You can look up values in a list, similar to how you lookup values in a string.

Remember the index operator from the lesson about Python strings?

>>> colors = [‘blue’, ‘green’, ‘red’]
>>> print colors[1]
green

 

Do not forget index values start at zero. That is why the above example returns ‘green’.

However, while strings are immutable, lists are mutable. This is a great feature of lists.

>>> lucky_numbers = [3, 21, 7, 68, 93]
>>> lucky_numbers[4] = 36
>>> print lucky_numbers
[3, 21, 7, 68, 36]

 

See! The fourth index value of the list was changed.

You can use ‘len’ to know the length of a list.

>>> print len(lucky_numbers)
5

 

You can use a range function.

>>> print range(len(lucky_numbers))
[0, 1, 2, 3, 4]

 

Now you know that lucky_numbers has a range of five values. You might want to loop through the list, while keeping track of the range value.

for i in range(len(lucky_numbers)):
++++number = lucky_numbers[i]
++++print number

 

You can concatenate lists with the ‘+’ operator.

You can slice a Python list. Again, this is similar to strings.

>>> print lucky_numbers[0:3]
[3, 21, 7]

 

There are many Python list methods that are built-in functions to do useful things to your list.

For example, you can append to a list.

>>> things = list()
>>> things.append(‘food’)
>>> things.append(5)
>>> print things
[‘food’, 5]

 

Find if something is, or is not in a list.

>>> ‘book’ in things
False
>>> 7 not in things
True

 

The ‘sort’ method will force a list to sort itself, like alphabetically for example.

There are lots great methods for lists of numbers, such as max, min, and sum.

You can loop through an input of numbers, and build a list.

A list building example.
How to loop through user input, and build a list with the input.

A very powerful method is ‘split’. This allows us to split a string into a list of words.

>>> lyric = ‘three little birds’
>>> words = lyric.split()
>>> print words
[‘three’, ‘little’, ‘birds’]

 

Split sees many spaces as just one space. So, if a line has lots of space at the end, then split will discard all that extra spice. This is very convenient.

Data could consist of no spaces, where every string is delimited by a comma, for example. You would pass the comma in as an argument to split.

>>> jibberish = ‘heh,reh,vtv’
>>> jiblist = jibberish.split(‘,’)
>>> print jiblist
[‘heh’, ‘reh’, ‘vtv’]

 

Python Open Function – Read Text Files

Text files are stored in secondary memory, so you need a way that tells Python where to go look for the text file we want it to read. This is what the built-in, Python open function is for.

For example:

handle = open(readme.txt, r)

In this example we assigned a variable name of handle that we can use to manipulate the file. The first parameter inside the parenthesis is the actual file name we want to open, and the second parameter of r indicates read mode. The other option is w for write mode, but for now we will use the read mode. The mode r is chosen by default for the Python open function if left blank.

It is important to note that the variable handle is not the file itself. Rather, it is a mechanism to use the file. To keep things simple, you want your text file to be in the same folder as your Python code file.

Before moving forward, you have to understand there is a special character to use that indicates when a line ends.

The New Line Character

>>>print ‘XY’
XY
>>>print ‘X\nY’
X
Y

The \n character tells us we start on a new line.

>>len(‘X\nY’)
3

You see that the new line character counts as only one character, even though it is technically two. Think of \n as syntax to encode a new line in a string.

You have to mentally visualize the new line character as being there at the end of lines in text files. Text editors do not show us this character when we are just looking at the text, but they are encoded there, and you have to know that.

The Efficiency of the Python Open Function

You can print every line in a file with three lines of Python code.

xfile = open(readme.txt)
for line in xfile:
++++print line

You can count the lines in a file with six lines of Python code.

xfile = open(readme.txt)
count = 0
for line in xfile:
++++count = count + 1
print ‘Line Count=’, count

Notice in these examples we used xfile instead of handle as our variable name. That is okay, it is just a variable name.

You can also read every character of a text file into one string. You would use the built-in read function.

xfile = open(readme.txt)
one_string = xfile.read()
print len(one_string)

This program will print the number of characters in your text file. In other words, it prints the length of one string.

You could print the first 20 characters.

print one_string[:20]

Select Only the Text You Want

Suppose you have a fairly large text file, and you only want to print only lines that start with the word ‘Time’.

xfile = open(readme.txt)
for line in xfile:
++++line = line.rstrip()
++++if line.startwith(‘Time’):
++++++++print line

You might be thinking, what is the purpose of line = line.rstrip()? Well, this bit of code strips the newline character from the text file. It is a built-in function that removes the whitespace so your program will not print blank lines.

You can skip a line by using the continue statement. The following Python code will skip every line that does not start with ‘I’.

xfile = open(readme.txt)
for line in xfile:
++++line = line.rstrip()
++++if not line.startwith(‘I’):
++++++++continue
++++print line

You can use ‘in’ to select lines. The following Python code will only select lines containing the ‘$’ character:

xfile = open(readme.txt)
for line in xfile:
line = line.rstrip()
++++if not ‘$’ in line:
++++++++continue
++++print line

How to Catch Bad User Input

Use this code to prompt a user for a file. This will catch a bad file if the user does not enter the file name correctly, or if the file does not exist.

xname = raw_input(‘Enter the file name: ‘)
try:
++++xfile = open(xname)
except:
++++print ‘File cannot be opened’
++++exit()

The Python String – Parse It!

A Python string is a sequence of characters. You can use single or double quotes to delimit a string.

We can look inside a Python string with the index operator. Use the square brackets for this, []. You must know that the index value is an integer and always starts at zero.

>>> creature = ‘monkey’
>>> print creature[0]
m

The output is m because the index value of a string always starts at zero. In other words, m is the first index value of the string ‘monkey’.

>>> x = 4
>>> print creature[x-1]
k

An expression can exist inside the index operator. Got it? Good!

Sometimes you need to know the length of a string.

>>> l = len(animal)
>>> print l
6

That’s right! The string ‘monkey’ has six characters. Note that len is a built-in function. It’s already been written for us, we just have to apply it.

You can loop through strings. The following is Python program to loop through a particular Python string.

food = ‘pizza’
for letter in food:
++++print letter

In the above program, the word letter is being used as an iteration variable.

You can write a Python program to count the occurrence of a letter in a string.

bigword = ‘supercalifragilisticexpialidocious’
count = 0
for letter in bigword:
++++if letter == ‘i’:
++++count = count + 1
++++print count

Slicing the Python String

You can slice a Python string to get a substring.

>>> bigword = ‘supercalifragilisticexpialidocious’
>>> slice = bigword[0:5]
>>> print slice
super

You can see that it will slice up to, but not including the second index value. The fifth index value is the letter c, but that is not include in our slice.

If you omit a the first or second index value, it will assume the beginning or end respectively.

>>> slice = bigword[:]
>>> print slice
supercalifragilisticexpialidocious

You can look for values.

>>> ‘x’ in bigword
True

Yes indeed! The letter x is in supercalifragilisticexpialidocious.

There is an extensive Python string library. These are built-in functions we can invoke on strings.

>>> greet = “HOw aRe YOu?”
>>> print greet.lower()
how are you?

You can look for a character and know its index value.

>>>idea = ‘Learn Python Programming Language’
>>>print idea.find(‘Python’)
6

Correct! Python start at the sixth index value of the string. Remember, index values start a zero!

Stripping Whitespace

You need to know how to remove whitespace at the beginning or end of strings. These are lstrip, rstrip, and strip. They remove whitespace from the left, right, and both sides respectively.

>>> color = ‘ blue’
>>> print color
++++blue
>>> print color.lstrip()
blue

See how that works? Great!

Sometimes you need to extract lines that begin with a certain string.

>>> line = ‘Email message sent at….’
>>> line.startswith(‘Email’)
True

These examples show how Python is really good at parsing data.

Python Loop – Simple Examples to Learn

A Python loop is what you can use to make computers do repeated processes that humans would quickly grow tired of. However, computers do not grow tired of repeated processes.

Python Loop
A Python loop can be used to repeat a process many times.

A Python loop usually will contain an iteration variable. This variable will change each time it goes through the loop.

Avoid an infinite loop, because those cause the CPU to crash. The iteration variable controls how many times the Python loop will run.

Beware the Infinite Python Loop

Below is an example of an infinite loop. You can see the error in logic that would cause the loop to never stop.

x = 3
while x > 0:
++++x = x + 1
++++print ‘I am going to crash!’

 

If you started the value of x at zero or below, then the above Python loop would never run. That would be called a zero trip loop.

How to ‘Break’ the Loop

Another way to force out of a loop is to use the Python reserved word ‘break’. Look at the example below of how this can be used. The loop will stop when the user enters ‘done’.

A Python loop with break.
User input ‘done’ will cause the loop to stop.

Skip and Continue

Another useful statement for a Python loop is ‘continue’. The continue statement stops the current iteration and jumps to the top of the loop for the next iteration. Thus, ‘continue’ does not stop a loop, it just allows you to skip certain iterations.

while True:
++++word = raw_input(‘ ‘)
++++if word == ‘skip’:
++++++++continue
++++if word == ‘done’:
++++++++break
++++print word
print ‘Done!’

 

The above example demonstrates a Python loop that will skip an iteration if the user enters the word ‘skip’.

From the Indefinite to the Definite Python Loop

These examples thus far of ‘while’ loops are often called indefinite loops. They will run until a logical condition becomes false. The examples here have been simple, but with more complex code comes the need for extra precaution. At some point the condition must become false, or else the loop will be infinite.

A definite loop is a type of loop that will iterate a finite number of times. The Python reserved word used to construct an infinite loop is ‘for’.

Python For Loop
Another Screenshot from Dr. Chuck’s Python Course at Coursera

A for loop does not just have to iterate through a set of numbers. It can iterate through a set of strings as well.

cities = [‘Los Angeles’, ‘Dallas’, ‘New York’, ‘Rome’]
for city in cities:
++++print city, “is a famous city.”

 

A for Python loop takes on the responsiblity of advancing the iteration variable. In essence, the iteration variable moves through all the values in the sequence.

Give Your Loop Intelligence

Loop idioms are how you construct a loop. The idea is to give the loop intelligence. Start by knowing what the Python loop wants, and then approach that by writing one line of code at a time. Think of this process in three steps.

  1. Set some variables for the loop.
  2. Do something to each variable.
  3. Return a result.

Imagine you have a list of 100,000 numbers, and you need to find the largest number. The example below demonstrates with a small set of numbers, but the same loop would apply no matter the size of the number set.

Find the Largest Value Loop
A Python loop for finding the largest value from a list.

Finding the average of a list of numbers is a classic programming problem. To accomplish this, you need to introduce a count variable. The count variable will keep track of the amount of members in a set. Look at the following example.

count = 0
sum = 0
set = [89, 78, 90, 87, 94]
for value in set:
++++sum = sum + value
++++count = count + 1
print ‘The average is’, sum / count

 

Use a conditional if statement within a Python loop to filter values. For example:

for value in [89, 78, 90, 87, 94]:
++++if value >= 90:
++++++++print value, “is one of your best grades!”
print “Good Job!”

 

You can also search using a Boolean variable.

A_grade = False
for value in [89, 78, 90, 87, 94]:
++++if value >= 90:
++++++++A_grade = True
++++++++print “You got an A!”
++++++++break

 

In the above example, the condition will change to true on the third iteration. The break statement will then prematurely stop iterating through the list.

It is easy to see that a loop could be integral to many types of Python functions.

Do you have what it takes to learn Python? Boost your career potential, and get on the Python specialization track at Coursera. Financial aid may be available to those who qualify.

 

Python Functions – Store and Reuse Your Code

Python Functions Example
Understand the output.

Python functions can be very useful. Python functions store logical steps that can be reused.

The advantage with a function is it can be invoked, rather than having to always retype the lines of code that consist of the function.

The Python reserved word to store a Python function is ‘def’. If you start a line of code with ‘def’, it tells Python to store the function, but to only run it if it is called on later.

Python Functions Examples

def hello():
++++print ‘Hello’
hello()

The first two lines in this example are the Python function. The last line below it invokes the function. The Python function will not execute until it is invoked.

Invoking a Built-In Python Function

A Python function could be built-in, so all you have to do is invoke it.

>>> big = max(‘Hello World’)
>>> print big
w

In the above example, ‘max’ is the built-in Python function. The string inside the parenthesis is called the argument. The argument passes through the function. The ‘max’ function then returns the highest character of a string.

Other common built-in functions are ‘float’, and ‘int’. There are many built-in Python functions. However, A Python function you write yourself is called a user defined function.

A Python Function with Arguments

Look at the following Python function:

def addition(x, y):
++++sum = x + y
++++print sum

 

Now you can invoke the function with two function arguments, as follows:

addition(5, 3)

 

Invoking this function should cause ‘8’ to be printed.

Now look at a slightly modified version of the addition function:

def addition(x, y):
++++sum = x + y
++++return sum

 

Notice the word ‘return’ was used. This gives you a return value, and it terminates the function. However, it does not print the value. You control where it prints, such as:

print addition(1, 2)

 

The number ‘3’ would be printed because that would be the return value.

You will not always need to write a Python function in your program, but if you catch yourself reusing code, it might be best to put that code in a Python function that can simply be invoked when you want to execute it.

Get started with interactive Python practice at Codecademy. You will start with the basics, and quickly ramp up to writing your own functions.

 

Python Conditional Execution Explained

A Python conditional may involve steps in a program that may or may not be executed.

Look at the following Python conditional program:

x = 0
if x == 0:
++++print x, ‘is nothing.’
else:
++++print x, ‘is something’

 

Think of the word ‘if’ as asking a question. The above Python conditional is asking if x is equal to zero. In this case it is, so the indented statement directly under the ‘if’ question gets executed. Consequently, the ‘else’ is ignored. The opposite would be true if x was any other value.

Know The Python Conditional Comparison Operators

You will need to be familiar with all the comparison operators to be proficient with Python conditional logic.

Python Conditional Comparison Operators
Take a moment to study these comparison operators.

Look at how to modify the above program to effectively do the same thing.

x = 0
if x != 0:
++++print x, ‘is something’
else:
++++print x, ‘is nothing.’

 

Remember that comparison operators only look at a value, they do not change it. Hence, there is a difference between ‘=’ and ‘==’. The first assigns a value, and the latter looks at a value.

Boolean expressions use comparison operators to evaluate to ‘True’ or ‘False’.

smart = True
if smart:
++++print ‘Congratulations!’

 

Indentation is very important for a Python conditional to execute properly. The convention is four spaces, but that’s not a hard fast rule. All lines that are part of a conditional should be indented. De-indenting ends the conditional.

x = 0
if x == 0:
++++print x, ‘is nothing.’
++++print ‘sorry’ ,x
else:
++++print x, ‘is something’
++++print ‘way to go’, x,

 

Warning! Your text editor may see indenting with a tab differently than indenting with spaces. Use spaces to indent for Python. The alternative is to go into the properties of the text editor, and change the tab settings to be seen as spaces.

Using Python Conditional Logic for Nested Decisions

A Python Conditional can be nested inside other conditionals.

x = -1
if (x > 0):
++++print x, ‘is not negative’
++++if (x > 1000000):
++++++++print x, ‘is quite large’

 

In the above program, None of the conditionals will execute, because x is negative. If x is 100, then only the first conditional executes. If x is 1000001, then both conditionals execute.

A Python Conditional for Multi-Way Decisions

You can also write conditionals that involve multi-way decisions. Use the Python reserved word, ‘elif’. It means else if. Look at the following program:

x = 3
if (x < 3):
++++print ‘Small’
elif (x < 7):
++++print ‘Medium’
else:
++++print ‘Large’

 

In the above program, x would be medium. Many ‘elif’ statements maybe be used. Only one ‘else’ statement can be used.

Look at the following puzzles, and try to identify the defective line in each program. Both the left and right side programs have a defective Python conditional.

Python Conditional Multi-Way Puzzles
Look for the Python Conditionals that will never execute.

The ‘try’ and ‘except’ Special Python Conditional

The ‘try’ and ‘except’ conditional has limited use, but can be handy when building a program with some dangerous code.

This concept might be hard to imagine, so take a look at the example, for conceptual purposes.

my_string = ‘nine’
try:
++++my_number = int(my_string)
except:
++++my_number = 9

 

The code ‘my_number = int(my_string)’, is the dangerous code. It is going to blow-up the program because you can not use ‘int’ on a string. However, the program is rescued by the two lines that come below that.

This special Python conditional could be useful for controlling user input, for example. Sometimes users will make mistakes when giving input. A good program can work around user mistakes. Use the special conditional as a work around while building new programs.

Here is a solution to the classic calculate pay problem. In this problem you have to use a conditional to calculate pay because there are two pay scales – regular and overtime. How might you solve this problem with your own Python program?

 

Python Variables and Operators

Python Variables

Using variables is one of the most powerful features in Python. Use assignment statements to create variables and give them values.

From the chevron prompt in the Python interpreter:

>>> x = 12
>>> message = “You are doing a good job!”

 

In the code samples above, two variables were created. Now you could tell Python:

>>> print x
12
>>> print message
“You are doing a good job!”

 

You can name variables with almost whatever you want, but it is good practice to give them a name that is meaningful.

The two main rules for naming variables are:

Python Operators

You need to know how to use operators ‘+, -, *, /, and **’. The operator ‘**’ is for exponentiation.

The order of operations follows the same PEMDAS rules. For example:

>>> x = 2 + 3 * 5
>>> print x
17

 

Beware of the Division Operator

The division operator might not do what you expect.

>>> y = 1 / 2
>>> print y
0

 
Why zero? When both operands are integers, the result is an integer. In other words, the decimal part gets chopped off. To solve this you have to use float types.

>>> y = float(1) / float(2)

 

One other operator, that is surprising useful, is ‘%’, the modulus operator. It yields the remainder.

>>> y = 5 % 2
>>> print y
1

 

Finally, use the ‘+’ operator for concatenation. That is, joining strings together.

>>> print ‘Hello,’ + ‘ World!’
Hello, World!

 

Python Values – Know the Type

Python values are basic things the language works with. Python values belong to different types. Use the Python interpreter to ask for the type of a given Python value.

Below are examples of input and output from asking Python for types of various Python values. The chevron prompt “>>>” is input for Python, and the line below is output from Python.

>>> type('Cookies')
<type 'str'>

>>> type(3)
<type 'int'>

>>> type(3.0)
<type 'float'>

>>>type('3.0')
<type 'str'>

 

The first type means string. After that it’s, integer, floating number, and string. Notice that if you put quotations around a number, it becomes a string.

While it might be habit, refrain from using commas with large numbers. It will cause a semantic error, because Python would interpret it as a comma separated sequence of numbers.