Erle Robotics Learning Python Gitbook Free PDF
Erle Robotics Learning Python Gitbook Free PDF
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
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/
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:
./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:
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:
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:
Practice 2
Create a file containing three numbers and print them on the screen:
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.
>>> var="Hello"
>>> print "this is the variable: ", var
this is the variable: Hello
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.
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.
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.
lower() You can use the lower() method to get rid of all the capitalization in your strings.
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()``.
>>> string_1="Erle"
>>> string_2="drone"
>>> print " %s is an awesome %s!"%(string_1,string_2)
Erle is an awesome drone!
>>>
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:
Random numbers
The random module provides functions that generate pseudorandom numbers. For using this module capabilities you
should firts import it, with the syntxis:
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:
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()
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.
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.
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.
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:
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
Exercise 3
Exercise 4
Exercise 5
Exercise 6
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
<=
>
Greater than
>=
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.
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.
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.
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
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.
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!
>>> 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..."
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:
Solutions
Exercise 1
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
Exercise 4
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:
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.
Practice 2
Make the same and kind of function as in Practice 1, but using two arguments:base, exponent.
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:
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:
For example:
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.
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.
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 :
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:
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
Exercise 2
Exercise 3
Exercise 4
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
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
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):
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.
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']
>>>
part_list=list_name[1:3]
Practice 4
Given a list:
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.
Use the .index(item) function to find the index of "duck". Then .insert(index, item) the string "cobra" at that index.Print
the result.
>>> n = [1, 3, 5]
>>> n.pop(1)
3
>>> print n
[1, 5]
>>> 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:
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:
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?
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.
Practice 3
Use a for loop to print out all of the elements in the list names.
names = ["Adam","Alex","Mariah","Martine","Columbus"]
def fizz_count(x):
count=0
for item in x:
if item == "fizz":
count=count +1
print count
fizz_count(["fizz","buzz"])
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]
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.
Practice 3
Create a function that concatenates strings.
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:
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:
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.
>>>
>>> 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}
>>>
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:
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.
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."
}
>>> 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.
>>>
print dic_name.items()
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
>>>
inventory = {
'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'],
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}
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:
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:
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
Exercise 3
Create a shoplist.py list with this content:
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)
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))
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 ).
>>> board=["O"]*5
>>> print board
['O', 'O', 'O', 'O', 'O']
>>> print len(board)
5
`
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)
>>>
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:
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
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
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):
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 :
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:
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!'
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.
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:
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:
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:
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.
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:
We are going to make a program that search for "carrot" between this fruit. If it doesn't appear it shows a succes message:
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.
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:
>>> 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
Exercise 4
Exercise 5
Exercise 6
Exercise 7
Exercise 8
4
>>>
Exercise 9
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 .
>>> 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
>>>
>>>
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
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
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)
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.
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.
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:
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:
Practice 1
Given:
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.
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:
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) .
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:
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:
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.
Exercise 5
The string
Solutions
Exercise 1
Exercise 2
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
Exercise 5
```
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
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
system
base 10
Examples
in base 10 is 2
in base 10 is 10
******
>>> 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:
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)
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.
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
Parctice 2
Print out the result of calling bin() on 0b1110 & 0b101.
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.
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.
0b1011
>>>
>>> print ~3
-4
>>> print ~42
-43
>>>
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.
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
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.
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.
...
>>>
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 .
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.
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:
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.
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()
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
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
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:
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
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
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):
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()
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
Solutions
Exercise 1
Exercise 2
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()
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
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.
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
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
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
>>>
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
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
>>>
>>>
>>> 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"
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:
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.
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:
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()
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
Practice 5
Write any data you like to the text.txt file using with...as . Give your file object the usual name: `my_file.
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.
Solutions
Exercise 1
The solution code is the following:
my_file.close
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()