Sunteți pe pagina 1din 129

Table

of Contents
1. Introduction
2. What is Python?
3. Python in Erle
4. First steps
i. Introducing comments
ii. Displaying values on the screen
iii. Variables
i. Integer and float variables
ii. Boolean variables
iii. String variables
iv. Asking the user for input
v. Random numbers
iv. Identation
v. Math operators
vi. Date and time Records
vii. Exercises: First steps
5. Control flow
i. Logical operators
ii. Conditional statements
iii. Errors and Exceptions
iv. Exercises: Control flow
6. Functions
i. Function basics: Defining functions
ii. Importing functions
iii. Built-in functions
iv. Exercises: Functions
7. Lists and Dictionaries
i. Lists basics
i. Strings as a list
ii. For loop with lists
iii. Function + Lists
ii. Dictionaries basics
i. For loop with dictionaries
ii. Iterators for dictionaries
iii. Exercises: List and Dictionaries
8. Exercise:Battleship
i. Battleship
ii. Solution:Battleship
9. Loops
i. Loops basics
ii. While loops
iii. For loops
iv. Exercises: Loops
10. Exercise: Exam statistics
i. Exam statistics
ii. Solution:Exam statistics
11. Advanced topics in Phyton
i. List Comprehensions
ii. List Slicing
iii. Lambdas
iv. Exercises:Advances topics in Python
12. Introduction to Bitwise Operators

i. Bitwise operators basics


ii. The Base 2 Number System
iii. Bitwise operators
iv. Advanced concepts about bitwise operators
v. Exercises:Introduction to Bitwise Operators
13. Classes
i. Classes basics
ii. Member variables and functions
iii. Inheritance
iv. Exercises:Classes
14. Exercise: Car
i. Car
ii. Solution:Car
15. File Input/Output
i. Files basics
ii. Exercises: File Input /Output

Erle Robotics Python Gitbook


book passing

Book
This book is a Python Programming Language tutorial using Erle board. Erle is a small-size Linux computer for
making drones.
Throught this tutorial you will find examples and explanations of how to use Python's sintaxis, variables, functions and so
on. Definitely, you will learn to program in Python language.

About
For years we've been working in the robotics field, particularly with drones. We have passed through different Universities
and research centers and in all these places we actually found that most of the drones are black boxes (check out our
60s pitch). Not meant to be used for learning, research. The software they use is in most of the cases unknown, closed
source or not documented. Given these conditions, how are we going to educate the next generations on this
technologies? How do you get started programming drones if you don't have $1000+ budget? Which platform allows me to
get started with drones without risking a hand?
We are coming up with an answer to all these questions, our technology at Erle Robotics and our drones brain: Erle-brain.

Inspired by the BeagleBone development board, we have designed a small computer with about 36+ sensors, plenty of I/O
and processing power for real-time analysis. Erle is the enabling technology for the next generation of aerial and terrestrial
robots that will be used in cities solving tasks such as surveillance, enviromental monitoring or even providing aid at
catastrophes.
Our small-size Linux computer is bringing robotics to the people and businesses.

License
Unless specified, this content is licensed under the Creative Commons Attribution-NonComercial-Share Alike 3.0 Unported
License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative
Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.

All derivative works are to be attributed to Erle Robotics S.L.. For a list of authors refer to erle_gitbook/graphs/contributors.
For any questions, concerns, or issues submit them to support [at] erlerobot.com.

What is Phyton?
Python is an interpreted programming language whose philosophy emphasizes a syntax that encourages readable code.
It is a multi-paradigm programming language, since it supports object-oriented, imperative programming and to a lesser
extent, functional programming. It is an interpreted language, it uses dynamic typing and is multiplatform. You can use it to
create web apps, games, even a search engine.

It is managed by the Python Software Foundation. It has an open source license called Python Software Foundation
License, 1 which is compatible with the GNU General Public License from version 2.1.1, and incompatible in some earlier
versions.
Python official website

Phyton in Erle
Open a Erle terminal and try typing:

python

If Python gets initialized, you are ready. Jump to the last paragraph of this page Compiling code. If not, follow the steps
bellow:
Installing and configuring Phyton
For installing and running Python in Erle, the first thing you should do is downloading python for Linux from the ofiicial
website (it is free): https://www.python.org/download/

Python 3.4.1 compressed source tarball (for Linux, Unix or Mac OS X)


Python 3.4.1 xzipped source tarball (for Linux, Unix or Mac OS X, better compression)

This two files are avaliable for Linux, so choose one.


You can donwload it directly in Erle, using the command line:

wget http://www.python.org/ftp/python/3.4.1/Python-3.4.1.tgz

The other option is to download it to your computer and then using scp command copy it to Erle. You can find the
instructions in this tutorial, more specifically ,in this section.
After that you need to extract the files, doing for example:

tar -xzf Python-3.4.1.tgz

You should configure the path and type:

./configure
make
sudo make install
sudo apt-get install python

For more information, or more detailed explanations, you can read this short tutorial.
Compiling code
After having Python installed, for compilling a code you have two possibilities:
Store the code in a python_file.py, and running it by typing:

python python_file.py

Typing:

python

And after that type the code.You can use quit() to exit.

First steps
Here you can find the basics of python programming.

Introducing comments
Single Line Comments
Comments make your program easier to understand. When you look back at your code or others want to collaborate with
you, they can read your comments and easily figure out what your code does.
The # sign is for comments. A comment is a line of text that Python won't try to run as code. It's just for humans to read.
Practice 1
Write a comment on line 1. Make sure it starts with #. It can say anything you like. The result when running a comment on
the interpeter must be the following one:

root@erlerobot:~# touch Comment.py


root@erlerobot:~# echo ' #This is a comment (readonly)' > Comment.py
root@erlerobot:~#
root@erlerobot:~#
root@erlerobot:~# python Comment.py
root@erlerobot:~#

Multi-Line Comments
The # sign will only comment out a single line. While you could write a multi-line comment, starting each line with #, that
can be a pain.
Instead, for multi-line comments, you can include the whole block in a set of triple quotation marks:

"""This is a paragraph containing


readonly comments"""

Displaying values on the screen


For displaying a desired sentence os text on the scrren you should use a simple sintaxis, like the following one:

print " Text goes here"

You can also display numbers and varibales:

print number

print varibale

The , character after our print statement means that our next print statement keeps printing on the same line.
Practice 1
Create a file with a "Hello world " message and display it on the screen:

root@erlerobot:~# touch Hello.py


root@erlerobot:~# echo 'print "Hello World!"' > Hello.py
root@erlerobot:~# python Hello.py
Hello World!
root@erlerobot:~#

Practice 2
Create a file containing three numbers and print them on the screen:

root@erlerobot:~/Python_files# touch Num.py


root@erlerobot:~/Python_files# echo 'print 1' >> Num.py
root@erlerobot:~/Python_files# echo 'print 4' >> Num.py
root@erlerobot:~/Python_files# echo 'print 6' >> Num.py
root@erlerobot:~/Python_files# python Num.py
1
4
6

Practice 3
Display a variable on your screen:

root@erlerobot:~/Python_files# python
Python 2.7.3 (default, Sep 26 2013, 21:37:06)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Like this you initialize the python program.

>>> var="Hello"
>>> print "this is the variable: ", var
this is the variable: Hello

Notice that we have use the two methods of running Python.

Variables
Creating web apps, games, and search engines all involve storing and working with different types of data. They do so
using variables. A variable stores a piece of data, and gives it a specific name.

Integer and float variables


Integer refers to an integer number.For example:
my_inte= 3
Float refers to a decimal number, such as:
my_flo= 3.2
You can use the commands float() and int() to change from onte type to another:

>>> float (8)


8.0
>>> int(9.5)
9
>>>

Boolean variables
A boolean is like a light switch. It can only have two values. Just like a light switch can only be on or off, a boolean can only
be True or False.
You can use variables to store booleans like this:
a = True
b = False

String variables
Another useful data type is the string. A string can contain letters, numbers, and symbols.
For example:
name = "Ryan"
age = "19"
food = "cheese"
There are some characters that cause problems. For example:
'There's a snake in my boot!'
This code breaks because Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to fix the
problem(for escaping characters), like this:
'There\'s a snake in my boot!'
Each character in a string is assigned a number. This number is called the index.
The string "PYTHON" has six characters, numbered 0 to 5, as shown below:
P
0

Y
1

T
2

H
3

O
4

N
5

So if you wanted "Y", you could just type "PYTHON"[1] (always start counting from 0!).
Pratice 1
Assign the variable fifth_letter equal to the fifth letter of the string "MONTY". Remember that the fifth letter is not at index 5.
Start counting your indices from zero.

>>> fifth_letter = "MONTY"[4]


>>> print fifth_letter
Y
>>>

String methods
Now that we know how to store strings, let's see how we can change them using string methods.
String methods let you perform specific tasks for strings.
We'll focus on four string methods: len() , lower() , upper() , str() .
len() The output when using this method will be the number of letters in the string.

>>> parrot="Norwegian Blue"


>>> len(parrot)
14
>>> print len(parrot)
14

lower() You can use the lower() method to get rid of all the capitalization in your strings.

>>> print parrot.lower()


nowegian blue

upper() A similar method exists to make a string completely upper case.

>>> parrot = "norwegian blue"


>>> print parrot.upper()

str()
Now let's look at str(), which is a little less straightforward. The str() method turns non-strings into strings.

>>> pi=3.14
>>> pi_1= str(pi)
>>> type(pi_1)
<type 'str'>

Notice that methods that use dot notation only work with strings.On the other hand, len() and str() can work on other data
types.
You can work with integer, string and float variables. But don't mix string variables with float and integer ones when making
concatenations:

>>> width+'Hello'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Sometimes you need to combine a string with something that isn't a string. In order to do that, you have to convert the nonstring into a string using `str()``.

>>> print "The value of pi is around " + str(3.14)


The value of pi is around 3.14

String Formatting with %


When you want to print a variable with a string, there is a better method than concatenating strings together.The % operator
after a string is used to combine a string with variables. The % operator will replace a %s in the string with the string
variable that comes after it.
Practice 2
We are going to print a message like this: " ---- is an awesome ----!". Where instead of --- we will introduce two strings:

>>> string_1="Erle"
>>> string_2="drone"
>>> print " %s is an awesome %s!"%(string_1,string_2)
Erle is an awesome drone!
>>>

Asking the user for input


Sometimes we would like to take the value for a variable from the user via their keyboard. Python provides a built-in
function called raw_input that gets input from the keyboard (We will see fuctions later) .When this function is called, the
program stops and waits forthe user to type something. When the user presses Return or Enter, the program resumes and
raw_input returns what the user typed as a string.

Practice 1
We are going to make a programm that ask your name and your favorite color and shows a message.
We store this code into a file called Raw.py:

name = raw_input("What is your name?")


color = raw_input("What is your favorite color?")
print "Ah, so your name is %s and your favorite color is %s." % (name, color)

Now we execute this file:

root@erlerobot:~# python Raw.py


What is your name? Paul
What is your favorite color? black
Ah, so your name is Paul and your favorite color is black.
root@erlerobot:~#

Random numbers
The random module provides functions that generate pseudorandom numbers. For using this module capabilities you
should firts import it, with the syntxis:

from random import function

The most used random number generators are:

random.randint(a, b)

This returns a random integer N such that a <= N <= b. The other is:

random.random()

The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0).
Practice 1
Create two numbers: num1 using randit and num2 using random.Print them:

>>> from random import randint


>>> num1=randint(5,7)
>>> print num1
5
>>> from random import random
>>> num2=random()
>>> print num2
0.769876247837
>>>

Identation
Whitespace
In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it.
Practice 1
The code on the right is badly formatted.

def spam():
eggs = 12
return eggs
print spam()

You should see an error message like this one:

File "<stdin>", line 2


eggs = 12
^
IndentationError: expected an indented block

Now let's examine. You'll get this error whenever your whitespace is off.
To correct this you should properly indent the code with four spaces before eggs on line 2 and another four before return on
line 3.
You should indent your code with four spaces.

>>> def spam():


... eggs = 12
... return eggs
...
>>> print spam()
12

Math operators
With Python you can add, subtract, multiply, divide numbers like this:
addition = 72 + 23
subtraction = 108 - 204
multiplication = 108 * 0.5
division = 108 / 9
exponentiation = 2 ** 3
modulo: Our final operator is modulo. Modulo returns the remainder from a division. So, if you type 3 % 2, it will return
1, because 2 goes into 3 evenly once, with 1 left over.
Operators Summary
Operator

Meaning

addition

subtraction

multiplication

division

**

power

remainder of a division

Practice 1
We are going to do the following operations:
Create a integer variable num equal to the sum of two numbers.
Squar num variable.
Multiply num from a new variables called num1 equal to the division of two numbers.

>>> # create num variable


...
>>> num = 23 +90
>>> # Notice that a variable can be squared
...
>>> num ** 2
12769
>>> #Create the new variable num1
...
>>> num1= 56/71
>>> print num1
0
>>> #Notice that the division gives integers
... num1=float(56/71)
>>> print num1
0.0
>>> #Now num1 is a decimal (float variable)
...
>>> num*num1
0.0
>>>

Practice 2
We are going to follow the steps bellow:
Create two string variables.

Sum them.

>>>
>>> #Create two string variables
...
>>> var1 = 'Hello'
>>> var2=' World'
>>> #Sum string variables
...
>>> var1+var2
'Hello World'
>>>

Be careful!
When you divide or multiply a integer by a float variable the result becomes float as well.
When you divide an integer by another integer, the result is always an integer (rounded down, if needed).
When you divide a float by an integer, the result is always a float.
To divide two integers and end up with a float, you must first use float() to convert one of the integers to a float.
When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence.
For mathematical operators, Python follows mathematical convention. You can use brackets () to reorder the
operations.

Date and time Records


A lot of times you want to keep track of when something happened. We can do so in Python using datetime.
Here we'll use datetime to print the date and time in a nice format.
We can use a function called datetime.now() to retrieve the current date and time.

>>> from datetime import datetime


>>> print datetime.now()
2014-07-01 16:28:34.848183
>>>

The first line imports the datetime library so that we can use it.The second line will print out the current date and time.
You can also store part of the date:

>>> from datetime import datetime


>>> now= datetime.now()
>>> print now.year
2014
>>> print now.month
7
>>> print now.day
1
>>>

You can also print now.hour , now.minute , now.second .

Exercises: First steps


Exercise 1
Assume that we execute the following assignment statements: width = 17 height = 12.0 For each of the following
expressions, write the value of the expression and the type (of the value of the expression).
1. width/2
2. width/2.0
3. height/3
4. 1 + 2 * 5 Use the Python interpreter to check your answers.
Exercise 2
You've finished eating at a restaurant, and received this bill:

Cost of meal: $44.50


Restaurant tax: 6.75%
Tip: 15%
You'll apply the tip to the overall cost of the meal (including tax).

Steps to follow:
First, let's declare the variable meal and assign it the value 44.50.
Now let's create a variable for the tax percentage: The tax on your receipt is 6.75%. You'll have to divide 6.75 by 100 in
order to get the decimal form of the percentage. Create the variable tax and set it equal to the decimal value of 6.75%.
You received good service, so you'd like to leave a 15% tip on top of the cost of the meal, including tax. Before we
compute the tip for your bill, let's set a variable for the tip. Again, we need to get the decimal form of the tip, so we
divide 15.0 by 100. Set the variable tip to decimal value of 15% .
Reassign in a Single Line We've got the three variables we need to perform our calculation, and we know some
arithmetic operators that can help us out. (We saw in 3.3 Variables that we can reassign variables. For example, we
could say spam = 7, then later change our minds and say spam = 3.) Reassign meal to the value of itself + itself *
tax .

We're only calculating the cost of meal and tax here. We'll get to the tip soon. Let's introduce on new variable, total,
equal to the new meal + meal * tip .
Insert at the end this code `print("%.2f" % total). This code print to the console the value of total with exactly two
numbers after the decimal.
Exercise 3
Practicing with string variables, follow the steps:
1. create the variable my_string and set it to any string you'd like.
2. print the length of my_string .
3. print my_string on capital letters.
Exercise 4
Write a program to prompt the user for hours and rate per hour to compute gross pay. The data should be:

Enter Hours: 35
Enter Rate: 2.75

Pay: 96.25

Exercise 5
Print the date and time together in the form: mm/dd/yyyy hh:mm:ss .
Exercise 6
Write a program which prompts the user for a Celsius temperature,convert the temperature to Fahrenheit and print out the
converted temperature. Note:` C *9/5 +32 = F

Solutions
Exercise 1

>>> width = 17
>>> height = 12.0
>>>
>>> width/2
8
>>> width/2.0
8.5
>>> height/3
4.0
>>> 1+ 2*5
11
>>>

Exercise 2

>>> meal = 44.50


>>> tax = 6.75/100
>>> tip = 15.0/100
>>> meal = meal + meal * tax
>>> total=meal +meal*tip
>>> print("%.2f" % total)

Exercise 3

>>> my_string= 'Erle'


>>> # For printing the length of the string we use len() method.
>>> print len(my_string)
4
>>> # For displaying the string in Capital letters we use upper() method.
>>> print my_string.upper()
ERLE
>>>

Exercise 4

>>> hours=raw_input('Enter worked hours:')


Enter worked hours: 35
>>> hours=int(hours)
>>> rate=raw_input('Enter rate of payment:')
Enter rate of payment:2.75
>>> rate=float(rate)
>>> #Notice that we change from string to integer/float before using math operators.
...
>>> pay= hours*rate
>>> print "the pay is:", pay
the pay is: 96.25
>>>

Exercise 5

>>> from datetime import datetime


>>> now = datetime.now()
>>>
>>> print '%s/%s/%s %s:%s:%s' % (now.month, now.day, now.year,now.hour, now.minute, now.second)
7/1/2014 19:4:35
>>>

Exercise 6

>>> tempC= raw_input('Enter de temperarute in Celsius:')


Enter de temperarute in Celsius:20
>>> tempC=float(tempC)
>>> #We change from string to float, so we can use operators.
...
>>> tempF=tempC*(9/5) +32
>>> print "The temperature in farenheit is:", tempF
The temperature in farenheit is: 52.0
>>>

Control flow
Just like in real life, sometimes we'd like our code to be able to make decisions.
The Python programs we've written so far have had one-track minds: they can add two numbers or print something, but
they don't have the ability to pick one of these outcomes over the other.
Control flow gives us this ability to choose among outcomes based off what else is happening in the program.

Logical operators
Comparartors
Let's start with the simplest aspect of control flow: comparators. They are use to compare expressions.
Comparator

Meaning

==

Equal to

!=

Not equal to

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

Note that == compares whether two things are equal, and = assigns a value to a variable.
For example:

>>> 17 < 4
False
>>> 3 >= 1
True
>>> 40*2 == 40 +40
True
>>> 1**2 <= -1
False
>>>

Boolean Operators
and operator
and checks if both the statements are True.

True and True is True


True and False is False
False and True is False
False and False is False

Practice 1
Let's practice with and . Assign each variable to the appropriate boolean value.
Set bool_one equal to the result of False and False .
Set bool_two equal to the result of -(-(-(-2))) == -2 and 4 >= 16**0.5 .
Set bool_three equal to the result of 19 % 4 != 300 / 10 / 10 and False .
Set bool_four equal to the result of -(1**2) < 2**0 and 10 % 10 <= 20 - 10 * 2 .
Set bool_five equal to the result of True and True .
You can check the results in your interpeter:

bool_one = False
bool_two = False

bool_three = False
bool_four = True
bool_five = True

or operator
or checks if at least one of the statements is True.

True or True is True


True or False is True
False or True is True
False or False is False

Practice 2
Now do the same, but with the or operator:
Set bool_one equal to the result of 2**3 == 108 % 100 or 'Cleese' == 'King Arthur' .
Set bool_two equal to the result of True or False .
Set bool_three equal to the result of 100**0.5 >= 50 or False .
Set bool_four equal to the result of True or True .
Set bool_five equal to the result of 1**100 == 100**1 or 3 * 2 * 1 != 3 + 2 + 1 .
The result should be:

bool_one = True
bool_two = True
bool_three = False
bool_four = True
bool_five = False

not operator
not gives the opposite of the statemen.

Not True is False


Not False is True

Practice 6
Let's get some practice with not .
Set bool_one equal to the result of not True .
Set bool_two equal to the result of not 3**4 < 4**3 .
Set bool_three equal to the result of not 10 % 3 <= 10 % 2
Set bool_four equal to the result of not 3**2 + 4**2 != 5**2 .
Set bool_five equal to the result of not not False .
The solution of this practice is:

bool_one = False

bool_two = True
bool_three = True
bool_four = True
bool_five = False

The order of operators


Boolean operators aren't just evaluated from left to right. Just like with arithmetic operators, there's an order of operations
for boolean operators:
not is evaluated first; and is evaluated next; or is evaluated last.

Parentheses () ensure your expressions are evaluated in the order you want. Anything in parentheses is evaluated as its
own unit.
Practice 4
Assign True or False as appropriate for bool_one through bool_five.
Set bool_one equal to the result of False or not True and True .
Set bool_two equal to the result of False and not True or True .
Set bool_three equal to the result of True and not (False or False)
Set bool_four equal to the result of not not True or False and not True .
Set bool_five equal to the result of False or not (True and True) .
The solution is the following one:

bool_one = False
bool_two = True
bool_three = True
bool_four = True
bool_five = False

Conditional statements
if is a conditional statement that executes some specified code after checking if its expression is True.

Practice 1
Run this code and see what happend:

>>> x=10
>>> if x>2 :
... print "It is a Large number."
...
It is a Large number.

Note, the identation is very important here.

The else statement complements the if statement. An if/else pair says: "If this expression is true, run this indented code
block; otherwise, run this code after the else statement."
Unlike if , `else doesn't depend on an expression.
Practice 2
Let's see an example:

>>> if 8 > 9:
... print "I don't printed!"
... else:
... print "I get printed!"
...
I get printed!
>>>

elif is short for "else if." It means exactly what it sounds like: "otherwise, if the following expression is true, do this!"

Practice 3
Here you find the example:

>>> if 8 > 9:
... print "I don't get printed!"
... elif 8 < 9:
... print "I get printed!"
... else:
... print "I also don't get printed!"
...
I get printed!

Errors and Exceptions


Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.
Errors detected during execution are called exceptions and are not unconditionally fatal.It is possible to write programs that
handle selected exceptions.
We use try and except to avoid this errors. Let's see an example:

>>> num=4
>>> if num<10:
... try:
... num=num**3
... print num
... except:
... print "Error"
...
64
>>>
>>> num = "Hola"
>>>
>>> if num<10:
... try:
... num=num**3
... print num
... except:
... print "Error"
...
Error

If try is executed successfully the except is ignored. If try fails, the except is executed.
Practice 1
Write a program that ask for an integer number. while True use try to ask this number and then break if the value is not
correct, print an error message.
The code syntaxis is the following. Copy this in pra.py file:

while True:
try:
num=int(raw_input("Enter an integer number:")
break
except ValueError:
print"That is not a valid number!Try again..."

The execution result on this:

root@erlerobot:~/Python_files# python pra.py


Enter an integer number:9.8
That is not a valid number!Try again...
Enter an integer number:9
root@erlerobot:~/Python_files#

Exercises: Control flow


Exercise 1
Write a program to prompt the user for hours and rate per hour to compute gross pay.Take into account that the factory
gives the employee 1.5 times the hourly rate for hours worked above 40 hours.

Enter Hours: 45
Rate: 10
Pay: 475.0

Exercise 2
Pig Latin is a language game, where you move the first letter of the word to the end and add "ay." So "Python" becomes
"ythonpay." To write a Pig Latin translator in Python, here are the steps we'll need to take:
Ask the user to input a word in English.
Make sure the user entered a valid word.
Convert the word from English to Pig Latin.
Display the translation result.
First define a variable called pyg equal to "ay" and ask the user to enter a word. Save the results of raw_input() in a
variable called original . Then add an if statement that checks that len(original) is greater than zero AND that the
word the user enters contains only alphabetical characters(Note: isalpha() returns False since the string contains nonletter characters.). If the string actually has some characters in it, print the user's word.Otherwise (i.e. an else: statement),
please print "empty".After that checks create a new variable called word that holds the .lower() -case conversion of
original . Create a new variable called first that holds word[0], the first letter of word. Create a new variable
called new_word and set it equal to the concatenation of word , first , and pyg .Set new_word equal to the slice from
the 1st index all the way to the end of new_word . Use [1:len(new_word)]` to do this.

Exercise 3
Write a program to prompt for a score between 0.0 and 1.0. If the core is out of range print an error. If the score is between
0.0 and 1.0, print a grade using the following table:

Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F

Exercise 4
Write a programm that ask for a number to the user and clasifies it:

number <2 SMALL


number <10 MEDIUM
number rest LARGE

Solutions
Exercise 1

Enter worked hours:45


>>> hours=float(hours)
>>> rate=10
>>> if hours < 40:
... pay=hours*rate
... print "the pay is:", pay
... else:
... pay = 40 * rate + (hours-40)*1.5*rate
... print "the pay is:", pay
...
the pay is: 475.0
>>>
`

Exercise 2

pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original
word= original.lower()
first=word[0]
new_word= word +first +pyg
new_word=new_word[1:len(new_word)]
else:
print 'empty'

Exercise 3

>>> score=raw_input("Enter a score:")


Enter a score:0.79
>>> score=float(score)
>>> if score >=0.9:
... print "A"
... elif score >= 0.8:
... print "B"
... elif score >= 0.7:
... print "C"
... elif score >=0.6:
... print "D"
... elif score <= 0.6 :
... print "F"
... else:
... print "error"
...
C
>>>

Exercise 4

>>> num =raw_input ("Enter a number:")


Enter a number:6
>>> if num < 2:
... print "SMALL"
... elif num < 10:
... print "MEDIUM"
... else:
... print "LARGE"
...
MEDIUM
>>>

Functions
You might have considered the situation where you would like to reuse a piece of code, just with a few different values.
Instead of rewriting the whole code, it's much cleaner to define a function, which can then be used repeatedly. In this
chapter we will learns more things about functions and their use.

Function basics
In the context of programming, a function is a named sequence of statements that performs a computation. When you
define a function, you specify the name and the sequence of statements. Later, you can call the function by name.
def is a keyword that indicates that this is a function definition. For example:

>>> def tax(bill):


... """Adds 8% tax to a restaurant bill."""
... bill *= 1.08
... print "With tax: %f" % bill
... return bill
...
>>> meal_cost = 100
>>> meal_with_tax = tax(meal_cost)
With tax: 108.000000
>>>

Note: *= means add that percentage. tip *=1.6 is the same as adding tip value a 60% : tip +tip +0.6 .
The function components are:
The header, which includes the def keyword, the name of the function, and any parameters the function requires.
An optional comment that explains what the function does.
The body, which describes the procedures the function carries out. The body is indented, just like for conditional
statements.
If you look the example above, after def we find the function argument, between brackets.The empty parentheses after
the name indicate that this function doesnt take any arguments. Then after the colon and idented to the rigth we find the
sentences to run when we call the function.
After defining a function, it must be called to be implemented.
Practice 1
Define a function that returns the square of a number, and call it with the argument 10.

>>> def square(n):


... """Returns the square of a number."""
... squared = n**2
... print "%d squared is %d." % (n, squared)
... return squared
...
... # Call the square function on line 9! Make sure to
... # include the number 10 between the parentheses.
...
>>> square(10)
10 squared is 100.
100

Practice 2
Make the same and kind of function as in Practice 1, but using two arguments:base, exponent.

>>> def power(base, exponent): # Add your parameters here!


... result = base**exponent
... print "%d to the power of %d is %d." % (base, exponent, result)
...

>>> power(37,4) # Add your arguments here!


37 to the power of 4 is 1874161.

A function can call another function, for example:


Practice 3
Define one_good_turn (which adds 1 to the number it takes in as an argument) and deserves_another (which adds 2).
Change the body of deserves_another so that it always adds 2 to the output of one_good_turn .

>>> def one_good_turn(n):


... return n + 1
...
>>> def deserves_another(n):
... return one_good_turn(n) + 2
...
>>> deserves_another(7)
10
>>>

Importing functions
A module is a file that contains definitionsincluding variables and functionsthat you can use once it is imported.There is
a Python module named math that includes a number of useful variables and functions, and sqrt() is one of those
functions. In order to access math, all you need is the import keyword. When you simply import a module this way, it's
called a generic import.
Note: We have done this with random and with datetime .
To import a function (in this case sqrt() function) from this module follow the steps:
Type import math .
Insert math. before sqrt() so that it has the form math.sqrt() . This tells Python not only to import math , but to get
the sqrt() function from within math .
Here you have an example:

>>> import math


>>> print math.sqrt(25)
5.0

It's possible to import only certain variables or functions from a given module. Pulling in just a single function from a module
is called a function import, and it's done with the from keyword:

from module import function

For example:

>>> from math import sqrt

What if we still want all of the variables and functions in a module but don't want to have to constantly type math. ?
Universal import can handle this for you.

from module import *

Note:The * means all.

>>> from math import *

Universal imports may look great on the surface, but they're not a good idea for one very important reason: they fill your
program with a ton of variable and function names without the safety of those names still being associated with the
module(s) they came from. If you have a function of your very own named sqrt and you import math, your function is safe:
there is your sqrt and there is math.sqrt. If you do from math import *, however, you have a problem: namely, two different
functions with the exact same name.
Even if your own definitions don't directly conflict with names from imported modules, if you import * from several modules
at once, you won't be able to figure out which variable or function came from where.
This code will show you everything available in the math module.

>>> import math # Imports the math module


>>> everything = dir(math) # Sets everything to a list of things from math
>>> print everything # Prints 'em all!
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil',
>>>

For these reasons, it's best to stick with either import module and type module.name or just import specific variables and
functions from various modules as needed.

Built-in functions
You already know about some of the built-in functions:
Strings functions, such as .upper() , .lower() , str() , and `len().
type() and type conversion functions: int() , float() , str() .

Now we are going to learn three new functions: min , max , abs .
max and min
The max and min functions give us the largest and smallest values in a list, respectively:
Example with max :

>>> def biggest_number(*args):


... print max(args)
... return max(args)
...
>>> biggest_number(-10, -5, 5, 10)
10
10
>>>

Note: The result of print and return is the same in this case.Usually print displays something in the screen, while return
asignd the function the stablished value.
Example with min and strings:

>>> min("Erle")
'E'

abs
The abs function returns the absolute value of a number, let's see an example:

>>> def distance_from_zero(arg):


... print abs(arg)
... return abs(arg)
...
>>> distance_from_zero(-10)
10
10

Exercises: Functions
Exercise 1
Write a shutting down program:
First, def a function, shut_down , that takes one argument s . Then, if the shut_down function receives an s equal to "yes",
it should return "Shutting down" Alternatively, elif s is equal to "no", then the function should return "Shutdown aborted".
Finally, if shut_dow n gets anything other than those inputs, the function should return "Sorry".
Exercise 2
Import the math module in whatever way you prefer. Call its sqrt function on the number 13689 and print that value to the
console.
Exercise 3
First, def a function called distance_from_zero , with one argument (choose any argument name you like). If the type of the
argument is either int or float , the function should return the absolute value of the function input. Otherwise, the
function should return "Nope". Check if it works calling the function with -5.6 and "what?".
Exercise 4
Rewrite your pay computation program (previus chapter) with time-and-a-half for overtime and create a function called
computepay which takes two parameters (hours and rate).

Enter Hours: 45
Enter Rate: 10
Pay: 475.0

Exercise 5
Let's use functions to calculate your trip's costs:
Define a function called hotel_cost with one argument nights as input. The hotel costs $140 per night. So, the
function hotel_cost should return 140 * nights.
Define a function called plane_ride_cost that takes a string, city , as input. The function should return a different
price depending on the location, similar to the code example above. Below are the valid destinations and their
corresponding round-trip prices.
"Charlotte": 183
"Tampa": 220
"Pittsburgh": 222
"Los Angeles": 475

-Below your existing code, define a function called rental_car_cost with an argument called days. Calculate the cost
of renting the car: Every day you rent the car costs $40.(cost=40*days) if you rent the car for 7 or more days, you get
$50 off your total(cost-=50). Alternatively (elif), if you rent the car for 3 or more days, you get $20 off your total. You
cannot get both of the above discounts. Return that cost. -Then, define a function called trip_cost that takes two
arguments, city and days . Like the example above, have your function return the sum of calling the
rental_car_cost(days) , hotel_cost(days) , and plane_ride_cost(city) functions.

Modify your trip_cost function definion. Add a third argument, spending_money . Modify what the trip_cost function
does. Add the variable `spending_money to the sum that it returns.
Exercise 6
Follow the stpes:

First, def a function called cube that takes an argument called number .
Make that function return the cube of that number (i.e. that number multiplied by itself and multiplied by itself once
again).
Define a second function called by_three that takes an argument called number. if that number is divisible by
3, by_three should call cube(number) and return its result. Otherwise, by_three should return False. -Check if it works.

Solutions
Exercise 1

>>> def shut_down(s):


... if s=="yes":
... return "Shutting down"
... elif s=="no":
... return "Shutdown aborted"
... else:
... return "Sorry"
...
>>> s="no"
>>> shut_down(s)
'Shutdown aborted'
>>>

Exercise 2

>>> from math import sqrt


>>> print sqrt(13689)
117.0

Exercise 3

>>> def distance_from_zero(num):


... if type(num)== int or type(num)== float:
... return abs(num)
... else:
... return "Nope"
...
>>> distance_from_zero(-5.6)
5.6
>>> distance_from_zero("what?")
'Nope'

Exercise 4

>>> def computepay(hours,rate):


... if hours < 40:
... pay=hours*rate
... print "the pay is:", pay
... else:
... pay = 40 * rate + (hours-40)*1.5*rate
... print "the pay is:", pay
...
>>>
>>> hours=raw_input("Enter worked hours:")
Enter worked hours:45
>>> hours=float(hours)
>>> rate=10
>>> computepay(hours,rate)
the pay is: 475.0
>>>

Exercise 5

Store this in a file. You can use vi text editor and open a .py file, save and execute it:

root@erlerobot:~# vi trpcal.txt
root@erlerobot:~# cp trpcal.txt trpcal.py
root@erlerobot:~# python trpcal.py

This is the code:

nights=raw_input("Enter nights:")
city=raw_input("Enter city:")
days=raw_input("Enter days of car rental:")
spending_money=raw_input("Enter money:")
def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if city=="Charlotte":
return 183
elif city=="Tampa":
return 220
elif city=="Pittsburgh":
return 222
elif city=="Los Angeles":
return 475

def rental_car_cost(days):
cost=days*40
if days >= 7:
cost -= 50
elif days>=3:
cost-=20
return cost
def trip_cost(city,days,spending_money):
print rental_car_cost(days)+hotel_cost(days)+plane_ride_cost(city)+spending_money
trip_cost(city,days,spending_money)

Exercise 6

>>> def cube(number):


... return number*number*number
...
>>> def by_three(number):
... if number %3 ==0:
... return cube(number)
... else:
... return False
...
>>> by_three(9)
729
>>>

Lists and Dictionaries


In this chapter you will find information and examples of lists/dictionaries.They are powerful tool when organizing, storing
and manipulating all kind of information.

Lists basics
Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single
variable name. (Datatypes you've already learned about include strings, numbers, and booleans.)
You can assign items to a list with an expression of the form(with the items in between brackets):

list_name = [item_1, item_2]

A list can also be empty: empty_list = [].


Lists are very similar to strings, but there are a few key differences.
Accessing a list
You can access an individual item on the list by its index. An index is like an address that identifies the item's place in the
list. The index appears directly after the list name, in between brackets, like this: list_name[index].
List indices begin with 0, not 1! You access the first item in a list like this: list_name[0] . The second item in a list is at
index 1: list_name[1] .
Practice 1
Make a list containg the zoo animals and print the 2nd. and the last one:

>>> zoo_animals = ["pangolin", "cassowary", "sloth","lion" ];


>>> print zoo_animals[1],zoo_animals[3]
cassowary lion
>>>

A list index behaves like any other variable name. It can be used to access as well as assign values.
Practice 2
Write an assignment statement that will replace the item that currently holds the value "lion" in the zoo_animals list with
another animal the tiger.

>>> zoo_animals[3]="tiger"
>>> print zoo_animals[3]
tiger
>>>
>>> print zoo_animals
['pangolin', 'cassowary', 'sloth', 'tiger']
>>>

Note that with the command print list_name you get printed the compelte list.

Adding elements to a list


A list doesn't have to have a fixed length. You can add items to the end of a list any time you like.
With the command list_name.append('name') you add a new item at the end of the list. With the command print
len(list_name) you can know how many items a list has.

Practice 3

Add the 5th element to the list: "parrot". Display the number of list items and print the new list.

>>> zoo_animals.append("parrot")
>>> print len(zoo_animals)
5
>>> print zoo_animals
['pangolin', 'cassowary', 'sloth', 'tiger', 'parrot']
>>>

Extracting parts of a list


Sometimes, you only want to access a portion of a list.You should use this format command:

part_list=list_name[1:3]

Practice 4
Given a list:

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

Create a list called first containing only the two first items from suitcase.
Create a list called middle containing only the two middle items from suitcase.
Create a list called last made up only of the last two items from suitcase.

>>> first =suitcase[0:2]


>>> print first
['sunglasses', 'hat']
>>>
>>> middle =suitcase[2:4]
>>> print middle
['passport', 'laptop']
>>>
>>> last =suitcase[4:6]
>>> print last
['suit', 'shoes']
>>>

Finding the index of a list element


You can use Use the .index(item) function to find the index of an element of the list.
Practice 5
Given

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]

Use the .index(item) function to find the index of "duck". Then .insert(index, item) the string "cobra" at that index.Print
the result.

>>> animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]


>>> print animals.index("duck")
2
>>> animals.insert(2,"cobra")
>>> print animals

['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox']


>>>

Removing elements from a list


Sometimes you need to remove something from a list. n.pop(index) will remove the item at index from the list and return it
to you:

>>> n = [1, 3, 5]
>>> n.pop(1)
3
>>> print n
[1, 5]

n.remove(item) will remove the actual item if it finds it

>>> n = [1, 3, 5]
>>> n.remove(3)
>>> print n
[1, 5]
>>>

del(n[1]) is like `.pop in that it will remove the item at the given index, but it won't return it:

>>> n=[1,3,5]
>>> del(n[0])
>>> print n
[3, 5]

Practice 6
From the list below remove 'dagger', choose the command you like of the above ones:

backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']

>>> backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']


>>>
>>> backpack.remove('dagger')
>>> print backpack
['xylophone', 'tent', 'bread loaf']
>>>

Strings as a list
You can slice a string exactly like a list! In fact, you can think of strings as lists of characters: each character is a sequential
item in the list, starting from index 0.If your list slice includes the very first or last item in a list (or a string), the index for that
item doesn't have to be included.
Practice 1
See an example of how managing strings as lists:

>>> animals = "catdogfrog"


>>>
>>> cat = animals[:3]
>>> print cat
cat
>>> # The first three characters of animals
...
>>> dog = animals[3:6]
>>> print dog
dog
>>> # The fourth through sixth characters
...
>>> frog = animals[6:]
>>> print frog
frog
>>> # From the seventh character to the end
...
>>>

For loop with lists


If you want to do something with every item in the list, you can use a for loop. The command line is:

for variable in list_name:

A variable name follows the for keyword; it will be assigned the value of each list item in turn.
Then in list_name designates list_nam e as the list the loop will work on. The line ends with a colon (:) and the indented
code that follows it will be executed once per item in the list.
Practice 1
What does this code?

>>> my_list = [1,9,3,8,5,7]


>>>
>>> for number in my_list:
... # Your code here
... print number*2
...
...

The for loop will automatically execute your code as many times as there are items in my_list .The result is:

...
2
18
6
16
10
14
>>>

If your list is a jumbled mess, you may need to sort() it.Note that .sort() modifies the list rather than returning a new list.
Practice 2
Write a for loop that iterates over start_list = [5, 3, 1, 2, 4] and .append()s each number squared (x ** 2) to
square_list (initialized to empty list). Then sort square_list.

>>> start_list = [5, 3, 1, 2, 4]


>>> square_list = []
>>>
>>>
>>> for number in start_list:
... n=star_list[number-1]
... square_list.append(n**2)
...
>>> #Now we reordenate the list
...
>>> square_list.sort()
>>> print square_list
[1, 4, 9, 16, 25]
>>>
over `start_list=[5, 3, 1, 2, 4] and .append()s each number squared (x ** 2) to `square_list` (which is initialized to empty list).
Then sort square_list.

Practice 3
Use a for loop to print out all of the elements in the list names.

names = ["Adam","Alex","Mariah","Martine","Columbus"]

>>> names = ["Adam","Alex","Mariah","Martine","Columbus"]


>>>
>>> for name in names:
... print name
...
Adam
Alex
Mariah
Martine
Columbus
>>>

You can also use the for loop with strings:


Practice 4
We are going to print only the "i" letters for a string. Run this code and analyze what happend:

word = "Programming is fun!"


for letter in word:
# Only print out the letter i
if letter == "i":
print letter

Functions and lists


Functions can also take lists as inputs and perform various operations on those lists.In later chapter we will deepen in this
topic.
For now,let's see an example to understand how it works:
Practice 1
Write a function that counts how many times the string "fizz" appears in a list.
We create a count.py file with this content:

def fizz_count(x):
count=0
for item in x:
if item == "fizz":
count=count +1
print count
fizz_count(["fizz","buzz"])

We execute it, the anwswer should be one:

root@erlerobot:~/Python_files# python count.py


1
root@erlerobot:~/Python_files#

Passing a range into a function


The Python range() function is just a shortcut for generating a list, so you can use ranges in all the same places you can
use lists.

range(6) # => [0,1,2,3,4,5]


range(1,6) # => [1,2,3,4,5]
range(1,6,3) # => [1,4]

The range function has three different versions:

range(stop)
range(start, stop)
range(start, stop, step)

In all cases, the range() function returns a list of numbers from start up to (but not including) stop. Each item Each item
increases by step.If omitted, start defaults to zero and step defaults to one.
Now you can iterate through indexes:

for i in range(len(list)):
print list[i]

This method is much safer. Since we aren't modifying the list.

Practice 2
Create a function called total that adds up all the elements of an arbitrary list and returns that count, using the existing code
as a hint. Use a for loop so it can be used for any size list.

>>> def total(numbers):


... result=0
... for number in range(len(numbers)):
... result=result+numbers[number]
...
... return result
...
>>> #Now we check if it works
...
>>> n = [3, 5, 7]
>>> total(n)
15

Practice 3
Create a function that concatenates strings.

>>> def join_strings(words):


... result=""
... for i in words:
... result=result + i
... return result
...
>>> #Now we checkt if it works
...
>>> n = ["Michael", "Lieberman"]
>>> print join_strings(n)
MichaelLieberman
>>>

Note, if you analize the codes of practice 2 and 3: you can see how when working with numbers( for elemt in list ) elemt
takes the value:0,1,2... while when working with strings elemt takes the string in index 0,1,2.. value.

Dictionaries basics
A dictionary is similar to a list, but you access values by looking up a key instead of an index. A key can be any string or
number. Dictionaries are enclosed in curly braces, like so:

d = {'key1' : 1, 'key2' : 2, 'key3' : 3}

This is a dictionary called d with three key-value pairs. The key 'key1' points to the value 1, 'key2' to 2, and so on.
Dictionaries are great for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail
address with a username)...
Accessing a dictionary
Note that accessing dictionary values by key is just like accessing list values by index.
Practice 1
Given this dictinary:

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

Print the value stored under the 'Sloth' key:

>>> residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}


>>> print residents['Sloth']
105

Adding elements to a dictionary


Like Lists, Dictionaries are "mutable". This means they can be changed after they are created. One advantage of this is that
we can add new key/value pairs to the dictionary after it is created like so:

dict_name[new_key] = new_value

An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list.
The length len() of a dictionary is the number of key-value pairs it has. Each pair counts only once, even if the value is a
list. (That's right: you can put lists inside dictionaries!)
Practice 2
Add three elements to menu{} . Print the number of elements in menu and the menu itselfs.

>>> menu = {} # Empty dictionary


>>> menu['Sunday']=16.78
>>> print menu['Sunday']
16.78
>>> menu['Monday']=6.78
>>> print menu['Monday']
6.78
>>> menu['Tuesday']= 9.98
>>> print menu['Tuesday']
9.98

>>>
>>> print "There are " + str(len(menu)) + " items on the menu."
There are 3 items on the menu.
>>> print menu
{'Sunday': 16.78, 'Tuesday': 9.98, 'Monday': 6.78}
>>>

Removing elements from a dictionary and associating values with keys.


Because dictionaries are mutable, they can be changed in many ways. Items can be removed from a dictionary with the del
command:

del dict_name[key_name]

will remove the key key_name and its associated value from the dictionary.
A new value can be associated with a key by assigning a value to the key, like so:

dict_name[key] = new_value

Practice 3
Given the dictionary:

# key - animal_name : value - location


zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}

Delete the 'Sloth' and 'Bengal Tiger' items from zoo_animals using del .
Set the value associated with 'Rockhopper Penguin' to anything other than 'Arctic Exhibit.

>>> zoo_animals = { 'Unicorn' : 'Cotton Candy House',


... 'Sloth' : 'Rainforest Exhibit',
... 'Bengal Tiger' : 'Jungle House',
... 'Atlantic Puffin' : 'Arctic Exhibit',
... 'Rockhopper Penguin' : 'Arctic Exhibit'}
>>>
>>> del zoo_animals['Sloth']
>>> del zoo_animals['Bengal Tiger']
>>> print zoo_animals
{'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper Penguin': 'Arctic Exhibit', 'Unicorn': 'Cotton Candy House'}
>>>
>>> zoo_animals['Rockhopper Penguin']='Arctic Dance'
>>> print zoo_animals
{'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper Penguin': 'Arctic Dance', 'Unicorn': 'Cotton Candy House'}
>>>

For loop with dictionaries


The use of for when accessing dictionaries is very similar to using this loop with lists.The command should be something
like this example:

for key in d:
print d[key]

Note that dictionaries are unordered, meaning that any time you loop through a dictionary, you will go through every key,
but you are not guaranteed to get them in any particular order.
Practice 1
We have the following dictionary:

webster = {
"Aardvark" : "A star of a popular children's cartoon show.",
"Baa" : "The sound a goat makes.",
"Carpet": "Goes on the floor.",
"Dab": "A small amount."
}

Use a for loop to print all the values:

>>> webster = {
... "Aardvark" : "A star of a popular children's cartoon show.",
... "Baa" : "The sound a goat makes.",
... "Carpet": "Goes on the floor.",
... "Dab": "A small amount."
... }
>>>
>>> for key in webster:
... print webster[key]
...
A star of a popular children's cartoon show.
Goes on the floor.
A small amount.
The sound a goat makes.
>>>

Iterators for dictionaries


.items()
The .items() function returns an array of tuples with each tuple consisting of a key/value pair from the dictionary. .items()
function doesn't return key/value in any specific order.The syntaxis is:

print dic_name.items()

.values() and .keys()


The .keys() function returns an array of the dictionary's keys, and the .values() function returns an array of the
dictionary's values. Again, these functions will not return the keys or values from the dictionary in any specific order. The
sintaxis is equal to the -items() one.
You can think of a tuple as an immutable (that is, unchangeable) list (though this is an oversimplification); tuples are
surrounded by () s and can contain any data type.
Practice 1
Create your own Python dictionary, my_dict, with two or three key/value pairs. Then, print the result of calling the
my_dict.items().

>>> my_dict={"string":"string of char",


... "bolean":True,
... "integer":3}
>>>
>>> print my_dict.items()
[('integer', 3), ('bolean', True), ('string', 'string of char')]
>>>

Now print the result of using .keys and .values() :

>>> print my_dict.keys()


['integer', 'bolean', 'string']
>>> print my_dict.values()
[3, True, 'string of char']
>>>

Remember the other way of iterating throug a dictionary usding the for loop.

>>>
>>> for key in my_dict:
... print key, my_dict[key]
...
integer 3
bolean True
string string of char
>>>

Exercises: List and Dictionaries


Exercise 1
Given the following dictionary:

inventory = {
'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'],
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

Try to do the followings:


Add a key to inventory called 'pocket'.
Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and 'lint' .
.sort() the items in the list stored under the 'backpack' key.

Then .remove('dagger') from the list of items stored under the 'backpack' key.
Add 50 to the number stored under the 'gold' key.
Exercise 2
Folow the steps bellow: -Create a new dictionary called prices using {} format like the example above.
Put these values in your prices dictionary:
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3

Loop through each key in prices . For each key, print out the key along with its price and stock information. Print the
answer in the following format:
apple
price: 2
stock: 0

Let's determine how much money you would make if you sold all of your food.
Create a variable called total and set it to zero.
Loop through the prices dictionaries.For each key in prices, multiply the number in prices by the number in stock.
Print that value into the console and then add it to total.
Finally, outside your loop, print total.
Exercise 3
Follow the steps:
First, make a list called groceries with the values "banana","orange", and "apple".
Define this two dictionaries:

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}

prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

Define a function compute_bill that takes one argument food as input. In the function, create a variable total with an
initial value of zero.For each item in the food list, add the price of that item to total. Finally, return the total. Ignore
whether or not the item you're billing for is in stock.Note that your function should work for any food list.
Make the following changes to your compute_bill function:
While you loop through each item of food, only add the price of the item to total if the item's stock count is greater
than zero.
If the item is in stock and after you add the price to the total, subtract one from the item's stock count.
Exercise 4
This exercise is a bit more complicate. We will review all about list and dictionaries. The aim of this exercise is to make a
gradebook for teacher's students.
Try to follow the steps:
Create three dictionaries: lloyd , alice , and tyler .
Give each dictionary the keys "name", "homework", "quizzes", and "tests".Have the "name" key be the name of the
student (that is, lloyd's name should be "Lloyd") and the other keys should be an empty list. Look in solutions, the
"solution 1". Chechk if you have done it rigth.
Now copy this code:
lloyd = {
"name": "Lloyd",
"homework": [90.0,97.0,75.0,92.0],
"quizzes": [88.0,40.0,94.0],
"tests": [75.0,90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}

Below your code, create a list called students that contains lloyd , alice , and `tyler.
for each student in your students list, print out that student's data, as follows:
print the student's name
print the student's homework
print the student's quizzes
print the student's tests
Write a function average that takes a list of numbers and returns the average.
Define a function called average that has one argument, numbers.
Inside that function, call the built-in sum() function with the numbers list as a parameter. Store the result in a
variable called total.
Use float() to convert total and store the result in total.
Divide total by the length of the numbers list. Use the built-in len() function to calculate that.
Return that result.
Write a function called get_average that takes a student dictionary (like lloyd, alice, or tyler) as input and returns his/her

weighted average.
Define a function called get_average that takes one argument called student.
Make a variable homework that stores the average() of student["homework"].
Repeat step 2 for "quizzes" and "tests".
Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30%
and tests are 60%.
Define a new function called get_letter_grade that has one argument called score. Expect score to be a number.
Inside your function, test score using a chain of if: / elif: / else: statements, like so:

If score is 90 or above: return "A"


Else if score is 80 or above: return "B"
Else if score is 70 or above: return "C"
Else if score is 60 or above: return "D"
Otherwise: return "F"

Finally, test your function. Call your get_letter_grade function with the result of get_average(lloyd) . Print the
resulting letter grade.
Define a function called get_class_average that has one argument, students. You can expect students to be a list
containing your three students.
First, make an empty list called results.
For each student item in the class list, calculate get_average(student) and then call results.append() with that
result.
Finally, return the result of calling average() with results.
Finally, print out the result of calling get_class_average with your students list. Your students should be [lloyd, alice,
tyler].
Then, print the result of get_letter_grade for the class's average.

Solutions
Exercise 1

>>> inventory = {
... 'gold' : 500,
... 'pouch' : ['flint', 'twine', 'gemstone'],
... 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
... }
>>>
>>> inventory['pocket']=['seashell', 'strange berry', 'lint']
>>>
>>> inventory['backpack'].sort()
>>>
>>> inventory['backpack'].remove('dagger')
>>>
>>> inventory['gold']=inventory['gold']+50
>>>
>>> print inventory
{'pocket': ['seashell', 'strange berry', 'lint'], 'backpack': ['bedroll', 'bread loaf', 'xylophone'], 'pouch': ['flint'
>>>

Exercise 2
Create and edit a supermarket.py file with vi text editor like this one:

1 #Create the prices dictionary:


2 prices={}

3 #Add values
4 prices["banana"]=4
5 prices["apple"]= 2
6 prices["orange"]= 1.5
7 prices["pear"]= 3
8
9 #Create the stock dictionary
10 stock={}
11 #Add values
12 stock["banana"]= 6
13 stock["apple"]= 0
14 stock["orange"] =32
15 stock["pear"]= 15
16
17 #Show all prices and stock
18
19 for food in prices:
20 print food
21 print "price: %s" % prices[food]
22 print "stock: %s" % stock[food]
23
24 total=0
25 for price in prices:
26 money= prices[price]*stock[price]
27 print money
28 total=total +money
29
30 print "The total money is", total
31

Now, call the file using python supermarket.py :

root@erlerobot:~/Python_files# python supermarket.py


orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0
48.0
45
24
0
The total money is 117.0
root@erlerobot:~/Python_files#

Exercise 3
Create a shoplist.py list with this content:

shopping_list = ["banana", "orange", "apple"]


stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

def compute_bill(food):
total=0

for x in food:
price= prices[x]
if stock[x]>0:
total=total +price
stock[x]=stock[x] -1
print total
compute_bill(shopping_list)

Now execute the file with python shoplist.py :

root@erlerobot:~/Python_files# python shoplist.py


5.5
root@erlerobot:~/Python_files#

Exercise 4
Solution 1

lloyd = {
"name": "Lloyd",
"homework": [],
"quizzes":[],
"tests":[],
}
alice = {"name": "Alice", "homework":[],"quizzes":[],"tests":[],}
tyler = {"name": "Tyler", "homework":[],"quizzes":[],"tests":[],}

Solution complete
Create note.py with this content:

lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}

students=[lloyd,alice,tyler]
for student in students:
print student["name"]
print student["homework"]
print student["quizzes"]
print student["tests"]
def average(numbers):
total=sum(numbers)
total=float(total)
media= total/ (len(numbers))
return media
def get_average(student):
homework=average(student["homework"])
quizzes=average(student["quizzes"])
tests=average(student["tests"])
final=0.1*homework +0.3*quizzes + 0.6*tests

return final
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >=80:
return "B"
elif score >=70:
return "C"
elif score >=60:
return "D"
else:
return "F"
print get_letter_grade(get_average(lloyd))

def get_class_average(students):
results=[]
for student in students:
r=get_average(student)
results.append(r)
return average(results)

students=[lloyd,alice,tyler]
print get_class_average(students)
print get_letter_grade(get_class_average(students))

Execute the file with python note.py :

root@erlerobot:~/Python_files# python note.py


Lloyd
[90.0, 97.0, 75.0, 92.0]
[88.0, 40.0, 94.0]
[75.0, 90.0]
Alice
[100.0, 92.0, 98.0, 100.0]
[82.0, 83.0, 91.0]
[89.0, 97.0]
Tyler
[0.0, 87.0, 75.0, 22.0]
[0.0, 75.0, 78.0]
[100.0, 100.0]
B
83.8666666667
B
root@erlerobot:~/Python_files#

Exercise:Battleship
Here you can find a complete exercise where you will review everithing you have learn till the moment.

Battleship
In this project you will build a simplified, one-player version of the classic board game Battleship! In this version of the
game, there will be a single ship hidden in a random location on a 5x5 grid. The player will have 10 guesses to try to sink
the ship.
To build this game we will use our knowledge of lists, conditionals and functions in Python.
We will go step by step, given solutions at the end you will find the solution(complete code stored in battleship.py ).

Ready? The computing starts here:


Create a variable board and set it equal to an empty list.
Create a 5 x 5 grid initialized to all 'O's and store it in board. Tip:

>>> board=["O"]*5
>>> print board
['O', 'O', 'O', 'O', 'O']
>>> print len(board)
5
`

Use range() to loop 5 times.


Inside the loop, .append() a list containing 5 "O"s to board, just like in the example above.
Note that these are capital letter "O" and not zeros.
Use the print command to display the contents of the board list.
Solution1:

board=[]
for x in range(0,5):
board.append(["O"]*5)
print board

We can use the fact that our board is a list of lists to help us do this. Let's set up a for loop to go through each of the
elements in the outer list (each of which is a row of our board) and print them.
First, delete your existing print statement. Then, define a function named print_board with a single argument,
board.
Inside the function, write a for loop to iterates through each row in board and print it to the screen.
Call your function with board to make sure it works.
Solution 2

def print_board(board):
for i in board:
print i
print_board(board)

Now we want to get rid of the commas, like this:


>>> letters = ['a', 'b', 'c', 'd']
>>> print " ".join(letters)
a b c d

>>>

Inside your function, inside your for loop, use " " as the separator to .join the elements of each row.
Solution 3

def print_board(board):
for row in board:
print " ".join(row)
print_board(board)

Now, let's hide our battleship in a random location on the board.Since we have a 2-dimensional list, we'll use two
variables to store the ship's location, ship_row and ship_col . Look at his example:

>>> from random import randint


>>> coin = randint(0, 1)
>>> dice = randint(1, 6)
>>> print coin
0
>>> print dice
1
>>>

In the above example, we first import the randint(low, high) function from the random module. Then, we generate
either zero or one and store it in coin. Finally, we generate a number from one to six inclusive. Let's generate a
random_row and random_col from zero to four.

Define two new functions, random_row and random_col , that each take board as input.
These functions should return a random row index and a random column index from your board, respectively. Use
randint(0, len(board) - 1).
Call each function on board.
Solution 4

def random_row(board):
from random import randint
return randint(0, len(board) - 1)
def random_col(board):
from random import randint
return randint(0, len(board) - 1)

We are going to ask the user to guess the column and the row where our ship is stored:
Create a new variable called guess_row and set it to int(raw_input("Guess Row: ")) .
Create a new variable called guess_col and set it to int(raw_input("Guess Col: ")) .
For now, while we're writing and debugging this part of the program, it will be helpful to know where that battleship is
hidden. Let's add a print statement that displays the location of the hidden ship.We will delete it later on.
We have the actual location of the ship and the player's guess so we can check to see if the player guessed right.For a
guess to be right, guess_col should be equal to ship_col and guess_row should be equal to ship_row .
Add an else under the if "correct condition".
Print out "You missed my battleship!"
Set the list element at guess_row , guess_col to "X".
As the last line in your else statement, call print_board(board) again so you can see the "X".
Solution 5

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
print ship_row
print ship_col
if guess_row==ship_row and guess_col==ship_col:
print "Congratulations!You sank my battleship!"
else:
print "You missed my battleship!"
board[guess_row][guess_col]="X"
print_board(board)

Now lets think a little bit more about the "miss" condition.
The user can enter a guess that's off the board.
He can guess a spot theyve already guessed.
He can just miss the ship. We'll add the first case:
Add a new if: statement that is nested under the else.
It should check if guess_row is not in range(5) or guess_col is not in range(5).
If that is the case, print out "Oops, that's not even in the ocean."
After your new if: statement, add an else: that contains your existing handler for an incorrect guess. Don't forget to
indent the code.
And now the second one:
Add an elif to see if the guessed location already has an 'X' in it.(board[col][row]=="X") If it has, print "You guessed
that one already."
Solution 6

if guess_row==ship_row and guess_col==ship_col:


print "Congratulations!You sank my battleship!"
else:
if guess_col not in range(5) or guess_row not in range(5):
print "Oops, that's not even in the ocean."
elif board[guess_row][guess_col]=="X":
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col]="X"
print_board(board)

Wed like our game to allow the player to make up to 4 guesses before they lose.We can use a for loop to iterate
through a range. Each iteration will be a turn.
Add a for loop that repeats the guessing and checking part of your game for 4 turns.
At the beginning of each iteration, print "Turn", turn + 1 to let the player know what turn they are on.
Indent everything that should be repeated.
Solution 7

for turn in range(4):

guess_row = int(raw_input("Guess Row:"))


guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
else:

if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):


print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print "Turn:",turn+1
print_board(board)

If someone runs out of guesses without winning right now, the game just exits. It would be nice to let them know
why.Since we only want this message to display if the user guesses wrong on their last turn, we need to think carefully
about where to put it.
Well want to put it under the else that accounts for misses.
Well want to print the message no matter what the cause of the miss.
Since our turn variable starts at 0 and goes to 3, we will want to end the game when turn equals 3.
We can use the command break to get out of a for loop, when the user guess the answer.
Add a break under the win condition to end the loop after a win.

Solution:Battleship
Create Battleship.py and copy this code:

#Battleship!
from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
for turn in range(4):

guess_row = int(raw_input("Guess Row:"))


guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
break
else:
if turn==3:
print "Game Over"
elif (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print "Turn:",turn+1
print_board(board)

Execute it with python Battleship.py :

root@erlerobot:~/Python_files# python Battleship.py


Let's play Battleship!
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
Guess Row:

Loops
Loops let you to quickly iterate in Phyton. Let's see how they work.

Loops basics
A loop is a sequence of instruction s that is continually repeated until a certain condition is reached.
For example for is a loop :

>>> n=["Welcome", " to", " Erleboard", " world"]


>>> for x in n:
... print x
...
Welcome
to
Erleboard
world
>>>

This type of flow is called a loop because after the statements, in this case "print x" ,loops back around to the top. Each
time we execute the body of the loop, we call it an iteration. For the above loop, we would say, It had four iterations which
means that the body of of the loop was executed four times.
An endless source of amusement for programmers is the observation that the directions on shampoo, Lather, rinse,
repeat, are an infinite loop because there is no iteration variable telling you how many times to execute the loop.
Break
Sometimes you dont know its time to end a loop until you get half way through the body. In that case you can write an
infinite loop on purpose and then use the break statement to jump out of the loop(remember the battleship exercise).
Practice 1
Analyze the code bellow:

>>> while True:


... print count
... count += 1
... if count >= 10:
... break
...
0
1
2
3
4
5
6
7
8
9
>>>

Note thet the while condition is always true, what leads to a infinite loop. See the effect of using break .

Continue
Another useful command is continue .Sometimes you are in an iteration of a loop and want to finish the current iteration
and immediately jump to the next iteration. In that case you can use the continue statement to skip to the next iteration
without finishing the body of the loop for the current iteration.
Practice 2

Here is an example of a loop that copies its input until the user types done, but treats lines that start with the hash
character as lines not to be printed (kind of like Python comments). Open a cont.py file and copy the code bellow:

while True:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done':
break
print line
print 'Done!'

Here is a sample run of this new program with continue added.

root@erlerobot:~/Python_files# python cont.py


> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done!

While loops
The while loop is similar to an if statement: it executes the code inside of it if some condition is true. The difference is that
the while loop will continue to execute as long as the condition is true. In other words, instead of executing if something is
true, it executes while that thing is true.
Practice 1
We are going to use while and if to see the difference:

>>> count = 0
>>>
>>> if count < 10:
... print "Hello, I am an if statement and count is", count
...
Hello, I am an if statement and count is 0
>>>

When using the following code we print the sentence 9 times(< is not the same as <=).Remember always to actualize the
count, if not you get an infinite loop.

... while count < 10:


... print "Hello, I am a while and count is", count
... count += 1
...
Hello, I am a while and count is 0
Hello, I am a while and count is 1
Hello, I am a while and count is 2
Hello, I am a while and count is 3
Hello, I am a while and count is 4
Hello, I am a while and count is 5
Hello, I am a while and count is 6
Hello, I am a while and count is 7
Hello, I am a while and count is 8
Hello, I am a while and count is 9
>>>

Practice 2
Create a while loop that prints out all the numbers from 1 to 10 squared (1, 4, 9, 16, ... , 100), each on their own line.

>>> num = 1
>>>
>>> while num<=10: # Fill in the condition
... print num**2 # Print num squared
... num += 1 # Increment num (make sure to do this!)
...
1
4
9
16
25
36
49
64
81
100
>>>

While/else

Something completely different about Python is the while/else construction. while/else is similar to if/else, but there is a
difference: the else block will execute anytime the loop condition is evaluated to False. This means that it will execute if the
loop is never entered or if the loop exits normally. If the loop exits as the result of a break, the else will not be executed.
Practice 3
Copy this code in a file called game.py and run it:

import random
print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"
count = 0
while count < 3:
num = random.randint(1, 6)
print num
if num == 5:
print "Sorry, you lose!"
break
count += 1
else:
print "You win!"

Practice 4
A common application of a while loop is to check user input to see if it is valid. For example, if you ask the user to enter y or
n and they instead enter 7, then you should re-prompt them for input.Analyze the code bellow:

>>> choice = raw_input('Enjoying the course? (y/n)')


Enjoying the course? (y/n) p
>>> while choice!="y" and choice !="n": # Fill in the condition (before the colon)
... choice = raw_input("Sorry, I didn't catch that. Enter again: ")
...
Sorry, I didn't catch that. Enter again: e
Sorry, I didn't catch that. Enter again: y
>>>

For loop
An alternative way to while loop is the for loop. the for loop is looping through a known set of items so it runs through
as many iterations as there are items in the set.
Practice 1
Execute the following code and analyze the result:

>>> friends = ['Joseph', 'Glenn', 'Sally']


>>>
>>> for friend in friends:
... print 'Happy New Year:', friend
... print 'Done!'
...
Happy New Year: Joseph
Done!
Happy New Year: Glenn
Done!
Happy New Year: Sally
Done!
>>>

Enumerate
A weakness of using this for-each style of iteration is that you don't know the index of the thing you're looking at. Generally
this isn't an issue, but at times it is useful to know how far into the list you are. Thankfully the built-in enumerate function
helps with this.
enumerate works by supplying a corresponding index to each element in the list that you pass it. Each time you go through

the loop, index will be one greater, and item will be the next item in the sequence. It's very similar to using a normal for loop
with a list, except this gives us an easy way to count how many items we've seen so far.
Practice 2
Look the result of this code:

>>> choices = ['pizza', 'pasta', 'salad', 'nachos']


>>>
>>> print 'Your choices are:'
Your choices are:
>>> for index, item in enumerate(choices):
... print index, item
...
0 pizza
1 pasta
2 salad
3 nachos
>>>

Zip
It's also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy. zip will
create pairs of elements when passed two lists, and will stop at the end of the shorter list. zip can handle three or more
lists as well.
Practice 3
Compare each pair of elements and print the larger of the two.Print the biggest one of each pair.

list_a = [3, 9, 17, 15, 19]


list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

>>> for a, b in zip(list_a, list_b):


...
... if a>b:
... print a
... else:
... print b
...
...
3
9
17
15
30
>>>

For/else
Just like with while , for loops may have an else associated with them.That is the for/else loop.
In this case, the else statement is executed after the for , but only if the for ends normallythat is, not with a break.
Practice 4
We have this fruit list:

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

We are going to make a program that search for "carrot" between this fruit. If it doesn't appear it shows a succes message:

>>> fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']


>>>
>>> print 'You have...'
You have...
>>> for f in fruits:
... if f == 'carrot':
... print 'A carrot is not a fruit!'
... break
... print 'A', f
... else:
... print 'A fine selection of fruits!'
...
A banana
A apple
A orange
A tomato
A pear
A grape
A fine selection of fruits!

Exercises: Loops
Exercise 1
Write a program that generates a random number (0-10) and ask you to guess it. You have three asserts.
Define a random_number with randit between 0-10.
Initialize guesses_left to 3.
Use a while loop to let the user keep guessing so long as guesses_left is greater than zero.
Ask the user for their guess, just like the second example above.
If they guess correctly, print 'You win!' and break. Decrement guesses_left by one.
Use an else: case after your while loop to print:You lose.
Exercise 2
Create a for loop that prompts the user for a hobby 3 times, then appends each one to hobbies.
Exercise 3
REmember: The , character after our print statement means that our next print statement keeps printing on the same line.
Let's filter out the letter 'A' from our string.

phrase = "A bird in the hand..."

Do the following for each character in the phrase.


If char is an 'A' or char is an 'a', print 'X', instead of char. Make sure to include the trailing comma.
Otherwise (else:), please print char, with the trailing comma.
Exercise 4
Define a function is_even that will take a number x as input.If x is even, then return True. Otherwise, return False. Note:
even means that is divisible by two.Check if it works.
Exercise 5
Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number's digits.
Exercise 6
Let's try a factorial problem. To calculate the factorial of a non-negative integer x, just multiply all the integers from 1
through x. For example: 3! is equal to 123
Exercise 7
Scrabble is a game where players get points by spelling words. Words are scored by adding together the point values of
each individual letter.Define a function scrabble_score that takes a string word as input and returns the equivalent scrabble
score for that word.

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,


"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}

Exercise 8
Define a function called count that has two arguments called sequence and item. Return the number of times the item

occurs in the list.For example: count([1,2,1,1], 1) should return 3 (because 1 appears 3 times in the list).
Exercise 9
Write a function remove_duplicates that takes in a list and removes elements of the list that are the same.For example:
remove_duplicates([1,1,2,2]) should return [1,2].

Solutions
Exercise 1
Create a random.py file:

from random import randint


# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
# Start your game!
while guesses_left>0:
guess=int(raw_input("Enter your guess:"))
if guess==random_number:
print "You win"
break
guesses_left-=1
else:
print "You lose"

And execute it.


Exercise 2

>>> hobbies = []
>>> for i in range(3):
... hob=raw_input("Enter hobby:")
... hobbies.append(hob)
...
Enter hobby:Shopping
Enter hobby:Swimming
Enter hobby:Golf
>>> print hobbies
['Shopping', 'Swimming', 'Golf']
>>>

Exercise 3

>>> phrase = "A bird in the hand..."


>>> for char in phrase:
... if char == "A" or char == "a":
... print "X",
... else:
... print char,
...
...
...
X b i r d i n t h e h X n d . . .
>>>

Exercise 4

>>> def is_even(x):


... if x%2==0 :
... return True
... else:

... return False


...
>>>
>>> is_even(7)
False
>>> is_even(8)
True
>>>

Exercise 5

>>> def digit_sum(n):


... num=str(n)
... count=0
... for i in num:
... add=int(i)
... count=count+add
...
... return count
...
>>>
>>> digit_sum(892)
19
>>>

Exercise 6

>>> def factorial(x):


... count=1
... for i in range(x):
... count=count*(i+1)
... return count
...
>>>
>>> factorial (12)
479001600
>>>

Exercise 7

>>> score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,


... "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
... "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
... "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
... "x": 8, "z": 10}
>>>
... def scrabble_score(word):
... word=word.lower()
... total=0
... for let in word:
... total=score[let]+ total
... return total
...
>>> scrabble_score("Hello")
8
>>>
>>>

Exercise 8

>>> def count(sequence,item):


... total=0
... for x in sequence:
... if x==item:
... total+=1
... return total
...
>>>
>>> count([1,2,1,1,1,3],1)

4
>>>

Exercise 9

>>> def remove_duplicates(lst):


... result = []
... for item in lst:
... if item not in result:
... result.append(item)
... return result
...
>>> remove_duplicates([1,1,3,4,5,6,6,7,7,8,3])
[1, 3, 4, 5, 6, 7, 8]
>>>

Exercise: Exam statistics


Creating a program to compute statistics means that you won't have to whip out your calculator and manually crunch
numbers. All you'll have to do is supply a new set of numbers and our program does all of the hard work.
This mini-project will give you some practice with functions, lists, and translating mathematical formulae into programming
statements.

Exam statistics
If you have done the Battleship exercise, this one will follow the same structure. We will go step by step, giving solutions in
case you get stucked. At the end you can look to the solution file Exam.py .

Ready? The computing starts here:


This are the grades of some students:
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

We are going to make a function to print them.


Define a function called print_grades() with one argument, a list called grades.
nside the function, iterate through grades and print each item on its own line.
After your function, call print_grades() with the grades list as the parameter.
Solution 1

>>> grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
>>>
>>> def print_grades(grades):
... for grade in grades:
... print grade
...
...
>>> print_grades(grades)
100
100
90
40
80
100
85
70
90
65
90
85
50.5
>>>

The next step in the creation of our grade statistics program involves computing the mean (average) of the grades.
Define a function grades_sum() that does the following.
Takes in a list of scores, scores
Computes the sum of the scores
Returns the computed sum
Call the newly created grades_sum() function with the list of grades and print the result.
Solution 2

>>> grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
>>>
>>>
>>>
>>> def grades_sum (scores):
... total = sum (scores)
... return total
...
>>>
>>> print grades_sum(grades)
1045.5
>>>
>>>

Note:You can also use a for loop.


Define a function grades_average() , below the grades_sum() function that does the following:
Has one argument, grades, a list
Calls grades_sum with grades
Computes the average of the grades by dividing that sum by float(len(grades)).
Returns the average.
Call the newly created grades_average() function with the list of grades and print the result.
Solution 3

>>> def grades_average(grades):


... tot =grades_sum(grades)
... ave=tot/float(len(grades))
... return ave
...
>>> print grades_average(grades)
80.4230769231

We're going to use the average for computing the variance. The variance allows us to see how widespread the grades
were from the average.
Define a new function called grades_variance() that accepts one argument, scores, a list.
First, create a variable average and store the result of calling grades_average(scores) .
Next, create another variable variance and set it to zero. We will use this as a rolling sum. for each score in
scores: Compute its squared difference: (average - score) ** 2 and add that to variance.
Divide the total variance by the number of scores.
Then, return that result.
Finally, after your function code, print grades_variance(grades) .
Solution 4

>>> def grades_variance(scores):


... average=grades_average(scores)
... variance=0
... for score in scores:
... add=(average-score)**2
... variance += add
... var_tot=variance/len(scores)
... return var_tot
...
>>> print grades_variance(grades)
334.071005917

The standard deviation is the square root of the variance. You can calculate the square root by raising the number to
the one-half power.
Define a function grades_std_deviation(variance) . return the result of variance ** 0.5
After the function, create a new variable called variance and store the result of calling grades_variance(grades) .
Finally print the result of calling grades_std_deviation(variance) .
Solution 5

>>> def grades_std_deviation(variance):


... return variance**0.5
...
>>> variance=grades_variance(grades)
334.071005917
>>> print grades_std_deviation(variance)
18.2776094147

Solution:Exam statistics
Create a file called Exam.py and add the code bellow:

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print grade
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / float(len(grades))
return average
def grades_variance(scores):
average=grades_average(scores)
variance=0
for score in scores:
add=(average-score)**2
variance += add
var_tot=variance/len(scores)
return var_tot
def grades_std_deviation(variance):
return variance**0.5
variance=grades_variance(grades)
print print_grades(grades)
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades)
print grades_std_deviation(variance)

The execution of the Exam.py file should be :

root@erlerobot:~/Python_files# python Exam.py


100
100
90
40
80
100
85
70
90
65
90
85
50.5
None
1045.5
80.4230769231
334.071005917
18.2776094147
root@erlerobot:~/Python_files#

Advanced topics in Phyton


In this chapter, we will cover some of the more complex aspects in Python, including iterating over data structures, list
comprehensions, lists slicing, and lambda expressions.

List Comprehensions
Let's say you wanted to build a list of the numbers from 0 to 50 (inclusive). We could do this pretty easily:

my_list = range(51)

But what if we wanted to generate a list according to some logicfor example, a list of all the even numbers from 0 to 50?
Python's answer to this is the list comprehension. List comprehensions are a powerful way to generate lists using the
for/in and if keywords we've learned.

For example the list of even numbers, is simply to obtain using:

>>> evens_to_50 = [i for i in range(51) if i % 2 == 0]


>>> print evens_to_50
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
>>>

Practice 1
Use a list comprehension to build a list called even_squares . Your even_squares list should include the squares of the even
numbers between 1 to 11. Your list should start [4, 16, 36...] and go from there. Remember: When using range() you
should stop in last_number +1.

>>> even_squares = [i**2 for i in range(1,12) if i % 2 == 0 ]


>>>
>>> print even_squares
[4, 16, 36, 64, 100]
>>>

List Slicing
Sometimes we only want part of a Python list. Maybe we only want the first few elements; maybe we only want the last few.
Maybe we want every other element!
List slicing allows us to access elements of a list in a concise manner. The syntax looks like this:

[start:end:stride]

Where start describes where the slice starts (inclusive), end is where it ends (exclusive), and stride describes the
space between items in the sliced list. For example, a stride of 2 would select every other item from the original list to place
in the sliced list.(Refer to the index).
For example:

>>> l = [i ** 2 for i in range(1, 11)]


>>> # Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
...
>>> print l[2:9:2]
[9, 25, 49, 81]
>>>

If you don't pass a particular index to the list slice, Python will pick a default.
The default starting index is 0.
The default ending index is the end of the list.
The default stride is 1.
For example:

>>> to_five = ['A', 'B', 'C', 'D', 'E']


>>>
>>> print to_five[3:]
['D', 'E']
>>> print to_five[:2]
['A', 'B']
>>> print to_five[::2]
['A', 'C', 'E']

Practice 1
Given:

my_list = range(1, 11) # List of numbers 1 - 10

Use list slicing to print out every odd element of my_list from start to finish. Omit the start and end index. You only need to
specify a stride.

>>> l = [i ** 2 for i in range(1, 11)]


>>> # Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
...
>>> print l[2:9:2]
[9, 25, 49, 81]
>>>

Reversing a List
We have seen that a positive stride progresses through the list from left to right.A negative stride progresses through the list
from right to left should be like this:

>>> letters = ['A', 'B', 'C', 'D', 'E']


>>> print letters[::-1]
['E', 'D', 'C', 'B', 'A']
>>>

A positive stride length traverses the list from left to right, and a negative one traverses the list from right to left.
Further, a stride length of 1 traverses the list "by ones," a stride length of 2 traverses the list "by twos," and so on.
Practice 2
Create a variable called backwards and set it equal to the reversed version of my_list = range(1, 11) .

>>> my_list = range(1, 11)


>>>
>>> backwards= my_list[::-1]
>>> print backwards
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>

Lambdas
Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a
construct called "lambda".
This is one of the more powerful aspects of Python, that it allows for a style of programming called functional programming,
which means that you're allowed to pass functions around just as if they were variables or values. Sometimes we take this
for granted, but not all languages allow this.
Let's see a pair of examples:
Typing

lambda x: x % 3 == 0

Is the same as

def by_three(x):
return x % 3 == 0

Only we don't need to actually give the function a name; it does its work and returns a value without one. That's why the
function the lambda creates is an anonymous function.
Another expample of the use of lambda function:

>>> my_list = range(16)


>>> print filter(lambda x: x % 3 == 0, my_list)
[0, 3, 6, 9, 12, 15]

When we pass the lambda to filter , filter uses the lambda to determine what to filter, and the second argument (my_list,
which is just the numbers 0 15) is the list it does the filtering on.
Take into account that if you plan on creating a function you'll use over and over, you're better off using def and giving that
function a name.
Practice 1
We have this piece of code:

languages = ["HTML", "JavaScript", "Python", "Ruby"]


print filter(_______, _______)

Fill in the first part of the filter function with a lambda. The lambda should ensure that only "Python" is returned by the
filter.
Fill in the second part of the filter function with languages, the list to filter.
Remember, filter() takes two arguments: the first is the function that tells it what to filter, and the second is the object to
perform the filtering on.

>>> languages = ["HTML", "JavaScript", "Python", "Ruby"]


>>> print filter(lambda word: word=="Python", languages)
['Python']
>>>

Exercises:Advances topics in Python


Exercise 1
Use a list comprehension to create a list, `cubes_by_four. The comprehension should consist of the cubes of the numbers
1 through 10 only if the cube is evenly divisible by four. Finally, print that list to the console. Note that in this case, the cubed
number should be evenly divisible by 4, not the original number.
Exercise 2
Create a variable, backwards_by_tens , and set it equal to the result of going backwards through to_one_hundred by tens.
Go ahead and print backwards_by_tens to the console.
Exercise 3
Create a list, to_21 , that's just the numbers from 1 to 21, inclusive. Create a second list, odds , that contains only the odd
numbers in the to_21 list (1, 3, 5, and so on). Use list slicing for this one instead of a list comprehension. Finally, create a
third list, middle_third , that's equal to the middle third of `to_21, from 8 to 14, inclusive.
Exercise 4
Create a list, squares, that consists of the squares of the numbers 1 to 10. A list comprehension could be useful here. Use
filter() and a lambda expression to print out only the squares that are between 30 and 70 (inclusive).

Exercise 5
The string

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"`

is garbled in two ways:


First, our message is backwards;
Second, the letter we want is every other letter.
Use lambda and filter to extract the message and save it to a variable called message. Use list slicing to extract the
message and save it to a variable called message.

Solutions
Exercise 1

>>> cubes_by_four = [i**3 for i in range(1,11) if i**3 % 4 == 0 ]


>>>
>>> print cubes_by_four
[8, 64, 216, 512, 1000]

Exercise 2

>>> to_one_hundred = range(101)


>>>
>>> backwards_by_tens=to_one_hundred[::-10]
>>> print backwards_by_tens
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0]
>>>
>>>

Exercise 3

>>> to_21=range(1,22)
>>> print to_21
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
>>>
>>> odds=to_21[0::2]
>>> print odds
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
>>>
>>> middle_third=to_21[7:14:1]
>>> print middle_third
[8, 9, 10, 11, 12, 13, 14]
>>>

Exercise 4

>>> squares= [i**2 for i in range(1,11) ]


>>> print squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
>>> print filter(lambda x: x<=70 and x>=30,squares)
[36, 49, 64]
>>>

Exercise 5

>>> garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"


>>>
>>> mess1=garbled[::-1]
>>> print mess1
IX XaXmX XtXhXeX XsXeXcXrXeXtX XmXeXsXsXaXgXeX!
>>>
>>> #Using filter
...
>>> message=filter(lambda let: let != "X",mess1)
>>> print message
I am the secret message!
>>>
>>>#Using list slicing
...
>>> message=mess1[::2]
>>> print message
I am the secret message!

```

Introduction to Bitwise Operators


A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast,
primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations. In
this chapter you will learn more about this topic.

Bitwise operators basics


Bitwise operations might seem a little esoteric and tricky at first, but you'll get the hang of them pretty quickly.
Bitwise operations are operations that directly manipulate bits. In all computers, numbers are represented with bits, a series
of zeros and ones. In fact, pretty much everything in a computer is represented by bits. This course will introduce you to the
basic bitwise operations and then show you what you can do with them.
Here is a list with one of the most used bitwise operators. We will explain them and exercise them later on.
Bitwise operator

Name

Execution

print 5 >> 4

Right Shift

print 5 << 1

Left Shift

10

print 8 & 5

Bitwise AND

print 9 pipe 4

Bitwise OR

13

print 12 ^ 42

Bitwise XOR

38

print ~88

Bitwise NOT

-9

The Base 2 Number System


When we count, we usually do it in base 10. That means that each place in a number can hold one of ten values, 0-9. In
binary we count in base two, where each place can hold one of two values: 0 or 1. The counting pattern is the same as in
base 10 except when you carry over to a new column, you have to carry over every time a place goes higher than one (as
opposed to higher than 9 in base 10).
For example, the numbers one and zero are the same in base 10 and base 2. But in base 2, once you get to the number 2
you have to carry over the one, resulting in the representation "10". Adding one again results in "11" (3) and adding one
again results in "100" (4).
Contrary to counting in base 10, where each decimal place represents a power of 10, each place in a binary number
represents a power of two (or a bit). The rightmost bit is the 1's bit (two to the zero power), the next bit is the 2's bit (two to
the first), then 4, 8, 16, 32, and so on.
The binary number '1010' is 10 in base 2 because the 8's bit and the 2's bit are "on". In Python, you can write numbers in
binary format by starting the number with` 0b. When doing so, the numbers can be operated on like any other number.
That is :
-

system

base 10

0/1

0/1

0/1

0/1

base 2

Examples

in base 10 is 2

in base 10 is 10

in base 10 is 4

in base 10 in 5

In Python you have only to invert the values:


-

system

base 10

Examples

in base 10 is 2

in base 10 is 10

Here you ca find an example using Python:

>>> print 0b1,


1
>>> print 0b10,
2
>>> print 0b11,
3
>>> print 0b100,
4
>>> print 0b101,
5
>>> print 0b110,
6
>>> print 0b111
7
>>> print "******"

******
>>> print 0b1 + 0b11
4
>>> print 0b11 * 0b11
9
>>>

Practice 1
Try to full-fill the values:

one = 0b1
two = 0b10
three = 0b11
four
five
six
seven
eight
nine
ten
eleven
twelve

Answer:

one = 0b0001
two = 0b0010
three = 0b0011
four = 0b0100
five = 0b0101
six = 0b0110
seven = 0b0111
eight = 0b1000
nine = 0b1001
ten = 0b1010
eleven = 0b1011
twelve = 0b1100

bin()
There are Python functions that can aid you with bitwise operations. In order to print a number in its binary representation,
you can use the bin() function. bin() takes an integer as input and returns the binary representation of that integer in a
string. (Keep in mind that after using the bin function, you can no longer operate on the value like a number.)
You can also represent numbers in base 8 and base 16 using the oct() and hex() functions.
For example:

>>> print bin(1)


0b1 #This is a string!Be careful!
>>>

int()
Python has an int() function that you've seen a bit of already. It can turn non-integer input into an integer. What you
might not know is that the int` function actually has an optional second parameter.

>>> int("110", 2)
6

When given a string containing a number and the base that number is in, the function will return the value of that number
converted to base ten.
Practice 2
Print this code and analize the results:

print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)
print int(bin(5),2)

The results should be:

>>> print int("1",2)


1
>>> print int("10",2)
2
>>> print int("111",2)
7
>>> print int("0b100",2)
4
>>> print int(bin(5),2)
5

Bitwise operators
left and right shift bitwise operators
The next two operations we are going to talk about are the left and right shift bitwise operators. These operators work by
shifting the bits of a number over by a designated number of slots.
This operation is mathematically equivalent to floor dividing and multiplying by 2 (respectively) for every time you shift, but
it's often easier just to think of it as shifting all the 1s and 0s left or right by the specified number of slots.
Note that you can only do bitwise operations on an integer. Trying to do them on strings or floats will result in nonsensical
output.
Practice 1
Shift the variable shift_right to the right twice (>> 2) and shift the variable shift_left to the left twice (<< 2). Try to
guess what the printed output will be.

>>> shift_right = 0b1100


>>> shift_left = 0b1
>>>
>>> shift_right=shift_right >>2
>>> shift_left=shift_left <<2
>>>
>>>
>>> print bin(shift_right)
0b11
>>> print bin(shift_left)
0b100
>>>

AND (&) operator


The bitwise AND (&) operator compares two numbers on a bit level and returns a number where the bits of that number are
turned on if the corresponding bits of both numbers are 1. For example:
a: 00101010 42
b: 00001111 15
a & b: 00001010 10
So remember, for every given bit in a and b:

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

Parctice 2
Print out the result of calling bin() on 0b1110 & 0b101.

>>> print bin(0b1110 & 0b101)


0b100

The bitwise OR (|) operator


The bitwise OR (|) operator compares two numbers on a bit level and returns a number where the bits of that number are
turned on if either of the corresponding bits of either number are 1. For example:
a: 00101010 42
b: 00001111 15
a | b: 00101111 47
So remember, for every given bit in a and b:

0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1

Parctice 3
For practice, print out the result of using | on 0b1110 and 0b101 as a binary string. Try to do it on your own without using
the | operator if you can help it.

>>> or_var=0b1110 | 0b101


>>>
>>> print or_var
15
>>> print bin(or_var)
0b1111
>>>

The XOR (^) or exclusive or operator


The XOR (^) or exclusive or operator compares two numbers on a bit level and returns a number where the bits of that
number are turned on if either of the corresponding bits of the two numbers are 1, but not both.
a: 00101010 42
b: 00001111 15
a ^ b: 00100101 37
So remember, for every given bit in a and b:

0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0

Practice 4
For practice, print the result of using ^ on 0b1110 and 0b101 as a binary string. Try to do it on your own without using the ^
operator.

>>> xor= 0b1110 ^ 0b101


>>>
>>> print xor
11
>>> print bin(xor)

0b1011
>>>

NOT (~) bitwise operator


The bitwise NOT operator (~) just flips all of the bits in a single number. What this actually means to the computer is
actually very complicated, so we're not going to get into it. Just know that mathematically, this is equivalent to adding one to
the number and then making it negative. For example:

>>> print ~3
-4
>>> print ~42
-43
>>>

Advanced concepts about bitwise operators


A bit mask is just a variable that aids you with bitwise operations. A bit mask can help you turn specific bits on, turn others
off, or just collect data from an integer about which bits are on or off.
Let's see an example:
Practice 1
Define a function, `check_bit4, with one argument, input, an integer. It should check to see if the fourth bit from the right is
on. If the bit is on, return "on" (not print!) If the bit is off, return "off".

>>> def check_bit4(input):


... mask=0b1000
... if input&mask >0:
... return "on"
... else:
... return "off"
...
>>>
>>> check_bit4(0b1100)
'on'
>>>

You can also use masks to turn a bit in a number on using |. For example, let's say I want to make sure the rightmost bit
of number a is turned on. I could do this:

>>> a = 0b110 # 6
>>> mask = 0b1 # 1
>>> desired = a | mask # 0b111, or 7
>>>

Using the bitwise | operator will turn a corresponding bit on if it is off and leave it on if it is already on.
Using the XOR (^) operator is very useful for flipping bits. Using ^ on a bit with the number one will return a result where
that bit is flipped.
For example, let's say I want to flip all of the bits in a. I might do this:

>>>
>>> a = 0b110 # 6
>>> mask = 0b111 # 7
>>> desired = a ^ mask # 0b1

Finally, you can also use the left shift (<<) and right shift (>>) operators to slide masks into place.

>>> a = 0b101
>>> # Tenth bit mask
...
>>> mask = (0b1 << 9) # One less than ten
>>> desired = a ^ mask

Let's say that I want to turn on the 10th bit from the right of the integer a.
Instead of writing out the entire number, we slide a bit over using the << operator.

We use 9 because we only need to slide the mask nine places over from the first bit to reach the tenth bit.

Exercises:Introduction to Bitwise Operators


Exercise 1
We have the variable a = 0b10111011 . Use a bitmask and the value a in order to achieve a result where the third bit from
the right of a is turned on. Be sure to print your answer as a bin() string.
Exercise 2
We have the variable a = 0b10111011 ..Use a bitmask and the value a in order to achieve a result where all of the bits in a
are flipped. Be sure to print your answer as a bin() string.
Exercise 3
Define a function called `flip_bit that takes the inputs (number, n). Flip the nth bit (with the ones bit being the first bit) and
store it in result. Return the result of calling bin(result).

Solutions
Exercise 1

>>> a = 0b10111011
>>>
>>> bitmask = 0b100
>>> print bin(a | bitmask)
0b10111111

Exercise 2

>>> a = 0b11101110
>>> mask = 0b11111111
>>> result = a^mask
>>> print bin(result)
0b10001
>>>

Exercise 3

>>> def flip_bit(number,n):


... mask=(0b1<<n-1)
... return bin(number^mask)
...
>>>
>>> flip_bit(0b1000111,4)
'0b1001111'
>>>

Note: mask=(0b1<<n-1) is going to slide over a number or add zeros to this particular number starting from the right and
going left

Classes
Classes give us the ability to create more complicated data structures that contain arbitrary content. Classes are a crucial
part of OOP (Object oriented programming).

Classes basics
A class is basically a scope inside which various code (especially function definitions) is executed, and the locals to this
scope become attributes of the class, and of any objects constructed by this class.
Python is an object-oriented programming language, which means it manipulates programming constructs called objects.
You can think of an object as a single data structure that contains data as well as functions; functions of objects are called
methods. For example, any time you call len("Eric") . Python is checking to see whether the string object you passed it
has a length, and if it does, it returns the value associated with that attribute. When you call my_dict.items() . Python
checks to see if my_dict has an items() method (which all dictionaries have) and executes that method if it finds it.
But what makes "Eric" a string and my_dict a dictionary? The fact that they're instances of the str and dict classes,
respectively. In other words,a class is just a way of organizing and producing objects with similar attributes and methods.
This OOP is a very powerful tool and it can be very useful.In Phyton Documentation you can find more information about it.
Class syntaxis
A basic class consists only of the class keyword, the name of the class, and the class from which the new class inherits in
parentheses. For now, our classes will inherit from the object class, like so:

class NewClass(object):

This gives them the powers and abilities of a Python object. By convention, user-defined Python class names start with a
capital letter.
Practice 1
Create a class called Animal in the editor. For now, in the body of your class, use the pass keyword. ( pass` doesn't do
anything, but it's useful as a placeholder in areas of your code where Python expects an expression.) Don't loose this code,
we are going to continue modifying it in next practices of this section.

>>> class Animal(object):


... pass
...
>>>

We'd like our classes to do more than... well, nothing, so we'll have to replace our pass with something else.
Initializing classes
We should start our class definition off with an odd-looking function: __init__() . This function is required for classes, and
it's used to initialize the objects it creates. __init__() always takes at least one argument, self , that refers to the object
being created. You can think of __init__() as the function that "boots up" each object the class creates.
Practice 2
Remove the pass statement in your class definition, then go ahead and define an __init__() function for your Animal
class. Pass it the argument self for now. Finally, put the pass into the body of the `init() definition, since it will expect an
indented block.

>>> class Animal(object):


... def __init__(self):
... pass
...

...
>>>

Let's make one more tweak to our class definition, then go ahead and instantiate (create) our first object.
So far, __init__() only takes one parameter: self . This is a Python convention; there's nothing magic about the word
"self". However, it's overwhelmingly common to use self as the first parameter in __init__() , so you should do this so that
other people will understand your code.
The part that is magic is the fact that self is the first parameter passed to __init__() . Python will use the first parameter
that __init__() receives to refer to the object being created; this is why it's often called self, since this parameter gives the
object being created its identity.
Parctice 3
Pass __init__() a second parameter, name. In the body of __init__() , let the function know that name refers to the
created object's name by typing self.name = name .

>>> class Animal(object):


... def __init__(self, name):
... self.name=name
...
...
>>>

Access attributes of objects


We can access attributes of our objects using dot notation.
Here's how it works:

>>> class Square(object):


... def __init__(self):
... self.sides = 4
...
>>> my_shape = Square()
>>> print my_shape.sides
4
>>>

Practice 4
Outside the Animal class definition, create a variable named zebra and set it equal to Animal("Jeffrey") . Then print out
zebra's name.

>>> class Animal(object):


... def __init__(self, name):
... self.name=name
...
...
>>> zebra=Animal("Jeffrey")
>>> print zebra.name
Jeffrey

As mentioned, you can think of __init__() as the method that "boots up" a class' instance object: the init bit is short for
"initialize."

The first argument __init__() gets is used to refer to the instance object, and by convention, that argument is called self.
If you add additional argumentsfor instance, a name and age for your animalsetting each of those equal to self.name
and self.age in the body of __init__() will make it so that when you create an instance object of your Animal class, you
need to give each instance a name and an age, and those will be associated with the particular instance you create.
Practice 5
Analyze this code. You can copy it in a file calles animals.py and execute it. What happend?

# Class definition
class Animal(object):
"""Makes cute animals."""
# For initializing our instance objects
def __init__(self, name, age, is_hungry):
self.name = name
self.age = age
self.is_hungry=is_hungry
# Note that self is only used in the __init__()
# function definition; we don't need to pass it
# to our instance objects.
zebra = Animal("Jeffrey", 2, True)
giraffe = Animal("Bruce", 1, False)
panda = Animal("Chad", 7, True)
print zebra.name, zebra.age, zebra.is_hungry
print giraffe.name, giraffe.age, giraffe.is_hungry
print panda.name, panda.age, panda.is_hungry

Execution:

root@erlerobot:~/Python_files# python animals.py


Jeffrey 2 True
Bruce 1 False
Chad 7 True
root@erlerobot:~/Python_files#

Class scope
Another important aspect of Python classes is scope. The scope of a variable is the context in which it's visible to the
program.
It may surprise you to learn that not all variables are accessible to all parts of a Python program at all times. When dealing
with classes, you can have variables that are available everywhere (global variables), variables that are only available to
members of a certain class (member variables), and variables that are only available to particular instances of a class
(instance variables).
The same goes for functions: some are available everywhere, some are only available to members of a certain class, and
still others are only available to particular instance objects.
For example:

class Animal(object):
"""Makes cute animals."""
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age

Each individual animal gets its own name and age (since they're all initialized individually), but they all have access to the
member variable is_alive , since they're all members of the Animal class.

Member variables and functions


Methods
When a class has its own functions, those functions are called methods. You've already seen one such
method: __init__() . But you can also define your own methods.
Practice 1
Going back to the Animals example, where we have this code:

class Animal(object):
"""Makes cute animals."""
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age

Add a method, description, to your Animal` class. Using two separate print statements, it should print out the name and
age of the animal it's called on. Then, create an instance of Animal, hippo (with whatever name and age you like), and call
its description method.
Answer: copy this in a file called hippo.py :

class Animal(object):
"""Makes cute animals."""
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age

def description(self):
print self.name
print self.age
hippo=Animal("George","12")
print hippo.description()

Here you have the result of the execution:

root@erlerobot:~/Python_files# python hippo.py


George
12
None
root@erlerobot:~/Python_files#

Member variables
A class can have any number of member variables. These are variables that are available to all members of a class.
Practice 2
You have this piece of code:

class Animal(object):
"""Makes cute animals."""
is_alive = True #This is the member variable
def __init__(self, name, age):

self.name = name
self.age = age

def description(self):
print self.name
print self.age
hippo=Animal("George","12")
print hippo.description()

After line 3, add a second member variable called health that contains the string "good". Then, create two new Animals:
sloth and ocelot . (Give them whatever names and ages you like.) Finally, on three separate lines, print out the health of

your hippo, sloth, and ocelot.


Answer:store this code in a file:

class Animal(object):
"""Makes cute animals."""
is_alive = True #This is the member variable
health="good"
def __init__(self, name, age):
self.name = name
self.age = age

def description(self):
print self.name
print self.age
hippo=Animal("George","12")
print hippo.description()
sloth=Animal("Mani","7")
ocelot=Animal("Prince","2")
print "sloth health:",sloth.health
print "ocelot health:", ocelot.health
print "hippo health:", hippo.health

The result when running it :

root@erlerobot:~/Python_files# python zoo.py


George
12
None
sloth health: good
ocelot health: good
hippo health: good
root@erlerobot:~/Python_files#

Inheritance
Inheritance is the process by which one class takes on the attributes and methods of another, and it's used to express an
is-a relationship. For example, a Panda is a bear, so a Panda class could inherit from a Bear class. However, a Toyota is
not a Tractor, so it shouldn't inherit from the Tractor class (even if they have a lot of attributes and methods in common).
Instead, both Toyota and Tractor could ultimately inherit from the same Vehicle class.
Practice 1
Analyze the following code. You can copy it to a file called car_prog.py and execute it.

class Customer(object):
"""Produces objects that represent customers."""
def __init__(self, customer_id):
self.customer_id = customer_id
def display_cart(self):
print "I'm a string that stands in for the contents of your shopping cart!"
class ReturningCustomer(Customer):
"""For customers of the repeat variety."""
def display_order_history(self):
print "I'm a string that stands in for your order history!"
monty_python = ReturningCustomer("ID: 12345")
monty_python.display_cart()
monty_python.display_order_history()

Execution:

root@erlerobot:~/Python_files# python car_prog.py


I'm a string that stands in for the contents of your shopping cart!
I'm a string that stands in for your order history!
root@erlerobot:~/Python_files#

Note:We've defined a class, Customer, as well as a ReturningCustomer class that inherits from Customer. Note that we
don't define the display_cart method in the body of ReturningCustomer, but it will still have access to that method via
inheritance.

Inheritance syntaxis
In Python, inheritance works like this:

class DerivedClass(BaseClass):
# code goes here

where DerivedClass is the new class you're making and BaseClass is the class from which that new class inherits.
Practice 2
Given this code:

class Shape(object):
"""Makes shapes!"""
def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides

Create your own class, Triangle, that inherits from Shape, like this:

class Triangle(Shape):
# code goes here

Inside the Triangle class, write an __init__() function that takes four arguments: self, side1, side2, and side3.
Inside the __init__() function, set self.side1 = side1 , self.side2 = side2 , and `self.side3 = side3.
The resulting code is:

class Shape(object):
"""Makes shapes!"""
def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides

class Triangle(Shape):
def __init__(self,side1,side2,side3):
self.side1=side1
self.side2=side2
self.side3=side3

Which is the original class and the one that inherits?

Override
Sometimes you'll want one class that inherits from another to not only take on the methods and attributes of its parent, but
to override one or more of them.
Practice 3
We have the following code:

class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00

Now, you are asked to: Create a new class, PartTimeEmployee , that inherits from Employee. Give your derived class a
calculate_wage method that overrides Employee's. It should take self and hours as arguments. Because
PartTimeEmployee.calculate_wage overrides Employee.calculate_wage , it still needs to set self.hours = hours . It should

return the part-time employee's number of hours worked multiplied by 12.00 .


Answer, the final code should be:

class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00

class PartTimeEmployee(Employee):

def calculate_wage(self, hours):


self.hours = hours
return hours * 12.00

super call

On the flip side, sometimes you'll be working with a derived class (or subclass) and realize that you've overwritten a method
or attribute defined in that class' base class (also called a parent or superclass) that you actually need. You can directly
access the attributes or methods of a superclass with Python's built-in super call.
The syntax looks like this:

class Derived(Base):
def m(self):
return super(Derived, self).m()

Where m() is a method from the base class.


Practice 4
After the code in Practice 3: First, inside your PartTimeEmployee class:
Add a new method called full_time_wage with the arguments self and hours.
That method should return the result of a super call to the calculate_wage method of PartTimeEmployee's parent
class.
Then, after your class:
Create an instance of the PartTimeEmployee class called milton. Don't forget to give it a name.
Finally, print out the result of calling his full_time_wage method . You should see his wage printed out at $20.00 per
hour! (That is, for 10 hours, the result should be 200.00.)
Answer should be:

class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
def full_time_wage(self, hours):
return super(PartTimeEmployee, self).calculate_wage(hours)
milton = PartTimeEmployee("Milton")
print milton.full_time_wage(10)

Exercises:Classes
Exercise 1
Follow the steps:
Create a class, Triangle. Its __init__() method should take self , angle1 , angle2 , and angle3 as arguments.
Make sure to set these appropriately in the body of the __init__() method.
Create a variable named number_of_sides and set it equal to 3.
Create a method named check_angles . The sum of a triangle's three angles is It should return True if the sum of
self.angle1, self.angle2, and self.angle3 is equal 180, and False otherwise.
Create a variable named my_triangle and set it equal to a new instance of your Triangle class. Pass it three angles
that sum to 180 (e.g. 90, 30, 60).
Print out my_triangle.number_of_sides and print out my_triangle.check_angles() .
Exercise 2
Define a class called Songs , it will show the lyrics of a song. Its __init__() method should have two arguments: self anf
lyrics . lyrics is a list. Inside your class create a method called sing_me_a_song that prints each element of lyrics on his

own line. Define a varible:

happy_bday = Song(["May god bless you, ",


"Have a sunshine on you,",
"Happy Birthday to you !"])

Call the sing_me_song mehod on this variable.


Exercise 3
Define a class called Lunch .Its __init__() method should have two arguments: self anf menu .Where menu is a string.
Add a method called menu_price .It will involve a if statement:
if "menu 1" print "Your choice:", menu, "Price 12.00", if "menu 2" print "Your choice:", menu, "Price 13.40", else print
"Error in menu".
To check if it works define: Paul=Lunch("menu 1") and call Paul.menu_price() .
Exercise 4
Define a Point3D class that inherits from object Inside the Point3D class, define an __init__() function that accepts self, x,
y, and z, and assigns these numbers to the member variables self.x , self.y , self.z . Define a __repr__() method that
returns "(%d, %d, %d)" % (self.x, self.y, self.z) . This tells Python to represent this object in the following format: (x, y,
z). Outside the class definition, create a variable named my_point containing a new instance of Point3D with x=1, y=2, and
z=3. Finally, print my_point .

Solutions
Exercise 1

>>> class Triangle(object):


... def __init__(self,angle1,angle2,angle3):
... self.angle1=angle1
... self.angle2=angle2
... self.angle3=angle3
...
... number_of_sides=3
... def check_angles(self):

... if self.angle1+self.angle2+self.angle3 ==180:


... return True
... else:
... return False
...
>>> class Equilateral(Triangle):
... angle = 60
... def __init__(self):
... self.angle1 = self.angle2 = self.angle3 = self.angle
...
>>> my_triangle=Triangle(90,30,60)
>>>
>>> print my_triangle.number_of_sides
3
>>> print my_triangle.check_angles()
True
>>>
>>>

Exercise 2

>>> class Song(object):


... def __init__(self, lyrics):
... self.lyrics=lyrics
... def sing_me_a_song(self):
... for line in self.lyrics:
... print line
...
>>>
>>> happy_bday = Song(["May god bless you, ",
... "Have a sunshine on you,",
... "Happy Birthday to you !"])
>>>
>>> print happy_bday.sing_me_a_song()
May god bless you,
Have a sunshine on you,
Happy Birthday to you !
None
>>>

Exercise 3
You can copy this code in a file called menu.py :

class Lunch(object):
def __init__(self,menu):
self.menu=menu
def menu_price(self):
if self.menu=="menu 1":
print "Your choice:", menu, "Price 12.00"
elif self.menu=="menu 2":
print "Your choice:", menu, "Price 13.40"
else:
print "Error in menu"
Paul=Lunch("menu 1")
Paul.menu_price()

The execution should be:

root@erlerobot:~/Python_files# python menu.py


Your choice: menu 1 Price 12.00
root@erlerobot:~/Python_files#

Exercise 4
Copy the following code in a file called 3d.py :

class Point3D(object):
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def __repr__(self) :
return "(%d, %d, %d)" % (self.x, self.y, self.z)

my_point=Point3D(1,2,3)
print my_point

Now, run the file:

root@erlerobot:~/Python_files# python menu.py


(1, 2, 3)
root@erlerobot:~/Python_files#

Exercise: Car
In this exercise you will review the object oriented programming and what you have learn in Classes chapter.

Car
We are going to follow the exercise instructions step by step and give solutions to each step, so you canfollow it easily.Also,
we will review the conceps shown in classes to fix them.

Ready? The computing starts here:


Defining a class is much like defining a function, but we use the class keyword instead. We also use the word object in
parentheses because we want our classes to inherit the object class. This means that our class has all the properties
of an object, which is the simplest, most basic class.
Define a new class named "Car". For now, since we have to put something inside the class, use the pass
keyword.
We can use classes to create new objects, which we say are instances of those classes.
Below your Car class, create a new object named my_car that is an instance of Car.
Solution 1

>>> class Car(object):


... pass
...
... my_car=Car()
>>>

Classes can have member variables that store information about each class object. We call them member variables
since they are information that belongs to the class object.
Inside your Car class, replace the pass statement with a new member variable named `condition and give it an
initial value of the string "new".
At the end of your code, use a print statement to display the condition of my_car .
Solution2

>>>
>>> class Car(object):
... condition="new"
...
>>> my_car=Car()
>>> print my_car.condition
new
>>>

There is a special function named __init__() that gets called whenever we create a new instance of a class.The first
argument passed to init( ) must always be the keyword self - this is how the object keeps track of itself internally - but we

can pass additional variables after that.In order to assign a variable to the class (creating a member variable), we use
dot notation.
Define the __init__() function of the Car class to take four inputs: self, model, color, and mpg. Assign the last
three inputs to member variables of the same name by using the self keyword.
Then, modify the object my_car to provide the following inputs at initialization:

model = "DeLorean"
color = "silver"
mpg = 88

Solution 3

>>> class Car(object):


... condition="new"
... def __init__(self,model,color,mpg):
... self.model=model
... self.color=color
... self.mpg=mpg
...
>>>
>>>
>>>
>>> my_car=Car("DeLorean","silver",88)
>>> print my_car.condition
new
>>>

Calling class member variables works the same whether those values are created within the class (like our car's
condition) or values are passed into the new object at initialization. We use dot notation to access the member
variables of classes since those variables belong to the object.
Now that you've created my_car print its member variables:First print the model of my_car . Then print out the
color of my_car .Finally, print out the mpg of `my_car.
Solution 4

>>> class Car(object):


... condition="new"
... def __init__(self,model,color,mpg):
... self.model=model
... self.color=color
... self.mpg=mpg
...
>>> my_car=Car("DeLorean","silver",88)
>>> print my_car.model
DeLorean
>>> print my_car.color
silver
>>> print my_car.mpg
88
>>>

Besides member variables, classes can also have their own methods (functions inside the class).
Inside the Car class, add a method named display_car() to Car that will reference the Car's member variables to
return the string, "This is a [color] [model] with [mpg] MPG." You can use the str() function to turn your mpg into
a string when creating the display string.
Replace the individual print statements with a single print command that displays the result of calling
my_car.display_car() .

Solution 5

>>> class Car(object):


... condition = "new"
... def __init__(self, model, color, mpg):
... self.model = model
... self.color = color
... self.mpg = mpg
...
... def display_car(self):
... return "This is a %s %s with %s MPG." % (self.color,self.model,str(self.mpg))
...
>>>
>>> my_car = Car("DeLorean", "silver", 88)
>>> print my_car.display_car()
This is a silver DeLorean with 88 MPG.

>>>

We can modify variables that belong to a class the same way that we initialize those member variables.
Inside the Car class, add a method drive_car() that sets self.condition to the string "used".
Remove the call to my_car.display_car() and instead print only the condition of your car.
Then drive your car by calling the drive_car() method.
Finally, print the condition of your car again to see how its value changes.
Solution 6

>>> class Car(object):


... condition = "new"
... def __init__(self, model, color, mpg):
... self.model = model
... self.color = color
... self.mpg = mpg
...
... def display_car(self):
... return "This is a %s %s with %s MPG." % (self.color,self.model,str(self.mpg))
...
... def drive_car(self):
... self.condition="used"
...
>>>
>>>
>>> my_car = Car("DeLorean", "silver", 88)
>>> print my_car.condition
new
>>> my_car.drive_car()
>>> print my_car.condition
used
>>>
>>>

One of the benefits of classes is that we can create more complicated classes that inherit variables or methods from
their parent classes. This saves us time and helps us build more complicated objects, since these child classes can
also include additional variables or methods.
Create a class ElectricCar that inherits from Car. Give your new class an __init__() method of that includes a
"battery_type" member variable in addition to the model, color and mpg.
Then, create an electric car named "my_car" with a "molten salt" battery_type. Supply values of your choice for
the other three inputs (model, color and mpg).
Solution 7

>>> class Car(object):


... condition = "new"
... def __init__(self, model, color, mpg):
... self.model = model
... self.color = color
... self.mpg = mpg
...
... def display_car(self):
... return "This is a %s %s with %s MPG." % (self.color,self.model,str(self.mpg))
...
... def drive_car(self):
... self.condition="used"
...
>>>
>>>
>>> class ElectricCar(Car):
... def __init__(self,model, color, mpg, battery_type):
... self.model = model
... self.color = color
... self.mpg = mpg
... self.battery_type=battery_type
...
>>>
>>>

>>>
>>>
>>> my_car=ElectricCar("DeLorean", "silver", 88,"molten salt")
>>>

Since our ElectricCar is a more specialized type of Car, we can give the ElectricCar its own drive_car() method that
has different functionality than the original Car class's.
Inside ElectricCar add a new method drive_car() that changes the car's condition to the string "like new".
Then, outside of ElectricCar, print the condition of my_car .
Next, drive my_car by calling the drive_car() function.
Finally, print the condition of my_ca r again
Solution 8

>>>
>>> class Car(object):
... condition = "new"
... def __init__(self, model, color, mpg):
... self.model = model
... self.color = color
... self.mpg = mpg
...
... def display_car(self):
... return "This is a %s %s with %s MPG." % (self.color,self.model,str(self.mpg))
...
... def drive_car(self):
... self.condition="used"
...
>>>
>>> class ElectricCar(Car):
... def __init__(self,model, color, mpg, battery_type):
... self.model = model
... self.color = color
... self.mpg = mpg
... self.battery_type=battery_type
...
... def drive_car(self):
... self.condition="like new"
...
>>>
>>>
>>> my_car=ElectricCar("DeLorean", "silver", 88,"molten salt")
>>> print my_car.condition
new
>>> my_car.drive_car()
>>> print my_car.condition
like new
>>>

Solution:Car
Store this code in a file called car.py . This code bellow to the last question of the exercise:

class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
return "This is a %s %s with %s MPG." % (self.color,self.model,str(self.mpg))
def drive_car(self):
self.condition="used"
class ElectricCar(Car):
def __init__(self,model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type=battery_type
def drive_car(self):
self.condition="like new"

my_car=ElectricCar("DeLorean", "silver", 88,"molten salt")


print my_car.condition
my_car.drive_car()
print my_car.condition

The execution should result on:

root@erlerobot:~/Python_files# python menu.py


new
like new
root@erlerobot:~/Python_files#

File Input/Output
So far, we have learned how to write programs and communicate our intentions to the Central Processing Unit using
conditional execution, functions, and iterations. We have learned how to create and use data structures in theMainMemory.
The CPU and memory are where our software works and runs. It is where all of the thinking happens. But if you recall
from our hardware architecture discussions, once the power is turned off, anything stored in either the CPU or main
memory is erased. So up to now, our programs have just been transient fun exercises to learn Python.
In this chapter, we start to work with Secondary Memory (or files). Secondary memory is not erased even when the power
is turned off.We will primarily focus on reading and writing text files such as those we create in a text editor.

Files basics
Until now, the Python code you've been writing comes from one source and only goes to one place: you type it in at the
keyboard and its results are displayed in the console. But what if you want to read information from a file on your computer,
and/or write that information to another file?
This process is called file I/O (the "I/O" stands for "input/output"), and Python has a number of built-in functions that handle
this for you.
Opening a file
Let's walk through the process of writing to a file one step at a time.Let's analyze the follwing command:

f = open("output.txt", "w")

This told Python to open output.txt in "w" mode ("w" stands for "write"). We stored the result of this operation in a file
object, f.
Doing this opens the file in write-mode and prepares Python to send data into the file.
You can open files in write-only mode ("w"), read-only mode ("r"), read and write mode ("r+"), and append mode ("a", which
adds any new data you write to the file to the end of the file).
Parctice 1
First you need to create a file on your site, called "output.txt" (If the file doesn't exists Python can't open it). You can do this
easily from your terminal typing:

root@erlerobot:~/Python_files# touch output.txt

Create a variable, my_file , and set it equal to calling the open() function on output.txt . In this case, pass "r+" as a
second argument to the function so the file will allow you to read and write to it. Note: You should create a file output.txt .

my_file=open("output.txt","r+")

Writing on a file
Now it's time to write some data to our output.txt file.We can write to a Python file like so:

my_file.write("Data to be written")

The write() function takes a string argument, so we'll need to do a few things here: You must close the file. You do this
simply by calling `my_file.close() (we did this for you in the last exercise). If you don't close your file, Python won't write to it
properly.
Practice 2
Create a variables called my_list that contains the squared numbers from 1 to 10. Open yout my_list in "+r" mode and
iterate over it to get each value. Use my_file.write() to write each value to output.txt Make sure to call str() on the
iterating data so .write() will accept it Make sure to add a newline ("\n") after each element to ensure each will appear on
its own line. Use my_file.close() to close the file when you're done.

>>> my_list = [i**2 for i in range(1,11)]


>>>
>>> my_file = open("output.txt", "r+")
>>>
>>>
>>> for num in my_list:
... data=str(num)
... my_file.write(data)
... my_file.write("\n")
...
>>> my_file.close()

For now you don't know how to read the content in Python (is the next step), so if you want to check the result display the
content of the file output.txt from your terminal like this this:

root@erlerobot:~/Python_files# cat output.txt


1
4
9
16
25
36
49
64
81
100
root@erlerobot:~/Python_files#

Reading a file
Finally, we want to know how to read from our output.txt file. As you might expect, we do this with the read() function, like
so:

print my_file.read()

Parctice 3
Declare a variable, my_file , and set it equal to the file object returned by calling open() with both "output.txt" and "r".
Next, print the result of using .read() on my_file , like the example above. Make sure to .close() your file when you're
done with it. All kinds of doom will happen if you don't.

>>> my_file=open("output.txt","r")
>>>
>>> print my_file.read()
1
4
9
16
25
36
49
64
81
100
>>> my_file.close()

What if we want to read from a file line by line, rather than pulling the entire file in at once. Thankfully, Python includes a
readline() function that does exactly that.

If you open a file and call .readline() on the file object, you'll get the first line of the file; subsequent calls to .readline()

will return successive lines.


Practice 4
Create a file by using touch text.txt and edit it using vi text editor by typing vi text.txt .

root@erlerobot:~/Python_files# touch text.txt


root@erlerobot:~/Python_files# vi text.txt

Copy this content:

I'm the first line of the file!


I'm the second line.
Third line here, boss.

Declare a new variable my_file and store the result of calling open() on the "text.txt" file in "r"ead-only mode. On three
separate lines, print out the result of calling my_file.readline() . See how it gets the next line each time? Don't forget to
close() your file when you're done with it.

>>> my_file=open("text.txt","r")
>>>
>>> print my_file.readline()
"'m the first line of the file!\n"
>>>
>>> print my_file.readline()
"I'm the second line.\n"
>>>
>>> print my_file.readline()
'Third line here, boss.\n'
>>>
>>> my_file.close()
>>>

Closing files
We keep telling you that you always need to close your files after you're done writing to them.
During the I/O process, data is buffered: this means that it is held in a temporary location before being written to the file.
Python doesn't flush the bufferthat is, write data to the fileuntil it's sure you're done writing. One way to do this is to
close the file. If you write to a file without closing, the data won't make it to the target file.
Is there a way to get Python to automatically close our files for us?
Yes, there is.You may not know this, but file objects contain a special pair of built-in methods: __enter__() and
__exit__() . The details aren't important, but what is important is that when a file object's __exit__() method is invoked, it

automatically closes the file. We invoke this method:Using with and as .


The syntax looks like this:

with open("file", "mode") as variable:


# Read or write to the file

Practice 5
Write any data you like to the text.txt file using with...as . Give your file object the usual name: `my_file.

>>> with open("text.txt","r+") as my_file:


... my_file.write("Hey!I'm writing on the file!")
... print my_file.read()

Checking if the file is closed


Finally, we'll want a way to test whether a file we've opened is closed. Sometimes we'll have a lot of file objects open, and if
we're not careful, they won't all be closed. We can check it with:

f = open("bg.txt")
f.closed
# False
f.close()
f.closed
# True

Python file objects have a closed attribute which is True when the file is closed and False otherwise.
By checking file_object.closed , we'll know whether our file is closed and can call `close() on it if it's still open.
Practice 6
Following with the code in Practice 5: Check if the file is not .closed . If that's the case, call .close() on it. (You don't need
an else here, since your if statement should do nothing if .closed is True.) After your if statement, print out the value of
my_file.closed to make sure your file is really closed.

>>> with open("text.txt","r+") as my_file:


... my_file.write("Hey!I'm writing on the file!")
... print my_file.read()
...
>>> f=open("text.txt")
>>> f.closed # If this returns True the file is closed, if not it is opened.
False
>>>
>>> if f.closed==True:
... f.close()
...
>>>
>>>
>>> print my_file.closed
True

Exercises: File Input /Output


Exercise 1
Write a program to prompt for a file name, and then read through the file line-by-line. Note: the file name is Erle.txt and its
content is,

Erle is the enabling technology for the


next generation of aerial and terrestrial
robots that will be used in cities solving
tasks such as surveillance, enviromental
monitoring or even providing aid at catastrophes.

Ensure you create the file.


Exercise 2
Create a file called new_world.txt .First add a new line to the file: Welcome to robotics time. . And then print the content of
new_world.txt .

Solutions
Exercise 1
The solution code is the following:

name=raw_input("Enter the file name:")


my_file=open(name,"r")
print my_file.readline()
print my_file.readline()
print my_file.readline()
print my_file.readline()

my_file.close

Store this in e_py.py file. The result of the execution is:

root@erlerobot:~/Python_files# python e_py.py


Enter the file name:Erle.txt
Erle is the enabling technology for the
next generation of aerial and terrestrial
robots that will be used in cities solving
tasks such as surveillance, enviromental
root@erlerobot:~/Python_files#

Exericse 2
The code should be stored on nworld.py and then executed:

my_file=open("new_world.txt","r+")
line= "Welcome to robotics time."
my_file.write(line)

print my_file.read()
my_file.close()

root@erlerobot:~/Python_files# python nworld.py


Welcome to robotics time.

S-ar putea să vă placă și