Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Learning Python 3 with the Linkbot/Printable version

From Wikibooks, open books for an open world
<Learning Python 3 with the Linkbot
This is theprint version ofLearning Python 3 with the Linkbot
You won't see this message or any elements not part of the book's content when you print orpreview this page.


Learning Python 3 with the Linkbot

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Learning_Python_3_with_the_Linkbot

Permission is granted to copy, distribute, and/or modify this document under the terms of theCreative Commons Attribution-ShareAlike 3.0 License.

Authors

The original authors and contributors for the original text as of this writing are:

  • Mike Challender
  • Ryan Uebner
  • David Ko (User:Davidko_barobo)
  • Natalie Ryland
  • Graham Ryland
  • Aaron Cooper
  • Dylan Besk

Additional Contributors

[edit |edit source]
Learning Python 3 with the Linkbot
Printable versionInstallation and Setup → 


Installation and Setup

Installing Python and the Linkbot Control Module (PyBarobo)

[edit |edit source]

For Python programming, you need a working Python installation and a text editor. Python comes with its own editorIDLE, which is quite nice and sufficient for the beginning programmer. As you get more into programming, you will probably switch to some other editor likeemacs,vi or another editor.

The Python download page is:https://www.python.org/downloads/. The most recent version is Python 3.10.6 (as of 8th August 2022);Python 2.7 and older versions will not work with this tutorial. There are various different installation files for different computer platforms available on the download site. Here are some specific instructions for the most common operating systems:

Ubuntu Linux Users

[edit |edit source]

To install everything you need to run this curriculum, which includes Python 3, Python 3 setup tools, and the Barobo Python package, make sure you have an internet connection and run these commands in a terminal window:

sudoapt-getinstallpython3python3-setuptoolspython3-numpyidle3sudoeasy_install3pybarobo

You will also have to add your user account to the "dialout" group. You can do this by using the command:

sudousermod-a-Gdialout$USER

The above command will add whatever user you are logged in as to the "dialout" group. If you wish to add a user account that is not the one that is logged in, replace "$USER" with the user name of the other account. You may have to log out and log back in for the change to take effect.

For other distributions of Linux, follow the instructions provided by either your distribution or on the Python website to getPython 3,NumPy, andPyBarobo installed.

Raspberry Pi (Raspbian) Users

[edit |edit source]

Raspbian comes with Python 3 and numpy installed by default. To get the Raspberry Pi ready to control the Linkbot, make sure your Pi is connected to the internet and type the following commands:

sudousermod-a-Gdialout$USERsudoapt-getinstallpython3-setuptoolssudoeasy_install3pybarobo

You may have to log out and log back in again for the changes to take effect.

Mac users

[edit |edit source]

Starting from Mac OS X (Tiger), Python ships by default with the operating system, but you will need to update to Python 3 until OS X starts including Python 3 (check the version by startingpython3 in a command line terminal). Also IDLE (the Python editor) might be missing in the standard installation. If you want to (re-)install Python, get the MacOS installer from thePython download site.

Windows users

[edit |edit source]

Download the appropriate Windows installer (thex86 MSI installer, if you do not have a 64-bit AMD or Intel chip). Even if you do have a 64-bit chip, I would still recommend downloading the 32-bit version because some of the Barobo Linkbot libraries are pre-built for 32-bit system by default. Start the installer by double-clicking it and follow the prompts. Be sure to include the optional package "pip", which can come in handy for installing additional Python modules and add-ons.

Template:Message box

Once Python is installed and the path is configured, open a command prompt and type the following command:

pipinstallpybarobo

Seehttps://docs.python.org/3/using/windows.html#installing-python for more information.

Configuring your PATH environment variable
[edit |edit source]

The PATH environment variable is a list of folders, separated by semicolons, in which Windows will look for a program whenever you try to execute one by typing its name at a Command Prompt. You can see the current value of your PATH by typing this command at a Command Prompt:

echo %PATH%

The easiest way to permanently change environment variables is to bring up the built-in environment variable editor in Windows. How you get to this editor is slightly different on different versions of Windows.

On Windows 8: Press the Windows key and typeControl Panel to locate the Windows Control Panel. Once you've opened the Control Panel, select View by: Large Icons, then click onSystem. In the window that pops up, click theAdvanced System Settings link, then click theEnvironment Variables... button.

On Windows 7 or Vista: Click the Start button in the lower-left corner of the screen, move your mouse overComputer, right-click, and selectProperties from the pop-up menu. Click theAdvanced System Settings link, then click theEnvironment Variables... button.

On Windows XP: Right-click theMy Computer icon on your desktop and selectProperties. Select theAdvanced tab, then click theEnvironment Variables... button.

Once you've brought up the environment variable editor, you'll do the same thing regardless of which version of Windows you're running. UnderSystem Variables in the bottom half of the editor, find a variable calledPATH. If there is one, select it and clickEdit.... Assuming your Python root is C:\Python34, add these two folders to your path (and make sure you get the semicolons right; there should be a semicolon between each folder in the list):

C:\Python34C:\Python34\Scripts

Note:If you want to double-click and start your Python programs from a Windows folder and not have the console window disappear, you can add the following code to the bottom of each script:

print("Hello World")#stops console from exitingend_prog=""whileend_prog!="q":end_prog=input("type q to quit")


Learning Python 3 with the Linkbot
 ← AuthorsPrintable versionIntro → 


Intro

First things first

[edit |edit source]

The Advanced Python 3 lessons before you are geared toward furthering your knowledge and abilities with programming using Python. The tutorials are designed to allow you to interact with the Linkbot robots by programming them to move in very specific ways. By seeing the Linkbot respond to your programming commands via code that you write, your abilities to use Python coding will motivate you to learn even more. First, you will just type in the code that is displayed in the tutorial to see how the Linkbot responds. Then, you will make your own changes to that code to play around with the Linkbot's abilities. The worst thing that can happen is that the program won't work and nothing will happen with the robot, so feel free to play with the code. When you are expected to type in code, it will look like this:

##Python is easy to learnprint("Hello, World!")

The reason that it will be formatted this way is to make code you need to type easy to distinguish from other text. Additionally, the code will be in color with different parts in different colors to help you see the code's distinct parts. When you enter code, it will not necessarily be in color, but it won't matter as long as you type it the same way that it is written here.

If the computer prints something out it will be formatted like this:

Hello, World!

(Note that printed text goes to your screen, and does not involve paper. Before computers had screens, the output of computer programs would be printed on paper.)

Please notice that these Advanced Python lessons are set up for Python 3, which means that most of the examples will not work in Python 2.7 and previous versions. Additionally, some of the extra lessons created by other programmers like you may not have been converted to Python 3. However, the differences between one version of Python and another are not really large, so if you learn how to code in one version, you should be able to read programs written for the other version without too much difficulty. At some point, you might want to look at the Non-Programmer's Tutorial for Python 2.6.


There will often be a mixture of the text you type (which is shown inbold) and the text the program prints on the screen, which would look like this:

Halt!Who Goes there?LinkbotYou may pass, Linkbot

These lessons will introduce you to the terminology or vocabulary of programming. For example, programming is also often calledcoding orhacking. By learning the special vocabulary of programming, you will be able to understand what programmers are talking about and sound like a programmer yourself.


Finally, it's very important for your success with these lessons that you have Python 3 software. If you don't already have the Python software, go tohttp://www.python.org/download/ and get the Python 3 version for your computer platform. Most likely if you are learning in a classroom, your teacher will already have done this for you beforehand. If not, download it, read the instructions, and install the program.

Installing Python and the Linkbot Control Module (PyBarobo)

[edit |edit source]

For Python programming, you need a working Python installation and a text editor. Python comes with its own editorIDLE, which is quite nice and sufficient for the beginning programmer. As you get more into programming, you will probably switch to some other editor likeemacs,vi or another editor.

The Python download page is:http://www.python.org/download. The most recent version is Python 3.4.2 (as of 18th October 2014);Python 2.7 and older versions will not work with this tutorial. There are various different installation files for different computer platforms available on the download site. Here are some specific instructions for the most common operating systems:

Ubuntu Linux Users

[edit |edit source]

To install everything you need to run this curriculum, which includes Python 3, Python 3 setup tools, and the Barobo Python package, make sure you have an internet connection and run these commands in a terminal window:

sudo apt-get install python3 python3-setuptools python3-numpy idle3sudo easy_install3 pybarobo

You will also have to add your user account to the "dialout" group. You can do this by using the command:

sudo usermod -a -G dialout $USER

The above command will add whatever user you are logged in as to the "dialout" group. If you wish to add a user account that is not the one that is logged in, replace "$USER" with the user name of the other account. You may have to log out and log back in for the change to take effect.

For other distributions of Linux, follow the instructions provided by either your distribution or on the Python website to getPython 3,NumPy, andPyBarobo installed.

Raspberry Pi (Raspbian) Users

[edit |edit source]

Raspbian comes with Python 3 and numpy installed by default. To get the Raspberry Pi ready to control the Linkbot, make sure your Pi is connected to the internet and type the following commands:

sudo usermod -a -G dialout $USERsudo apt-get install python3-setuptoolssudo easy_install3 pybarobo

You may have to log out and log back in again for the changes to take effect.

Mac users

[edit |edit source]

Starting from Mac OS X (Tiger), Python ships by default with the operating system, but you will need to update to Python 3 until OS X starts including Python 3 (check the version by startingpython3 in a command line terminal). Also IDLE (the Python editor) might be missing in the standard installation. If you want to (re-)install Python, get the MacOS installer from thePython download site.

Windows users

[edit |edit source]

Download the appropriate Windows installer (thex86 MSI installer, if you do not have a 64-bit AMD or Intel chip). Even if you do have a 64-bit chip, I would still recommend downloading the 32-bit version because some of the Barobo Linkbot libraries are pre-built for 32-bit system by default. Start the installer by double-clicking it and follow the prompts. Be sure to include the optional package "pip", which can come in handy for installing additional Python modules and add-ons.

Template:Message box

Next, you will need to install a driver, which is available here:Installer. Follow the link, download the file and run it.Once Python is installed and the path is configured, open a windows command prompt and type the following command:

pip install pybarobo

Seehttps://docs.python.org/3/using/windows.html#installing-python for more information.

Configuring your PATH environment variable
[edit |edit source]

The PATH environment variable is a list of folders, separated by semicolons, in which Windows will look for a program whenever you try to execute one by typing its name at a Command Prompt. You can see the current value of your PATH by typing this command at a Command Prompt:

echo %PATH%

The easiest way to permanently change environment variables is to bring up the built-in environment variable editor in Windows. How you get to this editor is slightly different on different versions of Windows.

On Windows 8: Press the Windows key and typeControl Panel to locate the Windows Control Panel. Once you've opened the Control Panel, select View by: Large Icons, then click onSystem. In the window that pops up, click theAdvanced System Settings link, then click theEnvironment Variables... button.

On Windows 7 or Vista: Click the Start button in the lower-left corner of the screen, move your mouse overComputer, right-click, and selectProperties from the pop-up menu. Click theAdvanced System Settings link, then click theEnvironment Variables... button.

On Windows XP: Right-click theMy Computer icon on your desktop and selectProperties. Select theAdvanced tab, then click theEnvironment Variables... button.

Once you've brought up the environment variable editor, you'll do the same thing regardless of which version of Windows you're running. UnderSystem Variables in the bottom half of the editor, find a variable calledPATH. If there is one, select it and clickEdit.... Assuming your Python root is C:\Python34, add these two folders to your path (and make sure you get the semicolons right; there should be a semicolon between each folder in the list):

C:\Python34C:\Python34\Scripts

Note:If you want to double-click and start your Python programs from a Windows folder and not have the console window disappear, you can add the following code to the bottom of each script:

print("Hello World")#stops console from exitingend_prog=""whileend_prog!="q":end_prog=input("type q to quit")

Interactive Mode

[edit |edit source]

Go into IDLE (also called the Python GUI). You should see a window that has some text like this:

Python 3.0 (r30:67503, Dec 29 2008, 21:31:07) [GCC 4.3.2 20081105 (Red Hat 4.3.2-7)] on linux2Type "copyright", "credits" or "license()" for more information.    ****************************************************************    Personal firewall software may warn about the connection IDLE    makes to its subprocess using this computer's internal loopback    interface.  This connection is not visible on any external    interface and no data is sent to or received from the Internet.    ****************************************************************    IDLE 3.0      >>>

The>>> is Python's way of telling you that you are ininteractive mode. In interactive mode what you type is immediatelyrun. Try typing1+1 in. Python will respond with2.Interactive mode allows you to test out and see what Python will do.If you ever feel you need to play with new Python statements, go intointeractive mode and try them out.

Creating and Running Programs

[edit |edit source]

Go into IDLE if you are not already. In the menu at the top, selectFile thenNew Window. In the new window that appears, type the following:

print("Hello, World!")

Now save the program: selectFile from the menu, thenSave. Save it as "hello.py" (you can save it in any folder you want). Now that it is saved it can be run. Just a Rookies note here, if you change a program, save it with a version notation likehelloV1.py that way you won't change your original program that worked.

Next run the program by going toRun thenRun Module (or if you have an older version of IDLE useEdit thenRun script). This will outputHello, World! on the*Python Shell* window.

For a more in-depth introduction to IDLE, a longer tutorial with screenshots can be found athttp://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html

Program file names

[edit |edit source]

It is very useful to stick to some rules regarding the file names of Python programs. Otherwise some thingsmight go wrong unexpectedly. These don't matter as much for programs, but you can have weird problems if you don't follow them for module names (modules will be discussed later).

  1. Always save the program with the extension.py. Do not put another dot anywhere else in the file name.
  2. Only use standard characters for file names: letters, numbers, dash (-) and underscore (_).
  3. White space ("") should not be used at all (use underscores instead).
  4. Do not use anything other than a letter (particularly no numbers!) at the beginning of a file name.
  5. Do not use "non-english" characters (such asä,ö,ü,å orß) in your file names—or, even better, do not use them at all when programming.

Using Python from the command line

[edit |edit source]

If you don't want to use Python from the command line, you don't have to, just use IDLE. To get into interactive mode just typepython3 without any arguments. To run a program, create it with a text editor (Emacs has a good Python mode) and then run it withpython3 program_name.

Additionally, to use Python within Vim, you may want to visitPython wiki page about VIM

Running Python Programs in *nix

[edit |edit source]

If you are using Unix (such as Linux, Mac OS X, or BSD), if you make the program executable withchmod, and have as the first line:

#!/usr/bin/env python3

you can run the python program with./hello.py like any other command.

Where to get help

[edit |edit source]

At some point in your Python career you will probably get stuck and have no clue about how to solve the problem you are supposed to work on. This tutorial only covers the basics of Python programming, but there is a lot of further information available.

Python documentation

[edit |edit source]

First of all, Python is very well documented. There might even be copies of these documents on your computer, which came with your Python installation:

  • The officialPython 3 Tutorial by Guido van Rossum is often a good starting point for general questions.
  • For questions about standard modules (you will learn what this is later), thePython 3 Library Reference is the place to look at.
  • If you really want to get to know something about the details of the language, thePython 3 Reference Manual is comprehensive but quite complex for beginners.

Python user community

[edit |edit source]

There are a lot of other Python users out there, and usually they are nice and willing to help you. Before you ask the Python user community a question, everyone will appreciate it if youdo a web search for a solution to your problem before contacting the community. This very active user community is organized mostly through mailing lists and a newsgroup:

  • Thetutor mailing list is for people who want to ask questions regarding how to learn computer programming with the Python language.
  • Thepython-help mailing list is python.org's help desk. You can ask a group of knowledgeable volunteers questions about all your Python problems.
  • The Python newsgroupcomp.lang.python (Google groups archive) is the place for general Python discussions, questions, and the central meeting point of the community.
  • Python wiki has alist of local user groups, you can join the group mailing list and ask questions. You can also participate in the user group meetings.


Learning Python 3 with the Linkbot
 ← Installation and SetupPrintable versionHello, World → 


Hello, World

Lesson Information**To Be Added**Vocabulary:Python Editor: a program used to create a block of text that will be sent to Python and interpreted. In thisbook we recommend IDLE 3.Line: a single sentence of programming code.  Lines of code can be used to measure the size of a program andcompare it to other programs.Function: a type of procedure or routine, a set of instructions to follow.Argument: data provided to a function as input.  This is like thedomain in algebra.String: a sequence of characters representing either a constant or a variable.Function Call:Necessary Materials and Resources:Computer Science Teachers Association Standards: L1:3.CT.4:Recognize that software is created to controlcomputer operationsCommon Core Math Practice Standards: CCSS.MATH.PRACTICE.MP5 Use appropriate tools strategically.


What you should know

[edit |edit source]

Once you've completed this chapter, you will know how to edit programs in aPython Editor, IDLE 3, or some other text editor, save them, and run them.

Printing

[edit |edit source]

Since the beginning of programming tutorials, "Hello World!"[1] has been the first foray into creating something on the screen, here is how to do it with Python:

print("Hello, World!")

If you are using the command line to run this program, then type it in a text editor, save it ashello.py and run it withpython3.0 hello.py

Otherwise go into your Python Editor, create a new file (Ctrl + N for IDLE), and create the program asin sectionCreating and Running Programs.

When this program is run here's what it prints:

Hello, World!

Remember, whenever you see code as an example, it's a good idea for you to type it in and run it. Learning by doing can be a powerful tool! It is worth the time it takes.

Here is a modified 'Hello World' using the Linkbot to say hello. Comments are added to help you understand what the code is doing step by step.

importbarobo#loads 'barobo' moduleimporttime#loads 'time' moduledongle=barobo.Dongle()#uses commands from 'barobo' to connect Linkbotdongle.connect()robotID=input('Enter Linkbot ID: ')#prompts user for Linkbot IDrobot=dongle.getLinkbot(robotID)print('Hello Linkbot Programmer')#prints greetingrobot.setBuzzerFrequency(1047)#calls for pizo buzzer to make a tonetime.sleep(0.25)#sets duration of tonerobot.setBuzzerFrequency(1567)#changes tonetime.sleep(0.5)robot.setBuzzerFrequency(0)#turns off tone.

Feel free to chance the frequency of the buzzer to change the tone, and the duration of time.sleep to see what that does to the greeting.

Now here is are a few more program:

print("I pledge allegiance to the flag")print("of the United States of America,")print("and to the republic, for which it stands,")

When you run this program it prints out:

I pledge allegiance to the flagof the United States of America,and to the republic, for which it stands,

When the computer runs this program it first sees theline (like one sentence of code):

print("I pledge allegiance to the flag")

so the computer prints:

I pledge allegiance to the flag

Then the computer goes down to the next line and sees:

print("of the United States of America,")

So the computer prints to the screen:

of the United States of America,

The computer keeps looking at each line, follows the command and then goes on to the next line. The computer keeps running commands until it reaches the end of the program.

Controlling a Linkbot LED Color

[edit |edit source]

Linkbots are equipped with a multi-color LED, which is basically just a light that can change colors.Lets try a simple program to control the LED color on a Linkbot. To get started, follow these steps:

  • Turn on your Linkbot by holding down the power button until the Linkbot flashes a bright red light.
  • After about 5 seconds, the Linkbot will beep and show a blue light. Your Linkbot is now on!
  • Take a Micro-USB cable and connect the Linkbot to your computer.
  • Open your text editor and try the following code:https://en.wikibooks.org/wiki/Learning_Python_3_with_the_Barobo_Linkbot
importbarobomyDongle=barobo.Dongle()myDongle.connect()myLinkbot=myDongle.getLinkbot()myLinkbot.setLEDColor(0,255,0)

Template:Message boxWhen you run this program, you should notice that your Linkbot turned green! In the code that you wrote, there were three numbers: 0, 255, and 0. These three numbers determine the brightness of the red, green, and blue LEDs inside the linkbot, where 0 denotes the lowest brightness setting and 255 the maximum setting. If you want to try making your Linkbot a brilliant purple color, try setting the color numbers to "255, 0, 255". This tells the Linkbot to turn on its red and blue LED's to their maximum brightness. When the red light blends with the blue light, it appears purple!

Terminology

[edit |edit source]

Now is probably a good time to give you a bit of an explanation of what is happening - and a little bit of programming terminology.

What we were doing above was using afunction calledprint. The function's name -print - is followed by parentheses containing zero or morearguments. So in this example

print("Hello, World!")

there is one argument, which is"Hello, World!". Note that this argument is a group of characters enclosed in double quotes (""). This is commonly referred to as a string of characters, orstring, for short. Another example of a string is"Jack and Jill went up a hill". The combination of a function and parentheses with the arguments is afunction call.

A function and its arguments are one type of statement that python has, so

print("Hello, World!")

is an example of a statement. Basically, you can think of a statement as a single line in a program.

That's probably more than enough terminology for now.

Expressions

[edit |edit source]

Here is another program:

print("2 + 2 is",2+2)print("3 * 4 is",3*4)print("100 - 1 is",100-1)print("(33 + 2) / 5 + 11.5 is",(33+2)/5+11.5)

And here is theoutput when the program is run:

2 + 2 is 43 * 4 is 12100 - 1 is 99(33 + 2) / 5 + 11.5 is 18.5

As you can see, Python can turn your thousand-dollar computer into a five-dollar calculator.

In this example, the print function is followed by two arguments, with each of the arguments separated by a comma. So with the first line of the program

print("2 + 2 is",2+2)

The first argument is the string"2 + 2 is" and the second argument is themathematical expression2 + 2, which is commonly referred to as anexpression.

What is important to note is that a string is printed as is (without the enclosing double quotes), but anexpression isevaluated, or converted to its actual value.

Python has seven basic operations for numbers:

OperationSymbolExample
Power (exponentiation)**5 ** 2 == 25
Multiplication*2 * 3 == 6
Division/14 / 3 == 4.666666666666667
Integer Division//14 // 3 == 4
Remainder (modulo)%14 % 3 == 2
Addition+1 + 2 == 3
Subtraction-4 - 3 == 1

Notice that there are two ways to do division, one that returns the repeating decimal, and the other that can get the remainder and the whole number. The order of operations is the same as in math:

  • parentheses()
  • exponents**
  • multiplication*, division/, integer division//, and remainder%
  • addition+ and subtraction-

So use parentheses to structure your formulas when needed.

Talking to humans (and other intelligent beings)

[edit |edit source]

Often in programming you are doing something complicated and may not in the future remember what you did. When this happens the program should probably be commented. Acomment is a note to you and other programmers explaining what is happening. For example:

# Not quite PI, but a credible simulationprint(22/7)

Which outputs

3.14285714286

Notice that the comment starts with a hash:#. Comments are used to communicate with others who read the program and your future self to make clear what is complicated.

Note that any text can follow a comment, and that when the program is run, the text after the# through to the end of that line is ignored. The# does not have to be at the beginning of a new line:

# Output PI on the screenprint(22/7)# Well, just a good approximation

Examples

[edit |edit source]

Each chapter (eventually) will contain examples of the programming features introduced in the chapter. You should at least look over them and see if you understand them. If you don't, you may want to type them in and see what happens. Mess around with them, change them and see what happens.

Denmark.py

print("Something's rotten in the state of Denmark.")print("                -- Shakespeare")

Output:

Something's rotten in the state of Denmark.                -- Shakespeare

School.py

# This is not quite true outside of USA# and is based on my dim memories of my younger yearsprint("Firstish Grade")print("1 + 1 =",1+1)print("2 + 4 =",2+4)print("5 - 2 =",5-2)print()print("Thirdish Grade")print("243 - 23 =",243-23)print("12 * 4 =",12*4)print("12 / 3 =",12/3)print("13 / 3 =",13//3,"R",13%3)print()print("Junior High")print("123.56 - 62.12 =",123.56-62.12)print("(4 + 3) * 2 =",(4+3)*2)print("4 + 3 * 2 =",4+3*2)print("3 ** 2 =",3**2)

Output:

Firstish Grade1 + 1 = 22 + 4 = 65 - 2 = 3Thirdish Grade243 - 23 = 22012 * 4 = 4812 / 3 = 413 / 3 = 4 R 1Junior High123.56 - 62.12 = 61.44(4 + 3) * 2 = 144 + 3 * 2 = 103 ** 2 = 9

Exercises

[edit |edit source]
  1. Write a program that prints your full name and your birthday as separate strings.
  2. Write a program that shows the use of all 7 math functions.
Solution

1. Write a program that prints your full name and your birthday as separate strings.

print("Ada Lovelace","born on","November 27, 1852")
print("Albert Einstein","born on","14 March 1879")
print(("John Smith"),("born on"),("14 March 1879"))


Solution

2. Write a program that shows the use of all 7 math functions.

print("5**5 = ",5**5)print("6*7 = ",6*7)print("56/8 = ",56/8)print("14//6 = ",14//6)print("14%6 = ",14%6)print("5+6 = ",5+6)print("9-0 = ",9-0)



Footnotes

[edit |edit source]
  1. Here is a great list of the famous "Hello, world!" program in many programming languages. Just so that you know how simple Python can be...
Learning Python 3 with the Linkbot
 ← IntroPrintable versionWho Goes There? → 


Who Goes There?

Lesson Information**To Be Added**Vocabulary:Necessary Materials and Resources:Computer Science Teachers Association Standards: 5.3.A.CD.4: Compare various forms of input and output.Common Core Math Content Standards:Common Core Math Practice Standards:Common Core English Language Arts Standards:


Input and Variables

[edit |edit source]

You are now ready to create a more complicated program. Type the following into your Python Editor:

print("Halt!")user_input=input("Who goes there?")print("You may pass,",user_input)

Run your program to ensure that it displays the following:

Halt!Who goes there?LinkbotYou may pass, Linkbot

Note: After running the code by pressing F5 on your keyboard, the Python Shell will only give the output:

Halt!Who goes there?

Enter your name in the Python Shell and press enter for the remainder of the output.

Your program will look different because of theinput() statement. Notice that, when running the program, you must type your name and press 'Enter'. The program responds by displaying text that includes your name. This is an example ofinput. The program reaches a certain point, and then waits for the user to type more data for the program to include.

The user's data that the program includes is stored as avariable. In the previous programuser_input is avariable. A variable is like a box that can store a piece of data. This program demonstrates the use of variables:

(Helpful blurb, Aaron, "This may not make a lot of sense right now, but refer back to it as you read the paragraph about variables.")

a=123.4b23='Barobo'first_name="Linkbot"b=432c=a+bprint("a + b is",c)print("first_name is",first_name)print("The Linkbot was created by ",b23)

And here is the output:

a + b is 555.4first_name is LinkbotThe Linkbot was created by Barobo

Variables store data, such as a number, a word, a phrase, or anything you choose to make it. The variables in the above program area,b23,first_name,b, andc. The two basic types of variables arenumbers andstrings.Numbers are simply a mathematical, numerical number, such as 7 or 89 or -3.14. In the above example,a,b, and evenc are number variables.c is considered a number variable because the result is a number.Strings are a sequence of letters, numbers and other characters. In this exampleb23 andfirst_name are variables that store strings.Barobo,Linkbot,a + b is,first_name is, andThe Linkbot was created by are the strings in this program. The characters are surrounded by" or'. The other types of symbols used in the program are variables representing numbers. Remember that variables are used to store a value, they do not use punctuation marks (" and'). If you want to use an actualvalue, youmust use those punctuation marks. See the next example.

value1==Pimvalue2=="Pim"

Both lines of code look the same at first glance, but they are different. In the first one, Python checks if the value stored in the variablevalue1 is the same as the value stored in thevariablePim. In the second one, Python checks if the string (the actual lettersP,i, andm) are the same as invalue2 (More explanation about strings and about the== come later).

Assignment

[edit |edit source]

In review, there are boxes called variables, and data goes into those boxes. Recall the previous examples. The computer sees a line such asfirst_name = "Linkbot", and it reads it as "put the stringLinkbot into the box, or variable,first_name". Then the computer sees the statementc = a + b, and it reads it as "put the sum ofa + b or123.4 + 432 which equals555.4 intoc". The right hand side of the statementa + b isevaluated, meaning that the two terms are equal, and the result is stored in the variable on the left hand sidec. In other words, one side of the statement isassigned to the other side. This process is calledassignment.

One single equal sign in coding makes the line of code a grammatical statement. For example,apple = banana reads "apple is banana." By writing the code in this way, apple is assigned to banana, and they are now considered equal by the program.You are basically telling the program that the two terms are equal, even if that is not in actuality the case.

Two equal signs together makes the line of code into a question that the computer will answer. For example,apple == banana reads "is apple equal to banana?" This answer would be "no," of course, unless you have previously and incorrectly assigned apple to banana.

(Helpful blurb, Aaron, "Be careful how many= you use because it can change your program entirely!")

Here is another example of variable usage:

a=1print(a)a=a+1print(a)a=a*2print(a)

Here is the output:

124

Even if the same variable appears on both sides of the equals sign (e.g., spam = spam), the computer still reads it as, "First find out the data to store, and then find out where the data goes."

Try another program:

number=float(input("Type in a number: "))integer=int(input("Type in an integer: "))text=input("Type in a string: ")print("number =",number)print("number is a",type(number))print("number * 2 =",number*2)print("integer =",integer)print("integer is a",type(integer))print("integer * 2 =",integer*2)print("text =",text)print("text is a",type(text))print("text * 2 =",text*2)

The output should be:

Type in a number:12.34Type in an integer:-3Type in a string:Hellonumber = 12.34number is a <class 'float'>number * 2 = 24.68integer = -3integer is a <class 'int'>integer * 2 = -6text = Hellotext is a <class 'str'>text * 2 = HelloHello

Notice thatnumber was created withfloat(input()) whiletext was created withinput().input() returns a string while the functionfloat returns a number from a string.int returns an integer, that is a number with no decimal point. When you want the user to type in a decimal usefloat(input()), if you want the user to type in an integer useint(input()), but if you want the user to type in a string useinput().

The second half of the program uses thetype() function which identifies a variable's type. Numbers are of typeint orfloat, which areshort forinteger andfloating point (mostly used for decimal numbers), respectively. Text strings are of typestr, short forstring. Integers and floats can be worked on by mathematical functions, strings cannot. Notice how when pythonmultiplies a number by an integer the expected thing happens. Howeverwhen a string is multiplied by an integer the result is that multiplecopies of the string are produced (i.e.,text * 2 = HelloHello).

Operations with strings do different things than operations with numbers. As well, some operations only work with numbers (both integers and floating point numbers) and will give an error if a string is used. Here are some interactive mode examplesto show that some more.

>>> print("This" + " " + "is" + " joined.")This is joined.>>> print("Ha, " * 5)Ha, Ha, Ha, Ha, Ha, >>> print("Ha, " * 5 + "ha!")Ha, Ha, Ha, Ha, Ha, ha!>>> print(3 - 1)2>>> print("3" - "1")Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for -: 'str' and 'str'>>>

Here is the list of some string operations:

OperationSymbolExample
Repetition*"i" * 5 == "iiiii"
Concatenation+"Hello, " + "World!" == "Hello, World!"

Moving a Linkbot's Motor

[edit |edit source]

Each Linkbot has two joints that it can move to do a variety of tasks. Sometimes, there might be wheels attached to the joints so that the Linkbot can drive around like a two-wheeled car. Or, the joints might be attached to a gripper, which would allow a Linkbot to pick up objects.

Each joint on a Linkbot has a number printed into the plastic. Looking at the Linkbot directly from a "top down" view, joint 1 is on the left side, joint 2 faces you, and joint 3 is on the right hand side. The Linkbot-L only has joints 1 and 2 and the Linkbot-I only has joints 1 and 3. Lets learn how to move a joint on a Linkbot!

moveMotor.py

# This program moves Joint 1 on a Linkbot by an amount# specified by the userimportbarobomyDongle=barobo.Dongle()myDongle.connect()robotID=input('Enter Linkbot ID: ')myLinkbot=myDongle.getLinkbot(robotID)degrees=float(input("Degrees to rotate Joint 1: "))myLinkbot.moveJoint(1,degrees)

When you run this example, you should notice joint 1 move. If you typed "90" for the input, you should see the joint rotate counter-clockwise 90 degrees. If you typed "-90", you should see the joint move 90 degrees in the clockwise direction. When you run this program, be careful about entering very large numbers or else you might have to wait a while for the joint to stop moving.

Examples

[edit |edit source]

Rate_times.py

# This program calculates rate and distance problemsprint("Input a rate and a distance")rate=float(input("rate: "))distance=float(input("Distance: "))print("Time:",(distance/rate))

Sample runs:

Input a rate and a distanceRate:5Distance:10Time: 2.0
Input a rate and a distanceRate:3.52Distance:45.6Time: 12.9545454545

Area.py

# This program calculates the perimeter and area of a rectangleprint("Calculate information about a rectangle")length=float(input("Length: "))width=float(input("Width: "))print("Area:",length*width)print("Perimeter:",2*length+2*width)

Sample runs:

Calculate information about a rectangleLength:4Width:3Area: 12.0Perimeter: 14.0
Calculate information about a rectangleLength:2.53Width:5.2Area: 13.156Perimeter: 15.46

Temperature.py

# This program converts Fahrenheit to Celsiusfahr_temp=float(input("Fahrenheit temperature: "))print("Celsius temperature:",(fahr_temp-32.0)*5.0/9.0)

Sample runs:

Fahrenheit temperature:32Celsius temperature: 0.0
Fahrenheit temperature:-40Celsius temperature: -40.0
Fahrenheit temperature:212Celsius temperature: 100.0
Fahrenheit temperature:98.6Celsius temperature: 37.0


Exercises

[edit |edit source]

Write a program that gets 2 string variables and 2 number variablesfrom the user, concatenates (joins them together with no spaces) anddisplays the strings, then multiplies the two numbers on a new line.

Solution

Write a program that gets 2 string variables and 2 number variablesfrom the user, concatenates (joins them together with no spaces) anddisplays the strings, then multiplies the two numbers on a new line.

string1=input('String 1: ')string2=input('String 2: ')float1=float(input('Number 1: '))float2=float(input('Number 2: '))print(string1+string2)print(float1*float2)


Write a program that gets 2 number variables from the user; each one an angle in degrees. After the program gets the two numbers, it makes the Linkbot rotate joint 1 by the amount in the first number, and then joint 3 (or 2, if you have a Linkbot-L) by the second number.

Solution
# This program moves Joints 1 and 3 on a Linkbot by an amount# specified by the userimportbarobomyDongle=barobo.Dongle()myDongle.connect()robotID=input('Enter Linkbot ID: ')myLinkbot=myDongle.getLinkbot(robotID)degrees1=float(input("Degrees to rotate Joint 1: "))degrees3=float(input("Degrees to rotate Joint 3: "))myLinkbot.moveJoint(1,degrees1)myLinkbot.moveJoint(3,degrees3)


Learning Python 3 with the Linkbot
 ← Hello, WorldPrintable versionCount to 10 → 


Count to 10

Lesson Information

**To Be Added**Vocabulary:Necessary Materials and Resources:Computer Science Teachers Association Standards: 5.2.CPP.5: Implement problem solutions using a programming language, including: looping behavior, conditional statements, logic, expressions, variables, and functions.Common Core Math Content Standards:Common Core Math Practice Standards:Common Core English Language Arts Standards:


While loops

[edit |edit source]

Ordinarily the computer starts with the first line and then goes down from there.Control structures change the order that statements are executed or decide if a certain statement will be run. Here's the source for a program that uses the while control structure:

a=0# FIRST, set the initial value of the variable a to 0(zero).whilea<10:# While the value of the variable a is less than 10 do the following:a=a+1# Increase the value of the variable a by 1, as in: a = a + 1!print(a)# Print to screen what the present value of the variable a is.# REPEAT! until the value of the variable a is equal to 9!? See note.# NOTE:# The value of the variable a will increase by 1# with each repeat, or loop of the 'while statement BLOCK'.# e.g. a = 1 then a = 2 then a = 3 etc. until a = 9 then...# the code will finish adding 1 to a (now a = 10), printing the# result, and then exiting the 'while statement BLOCK'.#              --# While a < 10: |#     a = a + 1 |<--[ The while statement BLOCK ]#     print (a) |#              --

And here is the extremely exciting output:

12345678910

(And you thought it couldn't get any worse after turning your computer into a five-dollar calculator?)

So what does the program do? First it sees the linea = 0 and setsa to zero. Then it seeswhile a < 10: and so the computer checks to see ifa < 10. The first time the computer sees this statement,a is zero, so it is less than 10. In other words, as long asa is less than ten, the computer will run the tabbed in statements. This eventually makesa equal to ten (by adding one toa again and again) and thewhile a < 10 is not true any longer. Reaching that point, the program will stop running the indented lines.

Always remember to put a colon ":" at the end of thewhile statement line!

Here is another example of the use ofwhile:

a=1s=0print('Enter Numbers to add to the sum.')print('Enter 0 to quit.')whilea!=0:print('Current Sum:',s)a=float(input('Number? '))s=s+aprint('Total Sum =',s)
Enter Numbers to add to the sum.Enter 0 to quit.Current Sum: 0Number?200Current Sum: 200.0Number?-15.25Current Sum: 184.75Number?-151.85Current Sum: 32.9Number?10.00Current Sum: 42.9Number?0Total Sum = 42.9

Notice howprint 'Total Sum =', s is only run at the end. Thewhile statement only affects the lines that are indented with whitespace. The!= means does not equal sowhile a != 0: means as long asa is not zero run the tabbed statements that follow.

Note thata is a floating point number, and not all floating point numbers can be accurately represented, so using!= on them can sometimes not work. Try typing in 1.1 in interactive mode.

Infinite loops or Never Ending Loop

[edit |edit source]

Now that we have while loops, it is possible to have programs that run forever. An easy way to do this is to write a program like this:

while1==1:print("Help, I'm stuck in a loop.")

The "==" operator is used to test equality of the expressions on the two sides of the operator, just as "<" was used for "less than" before (you will get a complete list of all comparison operators in the next chapter).

This program will outputHelp, I'm stuck in a loop. until the heat death of the universe or you stop it, because 1 will forever be equal to 1. The way to stop it is to hit the Control (orCtrl) button andC (the letter) at the same time. This will kill the program. (Note: sometimes you will have to hit enter after the Control-C.) On some systems, nothing will stop it, short of killing the process--so avoid!

Examples

[edit |edit source]

Fibonacci sequence

[edit |edit source]

Fibonacci-method1.py

# This program calculates the Fibonacci sequencea=0b=1count=0max_count=20whilecount<max_count:count=count+1print(a,end=" ")# Notice the magic end=" " in the print function arguments# that keeps it from creating a new line.old_a=a# we need to keep track of a since we change it.a=bb=old_a+bprint()# gets a new (empty) line.

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Note that the output is on a single line because of the extra argumentend=" " in theprint arguments.

Fibonacci-method2.py

# Simplified and faster method to calculate the Fibonacci sequencea=0b=1count=0max_count=10whilecount<max_count:count=count+1print(a,b,end=" ")# Notice the magic end=" "a=a+bb=a+bprint()# gets a new (empty) line.

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Enter password

[edit |edit source]

Password.py

# Waits until a password has been entered. Use Control-C to break out without# the password#Note that this must not be the password so that the# while loop runs at least once.password=str()# note that != means not equalwhilepassword!="unicorn":password=input("Password: ")print("Welcome in")


Sample run:

Password:auoPassword:y22Password:passwordPassword:open sesamePassword:unicornWelcome in

A Linkbot Musical Example

[edit |edit source]

The Linkbot has a small buzzer on board that can play one note at a time. We can control the frequency of the buzzer on the Linkbot to generate different tones. The equationpianokeyFrequency=2((key49)/12)440{\displaystyle \mathrm {pianokeyFrequency} =2^{((\mathrm {key} -49)/12)}*440} shows how to calculate the frequency of a key on a piano. There are 88 keys on a real piano, but lets see if we can make our robot play from the 34th key all the way up to the 73rd key.

In Python, to calculate the "power" of a number, we can use the** operator. For instance,23{\displaystyle 2^{3}} can be calculated in Python using2**3.

importbarobodongle=barobo.Dongle()dongle.connect()robotID=input('Enter Linkbot ID: ')robot=dongle.getLinkbot(robotID)importtime# imports the Python "time" module because we want to use "time.sleep()" later.key=34# Set key=34 which is the 34th key on a piano keyboard.whilekey<74:# While the key number is less than 74.robot.setBuzzerFrequency(2**((key-49)/12.0)*440)# Play the frequency to the corresponding note.time.sleep(.25)# Play the note for 0.25 seconds.robot.setBuzzerFrequency(0)# Turn off the notekey=key+1# Increase the key number by 1. This is the end of the loop. At this point,# Python will check to see if the condition in the "while" statement,# "key < 74", is true. If it is still true, Python will go back to the# beginning of the loop. If not, the program exits the loop.

Exercises

[edit |edit source]

Write a program that asks the user for a Login Name and password. Then when they type "lock", they need to type in their name and password to unlock the program.

Solution

Write a program that asks the user for a Login Name and password. Then when they type "lock", they need to type in their name and password to unlock the program.

name=input("What is your UserName: ")password=input("What is your Password: ")print("To lock your computer type lock.")command=Noneinput1=Noneinput2=Nonewhilecommand!="lock":command=input("What is your command: ")whileinput1!=name:input1=input("What is your username: ")whileinput2!=password:input2=input("What is your password: ")print("Welcome back to your system!")

If you would like the program to run continuously, just add awhile 1 == 1: loop around the whole thing.You will have to indent the rest of the program when you add this at the top of the code, but don't worry, you don't have to do it manually for each line! Just highlight everything you want to indent and click on "Indent" under "Format" in the top bar of the python window.

Another way of doing this could be:

name=input('Set name: ')password=input('Set password: ')while1==1:nameguess=""passwordguess=""key=""while(nameguess!=name)or(passwordguess!=password):nameguess=input('Name? ')passwordguess=input('Password? ')print("Welcome,",name,". Type lock to lock.")whilekey!="lock":key=input("")

Notice theor in while(nameguess != name) or (passwordguess != password), which we haven't yet introduced. You can probably figure out how it works.


Modify the Linkbot Buzzer program to play every third key on the piano from the 34th key up to the 74th key.

Solution
importbarobodongle=barobo.Dongle()dongle.connect()robotID=input('Enter Linkbot ID: ')robot=dongle.getLinkbot(robotID)importtime# imports the Python "time" module because we want to use "time.sleep()" later.key=34# Set key=34 which is the 34th key on a piano keyboard.whilekey<74:# While the key number is less than 74.robot.setBuzzerFrequency(2**((key-49)/12.0)*440)# Play the frequency to the corresponding note.time.sleep(.25)# Play the note for 0.25 seconds.robot.setBuzzerFrequency(0)# Turn off the notekey=key+3# Increase the key number by 3. This is the end of the loop. At this point,# Python will check to see if the condition in the "while" statement,# "key < 74", is true. If it is still true, Python will go back to the# beginning of the loop. If not, the program exits the loop.


Learning Python 3 with the Linkbot
 ← Who Goes There?Printable versionDecisions → 


Decisions

If statement

[edit |edit source]

As always I believe I should start each chapter with a warm-up typing exercise, so here is a short program to compute the absolute value of an integer:

n=int(input("Number? "))ifn<0:print("The absolute value of",n,"is",-n)else:print("The absolute value of",n,"is",n)

Here is the output from the two times that I ran this program:

Number?-34The absolute value of -34 is 34
Number?1The absolute value of 1 is 1

So what does the computer do when it sees this piece of code? First it prompts the user for a number with the statement "n = int(input("Number? "))". Next it reads the line "if n < 0:". Ifn is less than zero Python runs the line "print("The absolute value of", n, "is", -n)". Otherwise it runs the line "print("The absolute value of", n, "is", n)".

More formally Python looks at whether theexpressionn < 0 is true or false. Anif statement is followed by an indentedblock of statements that are run when the expression is true. Optionally after theif statement is anelse statement and another indentedblock of statements. This second block of statements is run if the expression is false.

There are a number of different tests that an expression can have. Here is a table of all of them:

operatorfunction
<less than
<=less than or equal to
>greater than
>=greater than or equal to
==equal
!=not equal

Another feature of the if command is the elif statement. It stands for else if and means if the original if statement is false but the elif part is true, then do theelif part. And if neither theif orelif expressions are true, then do what's in theelse block. Here's an example:

a=0whilea<10:a=a+1ifa>5:print(a,">",5)elifa<=3:print(a,"<=",3)else:print("Neither test was true")

and the output:

1 <= 32 <= 33 <= 3Neither test was trueNeither test was true6 > 57 > 58 > 59 > 510 > 5

Notice how theelif a <= 3 is only tested when theif statement fails to be true. There can be more than oneelif expression, allowing multiple tests to be done in a singleif statement.

Moving a Linkbot's Motors

[edit |edit source]

In the previous chapter,Who Goes There?, we saw that you can move a linkbot's motor with themoveJoint() function.It is typically used like:

myLinkbot.moveJoint(1,180)

where the first argument is the motor you want to move and the second argument is the angle in degrees you want to move it. The above code will move motor "1" in the positive direction by 180 degrees.

What if you want to move more than one motor at a time? The linkbot also has amove() function that does just that. It looks something like this:

myLinkbot.move(90,180,270)

Themove() function expects three numbers inside the parentheses. The first number is the angle to move motor 1, the second number is the angle to move motor 2, and the third number is the angle to move motor 3. If your Linkbot only has two motors, the valuefor the face that does not have a motor is ignored. For example, if I have a Linkbot-I and I ran the above sample code, the "180" is ignored because motor 2 is not a movable motor. Instead, the Linkbot will move motor 1 forward 90 degrees and motor 3 forward 270 degrees.

When themove() function is executed, the Linkbot will move any/all of its motors simultaneously.

command_linkbot.py

[edit |edit source]

In this example, we'd like to create a program that we can use to move our Linkbot around. This demo will use the pythonbreak command. In the previous chapter, we saw that Python can get stuck in "infinite loops". Thebreak command can be used to exit loops even if the loop condition is still true.

Lets start with just moving the Linkbot forward and backward first.To run this demo, you'll need a Linkbot-I and two wheels. A caster is also recommended but optional.

importbarobodongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('abcd')# Replace abcd with your Linkbot's serial IDwhileTrue:# This is an infinite loop. Get out by using the "break" statementcommand=input('Please enter a robot command or "quit" to exit the program: ')ifcommand=='forward':# Rotate the wheels 180 degrees to move the robot forwardmyLinkbot.move(180,0,-180)# Motor 3 has to spin in the negative direction to move the robot forwardelifcommand=='backward':myLinkbot.move(-180,0,180)elifcommand=='quit':breakelse:print('I\'m sorry. I don\'t understand that command.')print('Goodbye!')

A Note on Strings

You might have noticed that towards the end of the program, there is a line that readsprint('I\'m sorry. I don\'t understand that command.') with funny backslashes in the code. When you run the program though, it doesn't print those backslashes. These backslashes actually serve an important purpose.

When Python encounters either a single quote ' or double quote " , it knows that what follows will be a string that is terminated by the same type of quotation mark that started it. But, what if we want to include some quotation marks as part of the string? Consider the following piece of code:

mystring="Hello there. My dog says "woof!" when he's bored."

When Python sees the first Quotation mark at"Hello th..., it says "Ok, this is going to be a string and as soon as I see another quotation mark, that will be the end of the string". Soon, Python sees another quotation mark at...says "woof! and thinks "I've found the end of the string!", but this is not the end of our string! We wanted Python to go all the way to the end at...bored." . How do we tell Python that the quotation marks around"woof!" are special, and that our string doesn't actually end there?

The answer is backslashes. If there is a backslash preceding a quotation mark, that is a special indicator to Python to include that quotation mark as part of the string, rather than terminating the string. Therefore, the fixed code should be:

mystring="Hello there. My dog says\"woof!\" when he's bored."

In this example, the single quote inhe's is automatically included as part of the string because the string started with a double-quotation mark, and thus Python is looking for a double-quotation mark to terminate the string.

Sample runs

Sample runs:

Please enter a robot command or 'quit' to exit the program:forwardPlease enter a robot command or 'quit' to exit the program:backwardPlease enter a robot command or 'quit' to exit the program:aoeuI'm sorry. I don't understand that command.Please enter a robot command or 'quit' to exit the program:quitGoodbye!


Examples

[edit |edit source]

equality.py

# This Program Demonstrates the use of the == operator# using numbersprint(5==6)# Using variablesx=5y=8print(x==y)

And the output

FalseFalse

high_low.py

# Plays the guessing game higher or lower# This should actually be something that is semi random like the# last digits of the time or something else, but that will have to# wait till a later chapter.  (Extra Credit, modify it to be random# after the Modules chapter)number=7guess=-1print("Guess the number!")whileguess!=number:guess=int(input("Is it... "))ifguess==number:print("Hooray! You guessed it right!")elifguess<number:print("It's bigger...")elifguess>number:print("It's not so big.")

Sample run:

Guess the number!Is it...2It's bigger...Is it...5It's bigger...Is it...10It's not so big.Is it...7Hooray! You guessed it right!

even.py

# Asks for a number.# Prints if it is even or oddnumber=float(input("Tell me a number: "))ifnumber%2==0:print(int(number),"is even.")elifnumber%2==1:print(int(number),"is odd.")else:print(number,"is very strange.")

Sample runs:

Tell me a number:33 is odd.
Tell me a number:22 is even.
Tell me a number:3.48953.4895 is very strange.

average1.py

# keeps asking for numbers until 0 is entered.# Prints the average value.count=0sum=0.0number=1# set to something that will not exit the while loop immediately.print("Enter 0 to exit the loop")whilenumber!=0:number=float(input("Enter a number: "))ifnumber!=0:count=count+1sum=sum+numberifnumber==0:print("The average was:",sum/count)
Sample runs

Sample runs:

Enter 0 to exit the loopEnter a number:3Enter a number:5Enter a number:0The average was: 4.0
Enter 0 to exit the loopEnter a number:1Enter a number:4Enter a number:3Enter a number:0The average was: 2.66666666667

average2.py

# keeps asking for numbers until count numbers have been entered.# Prints the average value.#Notice that we use an integer to keep track of how many numbers,# but floating point numbers for the input of each numbersum=0.0print("This program will take several numbers then average them")count=int(input("How many numbers would you like to average: "))current_count=0whilecurrent_count<count:current_count=current_count+1print("Number",current_count)number=float(input("Enter a number: "))sum=sum+numberprint("The average was:",sum/count)

Sample runs:

This program will take several numbers then average themHow many numbers would you like to average:2Number 1Enter a number:3Number 2Enter a number:5The average was: 4.0
This program will take several numbers then average themHow many numbers would you like to average:3Number 1Enter a number:1Number 2Enter a number:4Number 3Enter a number:3The average was: 2.66666666667

Exercises

[edit |edit source]

Write a program that asks the user their name, if they enter your namesay "That is a nice name", if they enter "John Cleese" or "MichaelPalin", tell them how you feel about them ;), otherwise tell them "Youhave a nice name."

Solution
name=input('Your name: ')ifname=='Ada':print('That is a nice name.')elifname=='John Cleese':print('... some funny text.')elifname=='Michael Palin':print('... some funny text.')else:print('You have a nice name.')


Modify the higher or lower program from this section to keep track of how many times the user has entered the wrong number. If it is more than 3 times, print "That must have been complicated." at the end, otherwise print "Good job!"

Solution
number=7guess=-1count=0print("Guess the number!")whileguess!=number:guess=int(input("Is it... "))count=count+1ifguess==number:print("Hooray! You guessed it right!")elifguess<number:print("It's bigger...")elifguess>number:print("It's not so big.")ifcount>3:print("That must have been complicated.")else:print("Good job!")


Write a program that asks for two numbers. If the sum of the numbers is greater than 100, print "That is a big number."

Solution
number1=float(input('1st number: '))number2=float(input('2nd number: '))ifnumber1+number2>100:print('That is a big number.')


Modify the Linkbot program presented earlier to include the commands "turnright", "turnleft", and "beep". Make the "turnright" command turn the robot to the right, "turnleft" turn the robot to the left, and "beep" beep the robot buzzer for 1 second.

Solution
importbaroboimporttime# So we can use time.sleep() laterdongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('abcd')# Replace abcd with your Linkbot's serial IDwhileTrue:# This is an infinite loop. Get out by using the "break" statementcommand=input('Please enter a robot command or "quit" to exit the program: ')ifcommand=='forward':# Rotate the wheels 180 degrees to move the robot forwardmyLinkbot.move(180,0,-180)# Motor 3 has to spin in the negative direction to move the robot forwardelifcommand=='backward':myLinkbot.move(-180,0,180)elifcommand=='turnright':myLinkbot.move(180,0,180)elifcommand=='turnleft':myLinkbot.move(-180,0,-180)elifcommand=='beep':myLinkbot.setBuzzerFrequency(440)time.sleep(1)myLinkbot.setBuzzerFrequency(0)elifcommand=='quit':breakelse:print('I\'m sorry. I don\'t understand that command.')print('Goodbye!')


Learning Python 3 with the Linkbot
 ← Count to 10Printable versionLinkbot Multitasking → 


Linkbot Multitasking

"Non-blocking" Linkbot Functions

[edit |edit source]

Lets take an inventory of all of the functions that we've used so far to control various aspects of the Linkbot.

Function NameFunction Description
setLEDColor(r, g, b)Changes the LED color based on red, green, and blue intensities.
setBuzzerFrequency(Hz)Makes the Linkbot buzzer play a frequency in Hertz.
moveJoint(jointNum, degrees)Makes a single motor move.
move(degrees, degrees, degrees)Makes multiple motors move simultaneously

Using these functions, we can move our robot around, change the robot's LED color, and make the robot beep or play simple melodies. However, using only these functions, it is not possible to make a robot play a tune and change its LED colors while the robot is moving. For example, lets say we want to make our robot beep 2 times _while_ our robot is moving. We can try something like this:Template:Message box

myLinkbot.setBuzzerFrequency(440)# 1time.sleep(0.25)# 2myLinkbot.setBuzzerFrequency(0)# 3time.sleep(0.25)# 4myLinkbot.setBuzzerFrequency(440)time.sleep(0.25)myLinkbot.setBuzzerFrequency(0)time.sleep(0.25)myLinkbot.move(180,0,-180)# 5

Lets reason our way through each major point of this program.

  1. First, we turn on the buzzer on the Linkbot. It starts buzzing
  2. Pause the program for 0.25 seconds
  3. Turn off the Linkbot's buzzer.
  4. Pause the program for another 0.25 seconds. The end result of steps 1-4 is that the Linkbot buzzes its buzzer for 0.25 seconds. The next four lines do the same exact thing.
  5. At this point, the Linkbot has buzzed twice, and now themove() function makes the Linkbot roll forward.

This isalmost what we want to do, except we want the robot to beep twicewhile the robot is moving; not before it starts moving. Lets try again:

myLinkbot.move(180,0,-180)# 1myLinkbot.setBuzzerFrequency(440)# 2time.sleep(0.25)myLinkbot.setBuzzerFrequency(0)time.sleep(0.25)myLinkbot.setBuzzerFrequency(440)time.sleep(0.25)myLinkbot.setBuzzerFrequency(0)time.sleep(0.25)

This program is almost exactly the same as the program before except we relocated themove() function to the beginning of the program. Will this program make the robot beep twice as the robot is moving?

  1. First, we call themove() function which moves the robot's motors. The robot begins moving. However, the program stays at item 1 until themove() function is completed. After the robot finishes moving, the program continues.
  2. Here, the robot turns the buzzer on similar to the previous example. UsingsetBuzzerFrequency() andtime.sleep(), it makes the buzzer beep twice.

ThemoveNB() Function

[edit |edit source]

As we can see, we have failed yet again to make the robot beep twice while moving. In order to make the robot do these things simultaneously, we must use a similar but new type of function: Non-blocking functions. Lets take a look at an example:

myLinkbot.moveNB(180,0,-180)# 1myLinkbot.setBuzzerFrequency(440)# 2time.sleep(0.25)myLinkbot.setBuzzerFrequency(0)time.sleep(0.25)myLinkbot.setBuzzerFrequency(440)time.sleep(0.25)myLinkbot.setBuzzerFrequency(0)time.sleep(0.25)
  1. Here, instead of using themove() function, we use themoveNB() function.

The "NB" in the function name stands for "non-blocking". Both functions move the motors on the Linkbot, but there is one important difference: The NB version of the function "returns" immediately. What this means is Python continues on to the next line of code immediately without waiting for the movement to finish first. In other words, themoveNB() function does not "block" Python from continuing on immediately after the function is called.

  1. Now, the Linkbot begins playing its buzzer while the Linkbot is still moving. We've accomplished our task! This program will move the robot and beep twice while the robot is moving.

ThemoveWait() Function

[edit |edit source]

Now lets try one more example. Lets say we want to make the robot move its wheels 180 degrees to roll forward while beeping twice, and then change the LED color to greenafter the movement is done. To accomplish this, we introduce themoveWait() function. Lets take a look and see how it works:

myLinkbot.moveNB(180,0,-180)# 1myLinkbot.setBuzzerFrequency(440)# 2time.sleep(0.25)myLinkbot.setBuzzerFrequency(0)time.sleep(0.25)myLinkbot.setBuzzerFrequency(440)time.sleep(0.25)myLinkbot.setBuzzerFrequency(0)time.sleep(0.25)myLinkbot.moveWait()# 3myLinkbot.setLEDColor(0,255,0)# 4
  1. As before, this line tells the robot to begin moving motors 1 and 3. Since we used the "NB" version of the function, Python continues directly on to the next line of code even though the robot is still moving.
  2. The next several lines of code beep the robot twice, similar to before.
  3. Here, we call a function calledmoveWait(). This function blocks until all motor movements on the robot are finished. In effect, Python will wait at # 3 until the motors are done moving.
  4. Here, we set the LED color to green.

If we had omittedmoveWait() at # 3, the LED color would've been set whether the motors were still moving or not. By using themoveWait() function, we force Python to wait for the motors to stop moving before setting the LED color.

Other Non-Blocking Functions

[edit |edit source]

Almost all Linkbot movement commands have a non-blocking version with the "NB" suffix. The ones that do not have a non-blocking version are the ones that move a Linkbot's motor continuously forever. We haven't explored any of them yet, but they are out there. These functions do not have non-blocking versions because they would block forever.

All of the functions that begin with the prefix "set", such assetBuzzerFrequency() andsetLEDColor(), can be considered non-blocking because of how fast the buzzer and LED colors are set. For instance, if you run the following snippet of code:

myLinkbot.setBuzzerFrequency(440)myLinkbot.setLEDColor(0,255,0)

The Linkbot would appear to start buzzing and change the LED color to green simultaneously. Technically, the robot is actually doing one before the other, but the two things happen so fast (typically within 5 milliseconds of each other) that it is practically simultaneous.

Learning Python 3 with the Linkbot
 ← DecisionsPrintable versionDebugging → 


Debugging

What is debugging?

[edit |edit source]
"As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs." —Maurice Wilkes discovers debugging, 1949

By now if you have been messing around with the programs you have probably found that sometimes the program does something you didn't want it to do. This is fairly common. Debugging is the process of figuring out what the computer is doing and then getting it to do what you want it to do. This can be tricky. It surprisingly common to spend weeks tracking down and fixing a bug that was caused by someone putting anx where ay should have been.

This chapter will be more abstract than previous chapters.

What should the program do?

[edit |edit source]

The first thing to do (this sounds obvious) is to figure out what theprogram should be doing if it is running correctly. Come up with sometest cases and see what happens.

For instance, lets try to write a program that rolls a Linkbot-I with two wheels forward one rotation while making the LED green, and then rolls the Linkbot backward with the LED red. Here's a first try at this program:

importbarobodongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('ABCD')# Change 'ABCD' to your Linkbot's Serial IDmyLinkbot.moveNB(360,0,-360)# Roll ForwardmyLinkbot.setLEDColor(0,255,0)# Set LED to greenmyLinkbot.moveNB(-360,0,360)# Roll BackwardmyLinkbot.setLEDColor(255,0,0)# Set the LED color to red

At first glance, the above program may appear to be correct. When you actually try it though, you'll see that the robot never turns its LED green, and it never moves forward. It immediately changes its LED red and moves backward. What happened to the two lines that are supposed to make the robot roll forward and turn the LED green?

One easy and powerful method of debugging problems like this is to use theprint() function to track the progress of the program while it's running. Lets try adding some print statements to our original program and see if we can track down the problem:

importbarobodongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('ABCD')# Change 'ABCD' to your Linkbot's Serial IDprint("Moving forward...")myLinkbot.moveNB(360,0,-360)# Roll Forwardprint("Done. Setting LED to green...")myLinkbot.setLEDColor(0,255,0)# Set LED to greenprint("Done. Moving backward...")myLinkbot.moveNB(-360,0,360)# Roll Backwardprint("Done. Setting LED to red...")myLinkbot.setLEDColor(255,0,0)# Set the LED color to redprint("Done.")

When you run this program, pay attention not only to what it's printing, but also how and when it's printing. When you run the program, the output you should get is:

Moving forward...Done. Setting LED to green...Done. Moving backward...Done. Setting LED to red...Done.

However, you'll notice that all of those statements printimmediately; there is no delay between the commands that tell the robot to move forward and the commands that tell it to move backward. That should immediately give us an indication for what is wrong: the program should wait until the robot is finished moving forward before moving backward and turning red. You'll notice that we used non-blocking movement functions in our program so that we can move and change the LED color at the same time. However, we also know that Python doesn't stop and wait at non-blocking and "set" functions. From the previous chapter, we also have a function that makes Python wait until a non-blocking motion is completed calledmoveWait().Lets try fixing our broken program:

importbarobodongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('ABCD')# Change 'ABCD' to your Linkbot's Serial IDmyLinkbot.moveNB(360,0,-360)# Roll ForwardmyLinkbot.setLEDColor(0,255,0)# Set LED to greenmyLinkbot.moveWait()# Wait until the robot is finished rolling forwardmyLinkbot.moveNB(-360,0,360)# Roll BackwardmyLinkbot.setLEDColor(255,0,0)# Set the LED color to red

AmoveWait() statement has been added in-between the two steps. This forces Python to wait until the robot is done moving forward before telling it to move backward and set the LED color to red.

Without themoveWait() statement, Python will go through all of those statementsso fast that the robot rolling forward and green LED won't be noticeable to human eyes and ears. Only the last commands, rolling backward and the red LED, "stay" on the robot and are observable, making it seem like Python was skipping the moving forward and green LED altogether.

General Tips

[edit |edit source]
  1. This may sound obvious, but the first thing to ensure is that you know what the program is supposed to do.
  2. Check to make sure the program flow is correct by usingprint() statements.
  3. Check to make sure variable values are correct usingprint() statements.
  4. For complex programs that might use loops and variables, try "stepping" through the program, line by line, keeping track of variable values and program outputs using pen and paper.
  5. If you have a long program that does many calculations on a variable and the value of the variable is wrong at the end of the program, try using the "binary-search" method to find the bug: Use aprint() statement to check the value of the variable in the middle of the program. If the value is correct, you know the bug is somewhere in the second half of your program. Put anotherprint() statement in the middle of the second half of the program and check its value. Repeat until you've found the incorrect line of code that is incorrectly setting the variable's value. This technique is highly useful for findingwhere a bug might be occurring, and it is useful for many types of bugs.

Template:Message box

Learning Python 3 with the Linkbot
 ← DecisionsPrintable versionDefining Functions → 


Defining Functions

Creating Functions

[edit |edit source]

To start off this chapter I am going to give you an example of what you could do but shouldn't (so don't type it in):

a=23b=-23ifa<0:a=-aifb<0:b=-bifa==b:print("The absolute values of",a,"and",b,"are equal.")else:print("The absolute values of",a,"and",b,"are different.")

with the output being:

The absolute values of 23 and 23 are equal.

The program seems a little repetitive. Programmers hate to repeat things -- that's what computers are for, after all! (Note also that finding the absolute value changed the value of the variable, which is why it is printing out 23, and not -23 in the output.) Fortunately Python allows you to create functions to remove duplication. Here is the rewritten example:

a=23b=-23defabsolute_value(n):ifn<0:n=-nreturnnifabsolute_value(a)==absolute_value(b):print("The absolute values of",a,"and",b,"are equal.")else:print("The absolute values of",a,"and",b,"are different.")

with the output being:

The absolute values of 23 and -23 are equal.

The key feature of this program is thedef statement.def(short for define) starts a function definition.def isfollowed by the name of the functionabsolute_value. Next comes a '(' followed by the parametern (n is passed from the program into the function when the function is called). The statements after the ':' are executed when the function is used. The statements continue until either the indented statements end or areturn is encountered. Thereturn statement returns a value back to the place where the function was called. We already have encountered a function in our very first program, theprint function. Now we can make new functions.

Notice how the values ofa andb are not changed.Functions can be used to repeat tasks that don't returnvalues. Here are some examples:

defhello():print("Hello")defarea(width,height):returnwidth*heightdefprint_welcome(name):print("Welcome",name)hello()hello()print_welcome("Fred")w=4h=5print("width =",w," height =",h," area =",area(w,h))

with output being:

HelloHelloWelcome Fredwidth = 4  height = 5  area = 20

That example shows some more stuff that you can do withfunctions. Notice that you can use no arguments or two or more.Notice also when a function doesn't need to send back a value, areturn is optional.

Variables in functions

[edit |edit source]

When eliminating repeated code, you often have variables in the repeated code. In Python, these are dealt with in a special way. So far all variables we have seen are global variables. Functions have a special type of variable called local variables. These variables only exist while the function is running. When a local variable has the same name as another variable (such as a global variable), the local variable hides the other. Sound confusing? Well, these next examples (which are a bit contrived) should help clear things up.

a=4defprint_func():a=17print("in print_func a = ",a)print_func()print("a = ",a)

When run, we will receive an output of:

in print_func a = 17a = 4

Variable assignments inside a function do not override global variables, they exist only inside the function. Even thougha was assigned a new value inside the function, this newly assigned value was only relevant toprint_func, when the function finishes running, and thea's values is printed again, we see the originally assigned values.

Here is another more complex example.

a_var=10b_var=15e_var=25defa_func(a_var):print("in a_func a_var = ",a_var)b_var=100+a_vard_var=2*a_varprint("in a_func b_var = ",b_var)print("in a_func d_var = ",d_var)print("in a_func e_var = ",e_var)returnb_var+10c_var=a_func(b_var)print("a_var = ",a_var)print("b_var = ",b_var)print("c_var = ",c_var)print("d_var = ",d_var)
Output
 in a_func a_var =  15 in a_func b_var =  115 in a_func d_var =  30 in a_func e_var =  25 a_var =  10 b_var =  15 c_var =  125 d_var =   Traceback (most recent call last):  File "C:\def2.py", line 19, in <module>    print("d_var = ", d_var)NameError: name 'd_var' is not defined

In this example the variablesa_var,b_var, andd_var are all local variables when they are inside the functiona_func. After the statementreturn b_var + 10 is run, they all cease to exist. The variablea_var is automatically a local variable since it is a parameter name. The variablesb_var andd_var are local variables since they appear on the left of an equals sign in the function in the statementsb_var = 100 + a_var andd_var = 2 * a_var .

Inside of the functiona_var has no value assigned to it. When the function is called withc_var = a_func(b_var), 15 is assigned toa_var since at that point in timeb_var is 15, making the call to the functiona_func(15). This ends up settinga_var to 15 when it is inside ofa_func.

As you can see, once the function finishes running, the local variablesa_var andb_var that had hidden the global variables of the same name are gone. Then the statementprint("a_var = ", a_var) prints the value10 rather than the value15 since the local variable that hid the global variable is gone.

Another thing to notice is theNameError that happens at the end. This appears since the variabled_var no longer exists sincea_func finished. All the local variables are deleted when the function exits. If you want to get something from a function, then you will have to usereturn something.

One last thing to notice is that the value ofe_var remains unchanged insidea_func since it is not a parameter and it never appears on the left of an equals sign inside of the functiona_func. When a global variable is accessed inside a function it is the global variable from the outside.

Functions allow local variables that exist only inside the function and can hide other variables that are outside the function.

Linkbots in Functions : Making the Linkbot Move a Certain Distance

[edit |edit source]

We've seen now that we can pass numbers and variables to a function in the function parameters. It turns out that you can pass just about anything into a function, including Linkbot objects.In the Chapter "Decisions", we wrote some code that could move a two-wheels linkbot around. In the code, we specified the angle to rotate the wheels, but it would be much cooler if we could tell the Linkbot to move some distance on the ground. When you're writing new functions, it's common to prototype how the function might be used before actually writing it, so lets try that now.We want our function to be used something like this:

driveDistance(myLinkbot,10)# Drive a wheeled Linkbot 10 inches forward

Now that we're satisfied with how we want touse our function, now we have to worry about how to actually write it so that it does what we want it to do. First, let us catalog what we know and what we have. So far we know about 2 functions that we can use to move motors on the Linkbot:moveJoint() andmove(). Of the two, we have found thatmove() is probably better for driving two-wheeled Linkbots. However, themove() function takes angles as arguments. That leaves the question: How do we turn a distance into an angle?

It turns out there is an equation that you can use to figure out how many degrees a wheel has to turn to travel a certain distance. The equation is:degrees=3602πrdistance{\displaystyle \mathrm {degrees} ={\frac {360}{2\pi r}}*\mathrm {distance} }

If you would like to see a derivation where that equation comes from, click on the "derivation" link below.

Derivation

To solve this question, we can consider how wheels roll on a surface. Let us consider a wheel rolling on a surface that doesn't slip on the surface because it will make our calculations easier. Let us consider the "circumference" of a wheel. If you took a string and wrapped it all the way around a circle, the length of that string is the "circumference".The circumference of a circle with radius "r" is

circumference=2πr{\displaystyle \mathrm {circumference} =2\pi r}

The following figure illustrates a blue wheel with a green string wrapped around it. As the wheel rolls, the string unrolls off of the wheel.

The relationship between the distance traveled by a wheel and its circumference.

As we can see from the figure, if the wheel rolls one full revolution, it travels one circumference of distance. Knowing that one revolution is 360 degrees, we can write a ratio:

3602πr=degreesdistance{\displaystyle {\frac {360}{2\pi r}}={\frac {\mathrm {degrees} }{\mathrm {distance} }}}

So if we want to travel a distance "distance", we can do

degrees=3602πrdistance{\displaystyle \mathrm {degrees} ={\frac {360}{2\pi r}}*\mathrm {distance} }

Using this equation, if we know the wheel radius and we know what distance we want to travel, we can calculate the degrees to turn the wheel! Now we can write our function.

Template:Message box


Now, we can include that equation in our function. This allows us to re-use the function for any distance and we don't have to type in the equation over and over again.

importbaroboimportmath# So that we can use math.pidongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('abcd')# Change abcd to your Linkbot's serial IDdefdriveDistance(linkbot,distance):r=3.5/2# If you have a wheel that's not 3.5 inches in diameter, change "3.5" to the diameter of your wheeldegrees=(360)/(2*math.pi*r)*distancelinkbot.move(degrees,0,-degrees)driveDistance(myLinkbot,10)# Drives the Linkbot 10 inches forwarddriveDistance(myLinkbot,-5)# Drives the Linkbot 5 inches backward

The program shown above uses thedriveDistance() function to drive a robot forward 10 inches and then backward 5 inches. You might wondering why we went through all the trouble of defining a function, which took four lines of code, when we could accomplish the same task without functions.

  • Consider if the task was much more complex than just two movements. If you have to drive the robot forwards and backwards more than 4 times, you are actually saving time and code by using a function.
  • Writing repeated code via copy/paste can be very hard to debug. Imagine if you copy and pasted the equation 20 times for 20 robot movements, and then you found a bug in the copy-pasted code. You would have to correct the bug in each one of the 20 pasted code blocks. If you had written a function with a bug in it, you would only have to fix the equation inside the function.
  • If you are writing code for someone else to use, it would make sense to encapsulate your code in a function. Imagine if you are working with a team of people and your job is to write a function that moves the robot forward and backward, another person's job is to write a function that turns the robot, and a third person has to write a function that changes the LED color. You could then take all three functions and put them into a single program and have a robot that accurately drives a certain distance, turns, and changes LED color.

Examples

[edit |edit source]

temperature2.py

#! /usr/bin/python#-*-coding: utf-8 -*-# converts temperature to Fahrenheit or Celsiusdefprint_options():print("Options:")print(" 'p' print options")print(" 'c' convert from Celsius")print(" 'f' convert from Fahrenheit")print(" 'q' quit the program")defcelsius_to_fahrenheit(c_temp):return9.0/5.0*c_temp+32deffahrenheit_to_celsius(f_temp):return(f_temp-32.0)*5.0/9.0choice="p"whilechoice!="q":ifchoice=="c":c_temp=float(input("Celsius temperature: "))print("Fahrenheit:",celsius_to_fahrenheit(c_temp))choice=input("option: ")elifchoice=="f":f_temp=float(input("Fahrenheit temperature: "))print("Celsius:",fahrenheit_to_celsius(f_temp))choice=input("option: ")elifchoice=="p":#Alternatively choice != "q": so that print when anything unexpected inputedprint_options()choice=input("option: ")

Sample Run:

Options: 'p' print options 'c' convert from Celsius 'f' convert from Fahrenheit 'q' quit the programoption:cCelsius temperature:30 Fahrenheit: 86.0option:fFahrenheit temperature:60Celsius: 15.5555555556option:q

area2.py

#! /usr/bin/python#-*-coding: utf-8 -*-# calculates a given rectangle areadefhello():print('Hello!')defarea(width,height):returnwidth*heightdefprint_welcome(name):print('Welcome,',name)defpositive_input(prompt):number=float(input(prompt))whilenumber<=0:print('Must be a positive number')number=float(input(prompt))returnnumbername=input('Your Name: ')hello()print_welcome(name)print()print('To find the area of a rectangle,')print('enter the width and height below.')print()w=positive_input('Width: ')h=positive_input('Height: ')print('Width =',w,' Height =',h,' so Area =',area(w,h))

Sample Run:

Your Name:JoshHello!Welcome, JoshTo find the area of a rectangle,enter the width and height below.Width:-4Must be a positive numberWidth:4Height:3Width = 4  Height = 3  so Area = 12

Exercises

[edit |edit source]

Rewrite the area2.py program from the Examples above to have a separate function for the area of a square, the area of a rectangle, and the area of a circle (3.14 * radius**2). This program should include a menu interface.

Solution
defsquare(side):returnside*sidedefrectangle(width,height):returnwidth*heightdefcircle(radius):return3.14159*radius**2defoptions():print()print("Options:")print("s = calculate the area of a square.")print("c = calculate the area of a circle.")print("r = calculate the area of a rectangle.")print("q = quit")print()print("This program will calculate the area of a square, circle or rectangle.")choice="x"options()whilechoice!="q":choice=input("Please enter your choice: ")ifchoice=="s":side=float(input("Length of square side: "))print("The area of this square is",square(side))options()elifchoice=="c":radius=float(input("Radius of the circle: "))print("The area of the circle is",circle(radius))options()elifchoice=="r":width=float(input("Width of the rectangle: "))height=float(input("Height of the rectangle: "))print("The area of the rectangle is",rectangle(width,height))options()elifchoice=="q":print(" ",end="")else:print("Unrecognized option.")options()


Learning Python 3 with the Linkbot
 ← DebuggingPrintable versionAdvanced Functions Example → 


Advanced Functions Example

Some people find this section useful, and some find it confusing. If you find it confusing you can skip it. Now we will do a walk through for the following program:

defmult(a,b):ifb==0:return0rest=mult(a,b-1)value=a+restreturnvalueprint("3 * 2 = ",mult(3,2))

Basically this program creates a positive integer multiplication function(that is far slower than the built in multiplication function) and thendemonstrates this function with a use of the function. This program demonstrates the use of recursion, that is a form of iteration (repetition) in which there is a function that repeatedly calls itself until an exit condition is satisfied. It uses repeated additions to give the same result as mutiplication: e.g. 3 + 3 (addition) gives the same result as 3 * 2 (multiplication).

Question: What is the first thing the program does?
Answer: The first thing done is the function mult is defined with the lines:
defmult(a,b):ifb==0:return0rest=mult(a,b-1)value=a+restreturnvalue
This creates a function that takes two parameters and returns a value when it is done. Later this function can be run.
What happens next?
The next line after the function,print("3 * 2 = ", mult(3, 2)) is run.
And what does this do?
It prints3 * 2 = and the return value ofmult(3, 2)
And what doesmult(3, 2) return?
We need to do a walkthrough of themult function to find out.
What happens next?
The variablea gets the value 3 assigned to it and the variableb gets the value 2 assigned to it.
And then?
The lineif b == 0: is run. Sinceb has the value 2 this is false so the linereturn 0 is skipped.
And what then?
The linerest = mult(a, b - 1) is run. This line sets the local variablerest to the value ofmult(a, b - 1). The value of a is 3 and the value of b is 2 so the function call ismult(3,1)
So what is the value ofmult(3, 1) ?
We will need to run the function mult with the parameters 3 and 1.
So what happens next?
The local variables in the new run of the function are set so thata has the value 3 and b has the value 1. Since these are local values these do not affect the previous values ofa andb.
And then?
Since b has the value 1 the if statement is false, so the next line becomesrest = mult(a, b - 1).
What does this line do?
This line will assign the value ofmult(3, 0) to rest.
So what is that value?
We will have to run the function one more time to find that out. This timea has the value 3 andb has the value 0.
So what happens next?
The first line in the function to run isif b == 0:. b has the value 0 so the next line to run isreturn 0
And what does the linereturn 0 do?
This line returns the value 0 out of the function.
So?
So now we know thatmult(3, 0) has the value 0. Now we know what the linerest = mult(a, b - 1) did since we have run the functionmult with the parameters 3 and 0. We have finished runningmult(3, 0) and are now back to running mult(3, 1). The variablerest gets assigned the value 0.
What line is run next?
The linevalue = a + rest is run next. In this run of the function,a = 3 andrest = 0 so nowvalue = 3.
What happens next?
The linereturn value is run. This returns 3 from the function. This also exits from the run of the function mult(3, 1). Afterreturn is called, we go back to running mult(3, 2).
Where were we in mult(3, 2)?
We had the variablesa = 3 andb = 2 and were examining the linerest = mult(a, b - 1).
So what happens now?
The variablerest get 3 assigned to it. The next linevalue = a + rest setsvalue to3 + 3 or 6.
So now what happens?
The next line runs, this returns 6 from the function. We are now back to running the lineprint("3 * 2 = ", mult(3, 2)) which can now print out the 6.
What is happening overall?
Basically we used two facts to calculate the multiple of the two numbers. The first is that any number times 0 is 0 (x * 0 = 0). The second is that a number times another number is equal to the first number plus the first number times one less than the second number (x * y = x + x * (y - 1)). So what happens is3 * 2 is first converted into 3 + 3 * 1. Then3 * 1 is converted into3 + 3 * 0. Then we know that any number times 0 is 0 so3 * 0 is 0. Then we can calculate that3 + 3 * 0 is3 + 0 which is3. Now we know what3 * 1 is so we can calculate that3 + 3 * 1 is3 + 3 which is6.

This is how the whole thing works:

3 * 23 + 3 * 13 + 3 + 3 * 03 + 3 + 03 + 36

Recursion

[edit |edit source]

Programming constructs solving a problem by solving a smaller version of the same problem are calledrecursive. In the examples in this chapter, recursion is realized by defining a function calling itself. This facilitates implementing solutions to programming tasks as it may be sufficient to consider the next step of a problem instead of the whole problem at once. It is also useful as it allows to express some mathematical concepts with straightforward, easy to read code.

Any problem that can be solved with recursion could be re-implemented with loops. Using the latter usually results in better performance. However equivalent implementations using loops are usually harder to get done correctly.

Probably the most intuitive definition ofrecursion is:

Recursion
If you still don't get it, seerecursion.

Try walking through the factorial example if the multiplication example did not make sense.

Examples

[edit |edit source]

factorial.py

#defines a function that calculates the factorialdeffactorial(n):ifn<=1:return1returnn*factorial(n-1)print("2! =",factorial(2))print("3! =",factorial(3))print("4! =",factorial(4))print("5! =",factorial(5))

Output:

2! = 23! = 64! = 245! = 120

countdown.py

defcount_down(n):print(n)ifn>0:returncount_down(n-1)count_down(5)

Output:

543210


Learning Python 3 with the Linkbot
 ← Defining FunctionsPrintable versionLists → 


Lists

Variables with more than one value

[edit |edit source]

You have already seen ordinary variables that store a single value. However other variable types can hold more than one value. These are called containers because they can contain more than one object. The simplest type is called a list. Here is an example of a list being used:

which_one=int(input("What month (1-12)? "))months=['January','February','March','April','May','June','July','August','September','October','November','December']if1<=which_one<=12:print("The month is",months[which_one-1])

and an output example:

What month (1-12)?3The month is March

In this example themonths is a list.months is defined with the lines months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', and'August', 'September', 'October', 'November', 'December'] (note that a\ could also be used to split a long line, but that is not necessary in this case because Python is intelligent enough to recognize that everything within brackets belongs together). The[ and] start and end the list with commas (,) separating the list items. The list is used inmonths[which_one - 1]. A list consists of items that are numbered starting at 0. In other words, if you wanted January you would usemonths[0]. Give a list a number and it will return the value that is stored at that location.

The statement if 1 <= which_one <= 12: will only be true if which_one is between one and twelve inclusive (in other words it is what you would expect if you have seen that in algebra).

Lists can be thought of as a series of boxes. Each box has a different value. For example, the boxes created bydemolist = ['life', 42, 'the universe', 6, 'and', 9] would look like this:

box number012345
demolist"life"42"the universe"6"and"9

Each box is referenced by its number so the statementdemolist[0] would get'life',demolist[1] would get42 and so on up todemolist[5] getting9.

More features of lists

[edit |edit source]

The next example is just to show a lot of other stuff lists can do (for once I don't expect you to type it in, but you should probably play around with lists in interactive mode until you are comfortable with them.). Here goes:

demolist=["life",42,"the universe",6,"and",9]print("demolist = ",demolist)demolist.append("everything")print("after 'everything' was appended demolist is now:")print(demolist)print("len(demolist) =",len(demolist))print("demolist.index(42) =",demolist.index(42))print("demolist[1] =",demolist[1])# Next we will loop through the listforcinrange(len(demolist)):print("demolist[",c,"] =",demolist[c])deldemolist[2]print("After 'the universe' was removed demolist is now:")print(demolist)if"life"indemolist:print("'life' was found in demolist")else:print("'life' was not found in demolist")if"amoeba"indemolist:print("'amoeba' was found in demolist")if"amoeba"notindemolist:print("'amoeba' was not found in demolist")another_list=[42,7,0,123]another_list.sort()print("The sorted another_list is",another_list)

The output is:

demolist =  ['life', 42, 'the universe', 6, 'and', 9]after 'everything' was appended demolist is now:['life', 42, 'the universe', 6, 'and', 9, 'everything']len(demolist) = 7demolist.index(42) = 1demolist[1] = 42demolist[ 0 ] = lifedemolist[ 1 ] = 42demolist[ 2 ] = the universedemolist[ 3 ] = 6demolist[ 4 ] = anddemolist[ 5 ] = 9demolist[ 6 ] = everythingAfter 'the universe' was removed demolist is now:['life', 42, 6, 'and', 9, 'everything']'life' was found in demolist'amoeba' was not found in demolistThe sorted another_list is [0, 7, 42, 123]

This example uses a whole bunch of new functions. Notice that you canjustprint a whole list. Next theappend function is usedto add a new item to the end of the list.len returns how manyitems are in a list. The valid indexes (as in numbers that can beused inside of the[]) of a list range from 0 tolen - 1. Theindex function tells where the first location of an item islocated in a list. Notice howdemolist.index(42) returns 1, andwhendemolist[1] is run it returns 42. To get help on all the functions a list provides for you, typehelp(list) in the interactive Python interpreter.

The line# Next we will loop through the list is a just a reminder to the programmer (also called acomment). Python ignores everything that is written after a# on the current line. Next the lines:

forcinrange(len(demolist)):print('demolist[',c,'] =',demolist[c])

create a variablec, which starts at 0 and is incremented until it reaches the last index of the list. Meanwhile, theprint statement prints out each element of the list.

A much better way to do the above is:

forc,xinenumerate(demolist):print("demolist[",c,"] =",x)

Thedel command can be used to remove a given element in a list. The next few lines use thein operator to test if an element is in or is not in a list. Thesort function sorts the list. This is useful if you need alist in order from smallest number to largest or alphabetical. Notethat this rearranges the list. In summary, for a list, the following operations occur:

exampleexplanation
demolist[2]accesses the element at index 2
demolist[2] = 3sets the element at index 2 to be 3
del demolist[2]removes the element at index 2
len(demolist)returns the length ofdemolist
"value" in demolistisTrue if"value" is an element indemolist
"value" not in demolistisTrue if"value" is not an element indemolist
another_list.sort()sortsanother_list. Note that the list must be all numbers or all strings to be sorted.
demolist.index("value")returns the index of the first place that"value" occurs
demolist.append("value")adds an element"value" at the end of the list
demolist.remove("value")removes the first occurrence of value fromdemolist (same asdel demolist[demolist.index("value")])

This next example uses these features in a more useful way:

menu_item=0namelist=[]whilemenu_item!=9:print("--------------------")print("1. Print the list")print("2. Add a name to the list")print("3. Remove a name from the list")print("4. Change an item in the list")print("9. Quit")menu_item=int(input("Pick an item from the menu: "))ifmenu_item==1:current=0iflen(namelist)>0:whilecurrent<len(namelist):print(current,".",namelist[current])current=current+1else:print("List is empty")elifmenu_item==2:name=input("Type in a name to add: ")namelist.append(name)elifmenu_item==3:del_name=input("What name would you like to remove: ")ifdel_nameinnamelist:# namelist.remove(del_name) would work just as fineitem_number=namelist.index(del_name)delnamelist[item_number]# The code above only removes the first occurrence of# the name.  The code below from Gerald removes all.# while del_name in namelist:#       item_number = namelist.index(del_name)#       del namelist[item_number]else:print(del_name,"was not found")elifmenu_item==4:old_name=input("What name would you like to change: ")ifold_nameinnamelist:item_number=namelist.index(old_name)new_name=input("What is the new name: ")namelist[item_number]=new_nameelse:print(old_name,"was not found")print("Goodbye")

And here is part of the output:

--------------------1. Print the list2. Add a name to the list3. Remove a name from the list4. Change an item in the list9. QuitPick an item from the menu:2Type in a name to add:JackPick an item from the menu:2Type in a name to add:JillPick an item from the menu:10 . Jack1 . JillPick an item from the menu:3What name would you like to remove:JackPick an item from the menu:4What name would you like to change:JillWhat is the new name:Jill PetersPick an item from the menu:10 . Jill PetersPick an item from the menu:9Goodbye

That was a long program. Let's take a look at the source code. The linenamelist = [] makes the variablenamelist a list with no items (or elements). The next important line iswhile menu_item != 9:. This line starts a loop that allows the menu system for this program. The next few lines display a menu and decide which part of the program to run.

The section

current=0iflen(namelist)>0:whilecurrent<len(namelist):print(current,".",namelist[current])current=current+1else:print("List is empty")

goes through the list and prints each name.len(namelist) tells how many items are in the list. Iflen returns0, then the list is empty.

Then, a few lines later, the statementnamelist.append(name) appears. It uses theappend function to add an item to the end of the list. Jump down another two lines, and notice this section of code:

item_number=namelist.index(del_name)delnamelist[item_number]

Here theindex function is used to find the index value that will be used later to remove the item.del namelist[item_number] is used to remove an element of the list.

The next section

old_name=input("What name would you like to change: ")ifold_nameinnamelist:item_number=namelist.index(old_name)new_name=input("What is the new name: ")namelist[item_number]=new_nameelse:print(old_name,"was not found")

usesindex to find theitem_number and then putsnew_name where theold_name was.

Congratulations, with lists under your belt, you now know enough of the languagethat you could do any computations that a computer can do (this is technically known asTuring-Completeness). Of course, there are still many features thatare used to make your life easier.

Examples

[edit |edit source]

test.py

## This program runs a test of knowledge# First get the test questions# Later this will be modified to use file io.defget_questions():# notice how the data is stored as a list of listsreturn[["What color is the daytime sky on a clear day? ","blue"],["What is the answer to life, the universe and everything? ","42"],["What is a three letter word for mouse trap? ","cat"]]# This will test a single question# it takes a single question in# it returns True if the user typed the correct answer, otherwise Falsedefcheck_question(question_and_answer):# extract the question and the answer from the list# This function takes a list with two elements, a question and an answer.question=question_and_answer[0]answer=question_and_answer[1]# give the question to the usergiven_answer=input(question)# compare the user's answer to the tester's answerifanswer==given_answer:print("Correct")returnTrueelse:print("Incorrect, correct was:",answer)returnFalse# This will run through all the questionsdefrun_test(questions):iflen(questions)==0:print("No questions were given.")# the return exits the functionreturnindex=0right=0whileindex<len(questions):# Check the question#Note that this is extracting a question and answer list from the list of lists.ifcheck_question(questions[index]):right=right+1# go to the next questionindex=index+1# notice the order of the computation, first multiply, then divideprint("You got",right*100/len(questions),\"% right out of",len(questions))# now let's get the questions from the get_questions function, and# send the returned list of lists as an argument to the run_test function.run_test(get_questions())

The valuesTrue andFalse point to 1 and 0, respectively. They are often used in sanity checks, loop conditions etc. You will learn more about this a little bit later (chapterBoolean Expressions).Please note that get_questions() is essentially a list because even though it's technically a function, returning a list of lists is the only thing it does.

Sample Output:

What color is the daytime sky on a clear day?greenIncorrect, correct was: blueWhat is the answer to life, the universe and everything?42CorrectWhat is a three letter word for mouse trap?catCorrectYou got 66 % right out of 3

LinkbotMelody.py

We can also create our own lists of items and use for loops to loop through them. Lets try making a list of keyboard keys to play in order to play a simple tune.We'll write this program using the knowledge that middle-C is the 40th key on our keyboard.When you run this program, it should play the beginning of a very familiar tune. Can you guess what it is?

importbarobodongle=barobo.Dongle()dongle.connect()robot=dongle.getLinkbot('6wbn')# Replace '6wbn' with the serial ID on your Linkbotimporttime# Need to "import time" so we can use time.sleep()myNotes=[44,42,40,42,44,44,44]# Put some notes into a listt=0.5# Set a value to be used for the duration of the noteforiinmyNotes:# Select which keys on a piano keyboard to use for the tonesk=pow(2,(i-49)/12)*440# Determines the frequency of the note to be playedrobot.setBuzzerFrequency(k)# Directs the Linkbot to play this frequencytime.sleep(t)# Pauses the program while the note is playedrobot.setBuzzerFrequency(0)# Turns off the piezo speaker at the end of each note

Exercises

[edit |edit source]

Expand the test.py program so it has a menu giving the option of takingthe test, viewing the list of questions and answers, and an option toquit. Also, add a new question to ask, "What noise does a trulyadvanced machine make?" with the answer of "ping".

Solution

Expand the test.py program so it has menu giving the option of takingthe test, viewing the list of questions and answers, and an option toquit. Also, add a new question to ask, "What noise does a trulyadvanced machine make?" with the answer of "ping".

## This program runs a test of knowledgequestions=[["What color is the daytime sky on a clear day? ","blue"],["What is the answer to life, the universe and everything? ","42"],["What is a three letter word for mouse trap? ","cat"],["What noise does a truly advanced machine make?","ping"]]# This will test a single question# it takes a single question in# it returns True if the user typed the correct answer, otherwise Falsedefcheck_question(question_and_answer):# extract the question and the answer from the listquestion=question_and_answer[0]answer=question_and_answer[1]# give the question to the usergiven_answer=input(question)# compare the user's answer to the testers answerifanswer==given_answer:print("Correct")returnTrueelse:print("Incorrect, correct was:",answer)returnFalse# This will run through all the questionsdefrun_test(questions):iflen(questions)==0:print("No questions were given.")# the return exits the functionreturnindex=0right=0whileindex<len(questions):# Check the questionifcheck_question(questions[index]):right=right+1# go to the next questionindex=index+1# notice the order of the computation, first multiply, then divideprint("You got",right*100/len(questions),"% right out of",len(questions))#showing a list of questions and answersdefshowquestions():q=0whileq<len(questions):a=0print("Q:",questions[q][a])a=1print("A:",questions[q][a])q=q+1# now let's define the menu functiondefmenu():print("-----------------")print("Menu:")print("1 - Take the test")print("2 - View a list of questions and answers")print("3 - View the menu")print("5 - Quit")print("-----------------")choice="3"whilechoice!="5":ifchoice=="1":run_test(questions)elifchoice=="2":showquestions()elifchoice=="3":menu()print()choice=input("Choose your option from the menu above: ")


Learning Python 3 with the Linkbot
 ← Advanced Functions ExamplePrintable versionFor Loops → 


For Loops

And here is the new typing exercise for this chapter:

onetoten=range(1,11)forcountinonetoten:print(count)

and the ever-present output:

12345678910

The output looks awfully familiar but the program code looks different. The first line uses therange function. Therange function uses two arguments like thisrange(start, finish).start is the first number that is produced.finish is one larger than the last number. Note that this program could have been done in a shorter way:

forcountinrange(1,11):print(count)

The range function returns an iterable. This can be converted into a list with thelist function. Here are some examples to show what happens with therange command:

>>>range(1, 10)range(1, 10)>>>list(range(1, 10))[1, 2, 3, 4, 5, 6, 7, 8, 9]>>>list(range(-32, -20))[-32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21]>>>list(range(5,21))[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]>>>list(range(5))[0, 1, 2, 3, 4]>>>list(range(21, 5))[]

The next linefor count in onetoten: uses thefor control structure. Afor control structure looks likefor variable in list:.list is gone through starting with the first element of the list and going to the last. Asfor goes through each element in a list it puts each intovariable. That allowsvariable to be used in each successive time thefor loop is run through. Here is another example (you don't have to type this) to demonstrate:

demolist=['life',42,'the universe',6,'and',7,'everything']foritemindemolist:print("The current item is:",item)

The output is:

The current item is: lifeThe current item is: 42The current item is: the universeThe current item is: 6The current item is: andThe current item is: 7The current item is: everything

Notice how thefor loop goes through and sets item to each element in the list. So, what isfor good for? The first use is to go through all the elements of a list and do something with each of them. Here's a quick way to add up all the elements:

list=[2,4,6,8]sum=0fornuminlist:sum=sum+numprint("The sum is:",sum)

with the output simply being:

The sum is: 20

Or you could write a program to find out if there are any duplicates in a list like this program does:

list=[4,5,7,8,9,1,0,7,10]list.sort()prev=Noneforiteminlist:ifprev==item:print("Duplicate of",prev,"found")prev=item

and for good measure:

Duplicate of 7 found

Okay, so how does it work? Here is a special debugging version to help you understand (you don't need to type this in):

l=[4,5,7,8,9,1,0,7,10]print("l = [4, 5, 7, 8, 9, 1, 0, 7, 10]","\t\tl:",l)l.sort()print("l.sort()","\t\tl:",l)prev=l[0]print("prev = l[0]","\t\tprev:",prev)dell[0]print("del l[0]","\t\tl:",l)foriteminl:ifprev==item:print("Duplicate of",prev,"found")print("if prev == item:","\t\tprev:",prev,"\titem:",item)prev=itemprint("prev = item","\t\tprev:",prev,"\titem:",item)

with the output being:

l = [4, 5, 7, 8, 9, 1, 0, 7, 10]        l: [4, 5, 7, 8, 9, 1, 0, 7, 10]l.sort()                l: [0, 1, 4, 5, 7, 7, 8, 9, 10]prev = l[0]             prev: 0del l[0]                l: [1, 4, 5, 7, 7, 8, 9, 10]if prev == item:        prev: 0         item: 1prev = item             prev: 1         item: 1if prev == item:        prev: 1         item: 4prev = item             prev: 4         item: 4if prev == item:        prev: 4         item: 5prev = item             prev: 5         item: 5if prev == item:        prev: 5         item: 7prev = item             prev: 7         item: 7Duplicate of 7 foundif prev == item:        prev: 7         item: 7prev = item             prev: 7         item: 7if prev == item:        prev: 7         item: 8prev = item             prev: 8         item: 8if prev == item:        prev: 8         item: 9prev = item             prev: 9         item: 9if prev == item:        prev: 9         item: 10prev = item             prev: 10        item: 10

The reason I put so manyprint statements in the code was so that you can see what is happening in each line. (By the way, if you can't figure out why a program is not working, try putting in lots of print statements in places where you want to know what is happening.) First the program starts with a boring old list. Next the program sorts the list. This is so that any duplicates get put next to each other. The program then initializes aprev(ious) variable. Next the first element of the list is deleted so that the first item is not incorrectly thought to be a duplicate. Next afor loop is gone into. Each item of the list is checked to see if it is the same as the previous. If it is a duplicate was found. The value ofprev is then changed so that the next time thefor loop is run throughprev is the previous item to the current. Sure enough, the 7 is found to be a duplicate. (Notice how\t is used to print a tab.)

The other way to usefor loops is to do something a certain number of times. Here is some code to print out the first 9 numbers of the Fibonacci series:

a=1b=1forcinrange(1,10):print(a,end=" ")n=a+ba=bb=n

with the surprising output:

1 1 2 3 5 8 13 21 34

Everything that can be done withfor loops can also be done withwhile loops butfor loops give an easy way to go through all the elements in a list or to do something a certain number of times.

A Linkbot Example

[edit |edit source]

In this example the Linkbot will play changing tones a fixed number of times while the duration remains constant. The Linkbot can also change tone and duration a fixed number of times. Here we are using a for loop running with in a fixed range of values.

setBuzzerFrequency.py

importbarobodongle=barobo.Dongle()dongle.connect()robot=dongle.getLinkbot('6wbn')# Replace '6wbn' with the serial ID on your Linkbotimporttime# For time.sleep()t=1# Set a value to be used for the duration of the noteforiinrange(33,43):# Select which keys on a piano keyboard to use for the tonesk=pow(2,(i-49)/12)*440# Determines the frequency of the note to be playedrobot.setBuzzerFrequency(k)# Directs the Linkbot to play this frequencytime.sleep(t)# Pauses the program while the note is playedrobot.setBuzzerFrequency(0)# Turns off the piezo speaker at the end of the program

When you run this example play around with the loop range and time values to create interesting sounds.

Learning Python 3 with the Linkbot
 ← ListsPrintable versionBoolean Expressions → 


Boolean Expressions

Here is a little example of boolean expressions (you don't have to type it in):

a=6b=7c=42print(1,a==6)print(2,a==7)print(3,a==6andb==7)print(4,a==7andb==7)print(5,nota==7andb==7)print(6,a==7orb==7)print(7,a==7orb==6)print(8,not(a==7andb==6))print(9,nota==7andb==6)

With the output being:

1 True2 False3 True4 False5 True6 True7 False8 True9 False

What is going on? The program consists of a bunch of funny lookingprint statements. Eachprint statement prints a number and an expression. The number is to help keep track of which statement I am dealing with. Notice how each expression ends up being eitherFalse orTrue. In Python false can also be written as 0 and true as 1.

The lines:

print(1,a==6)print(2,a==7)

print out aTrue and aFalse respectively just as expected since the first is true and the second is false. The third print,print(3, a == 6 and b == 7), is a little different. The operatorand means if both the statement before and the statement after are true then the whole expression is true otherwise the whole expression is false. The next line,print(4, a == 7 and b == 7), shows how if part of anand expression is false, the whole thing is false. The behavior ofand can be summarized as follows:

expressionresult
trueand truetrue
trueand falsefalse
falseand truefalse
falseand falsefalse

Notice that if the first expression is false Python does not check the second expression since it knows the whole expression is false. Try runningFalse and print("Hi") and compare this to runningTrue and print("Hi") The technical term for this isshort-circuit evaluation

The next line,print(5, not a == 7 and b == 7), uses thenot operator.not just gives the opposite of the expression. (The expression could be rewritten as print(5, a != 7 and b == 7)). Here is the table:

expressionresult
not truefalse
not falsetrue

The two following lines,print(6, a == 7 or b == 7) andprint(7, a == 7 or b == 6), use theor operator. Theor operator returns true if the first expression is true, or if the second expression is true or both are true. If neither are true it returns false. Here's the table:

expressionresult
trueor truetrue
trueor falsetrue
falseor truetrue
falseor falsefalse

Notice that if the first expression is true Python doesn't check the second expression since it knows the whole expression is true. This works sinceor is true if at least one half of the expression is true. The first part is true so the second part could be either false or true, but the whole expression is still true.

The next two lines,print(8, not (a == 7 and b == 6)) andprint(9, not a == 7 and b == 6), show that parentheses can be used to group expressions and force one part to be evaluated first. Notice that the parentheses changed the expression from false to true. This occurred since the parentheses forced thenot to apply to the whole expression instead of just thea == 7 portion.

Here is an example of using a boolean expression:

list=["Life","The Universe","Everything","Jack","Jill","Life","Jill"]# make a copy of the list. See the More on Lists chapter to explain what [:] means.copy=list[:]# sort the copycopy.sort()prev=copy[0]delcopy[0]count=0# go through the list searching for a matchwhilecount<len(copy)andcopy[count]!=prev:prev=copy[count]count=count+1# If a match was not found then count can't be < len# since the while loop continues while count is < len# and no match is foundifcount<len(copy):print("First Match:",prev)

And here is the output:

First Match: Jill

This program works by continuing to check for matchwhile count < len(copy) and copy[count] is not equal to prev. When eithercount is greater than the last index ofcopy or a match has been found theand is no longer true so the loop exits. Theif simply checks to make sure that thewhile exited because a match was found.

The other "trick" ofand is used in this example. If you look at the table forand notice that the third entry is "false and false". Ifcount >= len(copy) (in other wordscount < len(copy) is false) thencopy[count] is never looked at. This is because Python knows that if the first is false then they can't both be true. This is known as a short circuit and is useful if the second half of theand will cause an error if something is wrong. I used the first expression (count < len(copy)) to check and see ifcount was a valid index forcopy. (If you don't believe me remove the matches "Jill" and "Life", check that it still works and then reverse the order ofcount < len(copy) and copy[count] != prev tocopy[count] != prev and count < len(copy).)

Boolean expressions can be used when you need to check two or more different things at once.

A note on Boolean Operators

[edit |edit source]

A common mistake for people new to programming is a misunderstanding of the way that boolean operators works, which stems from the way the python interpreter reads these expressions. For example, after initially learning about "and " and "or" statements, one might assume that the expressionx == ('a' or 'b') would check to see if the variablex was equivalent to one of the strings'a' or'b'. This is not so. To see what I'm talking about, start an interactive session with the interpreter and enter the following expressions:

>>> 'a' == ('a' or 'b')>>> 'b' == ('a' or 'b')>>> 'a' == ('a' and 'b')>>> 'b' == ('a' and 'b')

And this will be the unintuitive result:

>>> 'a' == ('a' or 'b')True>>> 'b' == ('a' or 'b')False>>> 'a' == ('a' and 'b')False >>> 'b' == ('a' and 'b')True

At this point, theand andor operators seem to be broken. It doesn't make sense that, for the first two expressions,'a' is equivalent to'a' or'b' while'b' is not. Furthermore, it doesn't make any sense that 'b' is equivalent to'a' and'b'. After examining what the interpreter does with boolean operators, these results do in fact exactly what you are asking of them, it's just not the same as what you think you are asking.

When the Python interpreter looks at anor expression, it takes the first statement and checks to see if it is true. If the first statement is true, then Python returns that object's value without checking the second statement. This is because for anor expression, the whole thing is true if one of the values is true; the program does not need to bother with the second statement. On the other hand, if the first value is evaluated as false Python checks the second half and returns that value. That second half determines the truth value of the whole expression since the first half was false. This "laziness" on the part of the interpreter is called "short circuiting" and is a common way of evaluating boolean expressions in many programming languages.

Similarly, for anand expression, Python uses a short circuit technique to speed truth value evaluation. If the first statement is false then the whole thing must be false, so it returns that value. Otherwise if the first value is true it checks the second and returns that value.

One thing to note at this point is that the boolean expression returns a value indicatingTrue orFalse, but that Python considers a number of different things to have a truth value assigned to them. To check the truth value of any given objectx, you can use the fuctionbool(x) to see its truth value. Below is a table with examples of the truth values of various objects:

TrueFalse
TrueFalse
10
Numbers other than zeroThe string 'None'
Nonempty stringsEmpty strings
Nonempty listsEmpty lists
Nonempty dictionariesEmpty dictionaries

Now it is possible to understand the perplexing results we were getting when we tested those boolean expressions before. Let's take a look at what the interpreter "sees" as it goes through that code:

First case:

>>> 'a' == ('a' or 'b')  # Look at parentheses first, so evaluate expression "('a' or 'b')"                           # 'a' is a nonempty string, so the first value is True                           # Return that first value: 'a'>>> 'a' == 'a'          # the string 'a' is equivalent to the string 'a', so expression is TrueTrue

Second case:

>>> 'b' == ('a' or 'b')  # Look at parentheses first, so evaluate expression "('a' or 'b')"                           # 'a' is a nonempty string, so the first value is True                           # Return that first value: 'a'>>> 'b' == 'a'          # the string 'b' is not equivalent to the string 'a', so expression is FalseFalse

Third case:

>>> 'a' == ('a' and 'b') # Look at parentheses first, so evaluate expression "('a' and 'b')"                           # 'a' is a nonempty string, so the first value is True, examine second value                           # 'b' is a nonempty string, so second value is True                           # Return that second value as result of whole expression: 'b'>>> 'a' == 'b'          # the string 'a' is not equivalent to the string 'b', so expression is FalseFalse

Fourth case:

>>> 'b' == ('a' and 'b') # Look at parentheses first, so evaluate expression "('a' and 'b')"                           # 'a' is a nonempty string, so the first value is True, examine second value                           # 'b' is a nonempty string, so second value is True                           # Return that second value as result of whole expression: 'b'>>> 'b' == 'b'          # the string 'b' is equivalent to the string 'b', so expression is TrueTrue

So Python was really doing its job when it gave those apparently bogus results. As mentioned previously, the important thing is to recognize what value your boolean expression will return when it is evaluated, because it isn't always obvious.

Going back to those initial expressions, this is how you would write them out so they behaved in a way that you want:

>>> 'a' == 'a' or 'a' == 'b'True>>> 'b' == 'a' or 'b' == 'b'True>>> 'a' == 'a' and 'a' == 'b'False>>> 'b' == 'a' and 'b' == 'b'False

When these comparisons are evaluated they return truth values in terms of True or False, not strings, so we get the proper results.

Using the Linkbot's Accelerometer

[edit |edit source]

An accelerometer is a device which can be used to detect the acceleration of an object, or the force of gravity. For instance, when you are sitting in a car and the driver steps on the gas pedal, you can feel a force pushing you back into your seat. Or, as you are sitting in your chair right now, you can feel Earth's gravity pulling you down, towards the center of the earth. The Linkbot can also feel these forces acting on it using its accelerometer, and you can get the accelerometer values from the Linkbot.

Lets take a look at the Linkbot'sgetAccelerometerData() function.

importbarobodongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot()accel=myLinkbot.getAccelerometerData()print(accel)

Output

[0.005859375, -0.1005859375, 0.9755859375]

This small program connects to a Linkbot, gets its accelerometer data, and prints it out. The number you get may be different than the ones shown, depending on the orientation and acceleration of your Linkbot when you ran the program.

Notice that the value isn't a single value, but is actually a list of 3 values. Each one of these values is the force (in G's) that the Linkbot is currently experiencing on a particular axis direction, corresponding to the x, y, and z axes of the Linkbot.

We can calculate the total magnitude of force that the Linkbot is experiencing through this equation:

TotalMagnitude=x2+y2+z2{\displaystyle \mathrm {TotalMagnitude} ={\sqrt {x^{2}+y^{2}+z^{2}}}}

Lets write a Python function that calculates the magnitude of acceleration given a list of three acceleration values:

importmath# for math.sqrt(), the square-root functiondefaccelMag(accel):returnmath.sqrt(accel[0]**2+accel[1]**2+accel[2]**2)importbarobodongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('ABCD')# Replace 'ABCD' with your Linkbot's Serial IDaccel=myLinkbot.getAccelerometerData()# Get the accel valuesprint(accel)# print accel valuesprint(accelMag(accel))# print total magnitude of accel values

Output:

[0.0078125, -0.1015625, 0.974609375]0.9799180631054775

Note that the units of these numbers is in earth-gravitational units, usually called "G's". When the above output was produced, the code was executed on a Linkbot that was sitting still on a desk. Because the Linkbot is only being pulled on by Earth's gravity, we expect its magnitude to be very close to 1. If the Linkbot were weightless, floating in space, or in freefall, we can expect the magnitude to be close to zero.

Lets try tilting our Linkbot on a diagonal and running it again. We should expect the three numbers in the list to change, but the total magnitude should still be very close to 1.

Output:

[0.72265625, -0.6875, -0.0244140625]0.997739621400201

As we can see, theaccelMag() function that we wrote can display the total magnitude of acceleration acting on the Linkbot regardless of direction. That means we can use it to detect free-fall or high acceleration events, like if the Linkbot is dropped, or bumps into something.

Now, lets try to write a program that makes the Linkbot beep if it detects that it is in freefall.Notice, though, that the values reported by the accelerometer have some "noise". Noise is tiny amounts of error that are picked up at random by robotic sensors. What this means is that the magnitude reported by the Linkbot will almost never exactly zero or exactly 1, even if the Linkbot is in free-fall or sitting still on your desk. What this means is when we write our program, we don't want to check to see if the acceleration magnitude is zero. Instead, we want to check to see if it is below a certain threshold; say, 0.2 G's.

importmath# for math.sqrt()defaccelMag(accel):returnmath.sqrt(accel[0]**2+accel[1]**2+accel[2]**2)importbaroboimporttime# for time.sleep()dongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('ABCD')# Replace 'ABCD' with your Linkbot's Serial IDprint('Gently toss your Linkbot into the air. Type Ctrl-C to quit the program.')whileTrue:accel=myLinkbot.getAccelerometerData()ifaccelMag(accel)<0.2:# 1myLinkbot.setBuzzerFrequency(440)# 2print('Wheeee!')time.sleep(1)myLinkbot.setBuzzerFrequency(0)

Notice that we've now added an infinite loop to the program. The loop repeatedly checks the accelerometer magnitude at "# 1". If the magnitude is less than 0.2, it beeps the buzzer for 1 second at "# 2".

Examples

[edit |edit source]

password1.py

## This program asks a user for a name and a password.# It then checks them to make sure that the user is allowed in.name=input("What is your name? ")password=input("What is the password? ")ifname=="Josh"andpassword=="Friday":print("Welcome Josh")elifname=="Fred"andpassword=="Rock":print("Welcome Fred")else:print("I don't know you.")

Sample runs

What is your name?JoshWhat is the password?FridayWelcome Josh
What is your name?BillWhat is the password?MoneyI don't know you.

Exercises

[edit |edit source]

Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits.

Solution
print("Try to guess my name!")count=1name="guilherme"guess=input("What is my name? ")whilecount<3andguess.lower()!=name:# .lower allows things like Guilherme to still matchprint("You are wrong!")guess=input("What is my name? ")count=count+1ifguess.lower()!=name:print("You are wrong!")# this message isn't printed in the third chance, so we print it nowprint("You ran out of chances.")else:print("Yes! My name is",name+"!")


Write a Linkbot program that beeps if the acceleration exceeds 2 G's. This typically happens if the robot is bumped, or when the robot is shaken vigorously.

Solution
importmathdefaccelMag(accel):returnmath.sqrt(accel[0]**2+accel[1]**2+accel[2]**2)importbaroboimporttime# For time.sleep()dongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('ABCD')# Change 'ABCD' to your Linkbot's Serial IDprint('Shake or bump your Linkbot. Type Ctrl-C to quit the program.')whileTrue:accel=myLinkbot.getAccelerometerData()ifaccelMag(accel)>2:myLinkbot.setBuzzerFrequency(440)print('Ow!')time.sleep(1)myLinkbot.setBuzzerFrequency(0)


Learning Python 3 with the Linkbot
 ← For LoopsPrintable versionDictionaries → 


Dictionaries

This chapter is about dictionaries. Dictionaries have keys and values. The keys are used to find the values. Here is an example of a dictionary in use:

defprint_menu():print('1. Print Phone Numbers')print('2. Add a Phone Number')print('3. Remove a Phone Number')print('4. Lookup a Phone Number')print('5. Quit')print()numbers={}menu_choice=0print_menu()whilemenu_choice!=5:menu_choice=int(input("Type in a number (1-5): "))ifmenu_choice==1:print("Telephone Numbers:")forxinnumbers.keys():print("Name: ",x,"\tNumber:",numbers[x])print()elifmenu_choice==2:print("Add Name and Number")name=input("Name: ")phone=input("Number: ")numbers[name]=phoneelifmenu_choice==3:print("Remove Name and Number")name=input("Name: ")ifnameinnumbers:delnumbers[name]else:print(name,"was not found")elifmenu_choice==4:print("Lookup Number")name=input("Name: ")ifnameinnumbers:print("The number is",numbers[name])else:print(name,"was not found")elifmenu_choice!=5:print_menu()

And here is my output:

1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. QuitType in a number (1-5):2Add Name and NumberName:JoeNumber:545-4464Type in a number (1-5):2Add Name and NumberName:JillNumber:979-4654Type in a number (1-5):2Add Name and NumberName:FredNumber:132-9874Type in a number (1-5):1Telephone Numbers:Name: Jill     Number: 979-4654Name: Joe      Number: 545-4464Name: Fred     Number: 132-9874Type in a number (1-5):4Lookup NumberName:JoeThe number is 545-4464Type in a number (1-5):3Remove Name and NumberName:FredType in a number (1-5):1Telephone Numbers:Name: Jill     Number: 979-4654Name: Joe      Number: 545-4464Type in a number (1-5):5

This program is similar to the name list earlier in the chapter on lists. Here's how the program works. First the functionprint_menu is defined.print_menu just prints a menu that is later used twice in the program. Next comes the funny looking linenumbers = {}. All that this line does is to tell Python thatnumbers is a dictionary. The next few lines just make the menu work. The lines

forxinnumbers.keys():print"Name:",x,"\tNumber:",numbers[x]

go through the dictionary and print all the information. The function numbers.keys() returns a list that is then used by thefor loop. The list returned bykeys() is not in any particular order so if you want it in alphabetic order it must be sorted. Similar to lists the statementnumbers[x] is used to access a specific member of the dictionary. Of course in this casex is a string. Next the linenumbers[name] = phone adds a name and phone number to the dictionary. Ifname had already been in the dictionaryphone would replace whatever was there before. Next the lines

ifnameinnumbers:delnumbers[name]

see if a name is in the dictionary and remove it if it is. The operatorname in numbers returns true ifname is innumbers but otherwise returns false. The linedel numbers[name] removes the keyname and the value associated with that key. The lines

ifnameinnumbers:print("The number is",numbers[name])

check to see if the dictionary has a certain key and if it does prints out the number associated with it. Lastly if the menu choice is invalid it reprints the menu for your viewing pleasure.

A recap: Dictionaries have keys and values. Keys can be strings ornumbers. Keys point to values. Values can be any type of variable(including lists or even dictionaries (those dictionaries or lists ofcourse can contain dictionaries or lists themselves (scary right? :-)))). Here is an example of using a list in a dictionary:

max_points=[25,25,50,25,100]assignments=['hw ch 1','hw ch 2','quiz   ','hw ch 3','test']students={'#Max':max_points}defprint_menu():print("1. Add student")print("2. Remove student")print("3. Print grades")print("4. Record grade")print("5. Print Menu")print("6. Exit")defprint_all_grades():print('\t',end=' ')foriinrange(len(assignments)):print(assignments[i],'\t',end=' ')print()keys=list(students.keys())keys.sort()forxinkeys:print(x,'\t',end=' ')grades=students[x]print_grades(grades)defprint_grades(grades):foriinrange(len(grades)):print(grades[i],'\t',end=' ')print()print_menu()menu_choice=0whilemenu_choice!=6:print()menu_choice=int(input("Menu Choice (1-6): "))ifmenu_choice==1:name=input("Student to add: ")students[name]=[0]*len(max_points)elifmenu_choice==2:name=input("Student to remove: ")ifnameinstudents:delstudents[name]else:print("Student:",name,"not found")elifmenu_choice==3:print_all_grades()elifmenu_choice==4:print("Record Grade")name=input("Student: ")ifnameinstudents:grades=students[name]print("Type in the number of the grade to record")print("Type a 0 (zero) to exit")foriinrange(len(assignments)):print(i+1,assignments[i],'\t',end=' ')print()print_grades(grades)which=1234whilewhich!=-1:which=int(input("Change which Grade: "))which-=1#same as which = which - 1if0<=which<len(grades):grade=int(input("Grade: "))grades[which]=gradeelifwhich!=-1:print("Invalid Grade Number")else:print("Student not found")elifmenu_choice!=6:print_menu()

and here is a sample output:

1. Add student2. Remove student3. Print grades4. Record grade5. Print Menu6. ExitMenu Choice (1-6):3       hw ch 1         hw ch 2         quiz            hw ch 3         test #Max    25              25              50              25              100 Menu Choice (1-6):51. Add student2. Remove student3. Print grades4. Record grade5. Print Menu6. ExitMenu Choice (1-6):1Student to add:BillMenu Choice (1-6):4Record GradeStudent:BillType in the number of the grade to recordType a 0 (zero) to exit1   hw ch 1     2   hw ch 2     3   quiz        4   hw ch 3     5   test 0               0               0               0               0 Change which Grade:1Grade:25Change which Grade:2Grade:24Change which Grade:3Grade:45Change which Grade:4Grade:23Change which Grade:5Grade:95Change which Grade:0Menu Choice (1-6):3       hw ch 1         hw ch 2         quiz            hw ch 3         test #Max    25              25              50              25              100Bill    25              24              45              23              95 Menu Choice (1-6):6

Heres how the program works. Basically the variablestudents is a dictionary with the keys being the name of the students and the values being their grades. The first two lines just create two lists.The next linestudents = {'#Max': max_points} creates a newdictionary with the key {#Max} and the value is set to be[25, 25, 50, 25, 100] (since that's whatmax_points was when the assignment is made) (I use the key#Max since# is sorted ahead of any alphabetic characters). Nextprint_menu is defined. Next theprint_all_grades function is defined in thelines:

defprint_all_grades():print('\t',end=" ")foriinrange(len(assignments)):print(assignments[i],'\t',end=" ")print()keys=list(students.keys())keys.sort()forxinkeys:print(x,'\t',end=' ')grades=students[x]print_grades(grades)

Notice how first the keys are gotten out of thestudents dictionary with thekeys function in the linekeys = list(students.keys()).keys is an iterable, and it is converted to list so all the functions for lists can be used on it. Next the keys are sorted in the linekeys.sort().for is used to go through all the keys. The grades are stored as a list inside the dictionary so the assignmentgrades = students[x] givesgrades the list that is stored at the keyx. The functionprint_grades just prints a list and is defined a few lines later.

The later lines of the program implement the various options of the menu. The linestudents[name] = [0] * len(max_points) adds a student to the key of their name. The notation[0] * len(max_points) just creates a list of 0's that is the same length as themax_points list.

The remove student entry just deletes a student similar to the telephone book example. The record grades choice is a little more complex. The grades are retrieved in the linegrades = students[name] gets a reference to the grades of the studentname. A grade is then recorded in the linegrades[which] = grade. You may notice thatgrades is never put back into the students dictionary (as in nostudents[name] = grades). The reason for the missing statement is thatgrades is actually another name forstudents[name] and so changinggrades changesstudent[name].

Dictionaries provide an easy way to link keys to values. This can be used to easily keep track of data that is attached to various keys.

Using a Dictionary to Store Musical Notes

[edit |edit source]

Up to this point, our Linkbot programs have been playing musical notes on the Linkbot either by specifying a specific frequency to play, such as myLinkbot.setBuzzerFrequency(440), or using an equation to calculate the frequency based on a keyboard key number. Wouldn't it be nice if we could just tell the Linkbot to play notes like "Do-Re-Mi", or "A-B-C"?

Perhaps we can use a dictionary to accomplish this task. We can use a dictionary that uses the strings "Do", "Re", "Mi", etc. as keys, and their actual frequencies as values. To find the actual values, we can use an equation or simply look them up online. A quick search shows these frequencies:

Note NameNote Frequency
Do261.63
Re293.66
Mi329.63
Fa349.23
Sol392.00
La440
Ti493.88

Now we can create and use a dictionary to play notes.

importtime# for time.sleep()importbarobodongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('ABCD')# Replace 'ABCD' with your Linkbot's IDdefplayNote(linkbot,note):# 1notes={'Do':261.63,# 2'Re':293.66,'Mi':329.63,'Fa':349.23,'Sol':392.00,'La':440,'Ti':493.88}linkbot.setBuzzerFrequency(notes[note])time.sleep(0.5)linkbot.setBuzzerFrequency(0)mySong=[# 3'Do','Do','Sol','Sol','La','La','Sol','Sol','Fa','Fa','Mi','Mi','Re','Re','Do','Do',]fornoteinmySong:# 4playNote(myLinkbot,note)
  1. Here, we define a helper function that helps us play notes. The function takes a linkbot object and a string note value such as "Do" as input arguments and plays that note on the linkbot for 0.5 seconds.
  2. This is where we create the dictionary that relates note names to note frequencies.
  3. This list defines the notes in a simple song we want to play.
  4. This loop takes each note in the list of notes that we constructed earlier and plays it using ourplayNote() function.
Learning Python 3 with the Linkbot
 ← Boolean ExpressionsPrintable versionUsing Modules → 


Using Modules

Here's this chapter's typing exercise (name it cal.py (import actually looks for a file named calendar.py and reads it in. If the file is named calendar.py and it sees a "import calendar" it tries to read in itself which works poorly at best.)):

importcalendaryear=int(input("Type in the year number: "))calendar.prcal(year)

And here is part of the output I got:

Type in the year number: 2001                                 2001                                         January                  February                    March      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su1  2  3  4  5  6  7                1  2  3  4                1  2  3  4     8  9 10 11 12 13 14       5  6  7  8  9 10 11       5  6  7  8  9 10 1115 16 17 18 19 20 21      12 13 14 15 16 17 18      12 13 14 15 16 17 18     22 23 24 25 26 27 28      19 20 21 22 23 24 25      19 20 21 22 23 24 25     29 30 31                  26 27 28                  26 27 28 29 30 31

(I skipped some of the output, but I think you get the idea.) So what does the program do? The first lineimport calendar uses a new commandimport. The commandimport loads a module (in this case thecalendar module). To see the commands available in the standard modules either look in the library reference for python (if you downloaded it) or go tohttp://docs.python.org/library/. If you look at the documentation for the calendar module, it lists a function calledprcal that prints a calendar for a year. The linecalendar.prcal(year) uses this function. In summary to use a moduleimport it and then usemodule_name.function for functions in the module. Another way to write the program is:

fromcalendarimportprcalyear=int(input("Type in the year number: "))prcal(year)

This version imports a specific function from a module. Here is another program that uses the Python Library (name it something like clock.py) (press Ctrl and the 'c' key at the same time to terminate the program):

fromtimeimporttime,ctimeprev_time=""whileTrue:the_time=ctime(time())ifprev_time!=the_time:print("The time is:",ctime(time()))prev_time=the_time

With some output being:

The time is: Sun Aug 20 13:40:04 2000The time is: Sun Aug 20 13:40:05 2000The time is: Sun Aug 20 13:40:06 2000The time is: Sun Aug 20 13:40:07 2000Traceback (innermost last): File "clock.py", line 5, in ?    the_time = ctime(time())KeyboardInterrupt

The output is infinite of course so I canceled it (or the output at least continues until Ctrl+C is pressed). The program just does a infinite loop (True is always true, sowhile True: goes forever) and each time checks to see if the time has changed and prints it if it has. Notice how multiple names after the import statement are used in the linefrom time import time, ctime.

The Python Library contains many useful functions. These functions give your programs more abilities and many of them can simplify programming in Python.

The following Barobo Linkbot program demonstrates multiple modules that are used to create some fun examples of playing with the Linkbot functionality. Comments have been added to the program to explain what the link is doing as you read. Once again thewhile True: puts the program in an infinite loop that can be exited when Ctrl+C is pressed.

importbarobo#imports the module with the Linkbot commandsimporttime#imports the module to use time.sleepimportrandom#imports a random integer generatordongle=barobo.Dongle()#this block uses the 'barobo' module to connect the Linkbotdongle.connect()#and the dongle that is plugged into the computerrobotID=input('Enter robot ID: ')#prompts user to enter Linkbot IDrobot=dongle.getLinkbot(robotID)defcallback(mask,buttons,data):ifbuttons&0x02:robot.setLEDColor(#calls setLEDColor from 'barobo' modulerandom.randint(0,255),#uses the 'random' integer generator fromrandom.randint(0,255),#the random module to set colorsrandom.randint(0,255))robot.enableButtonCallback(callback)whileTrue:time.sleep(1)#uses the 'time' module to call time.sleep command

Check out the range of colors and intensity the Linkbot is capable of generating with its built in RGB LED.

Exercises

[edit |edit source]

Rewrite thehigh_low.py program from sectionDecisions to use an random integer between 0 and 99 instead of the hard-coded 78. Use the Python documentation to find an appropriate module and function to do this.

Solution

Rewritethe high_low.py program from sectionDecisions to use an random integer between 0 and 99 instead of the hard-coded 78. Use the Python documentation to find an appropriate module and function to do this.

fromrandomimportrandintnumber=randint(0,99)guess=-1whileguess!=number:guess=int(input("Guess a number: "))ifguess>number:print("Too high")elifguess<number:print("Too low")print("Just right")


Learning Python 3 with the Linkbot
 ← DictionariesPrintable versionMore on Lists → 


More on Lists

We have already seen lists and how they can be used. Now that you have some more background I will go into more detail about lists. First we will look at more ways to get at the elements in a list and then we will talk about copying them.

Here are some examples of using indexing to access a single element of a list:

>>>some_numbers = ['zero', 'one', 'two', 'three', 'four', 'five']>>>some_numbers[0]'zero'>>>some_numbers[4]'four'>>>some_numbers[5]'five'

All those examples should look familiar to you. If you want the first item in the list just look at index 0. The second item is index 1 and so on through the list. However what if you want the last item in the list? One way could be to use thelen() function likesome_numbers[len(some_numbers) - 1]. This way works since thelen() function always returns the last index plus one. The second from the last would then besome_numbers[len(some_numbers) - 2]. There is an easier way to do this. In Python the last item is always index -1. The second to the last is index -2 and so on. Here are some more examples:

>>>some_numbers[len(some_numbers) - 1]'five'>>>some_numbers[len(some_numbers) - 2]'four'>>>some_numbers[-1]'five'>>>some_numbers[-2]'four'>>>some_numbers[-6]'zero'

Thus any item in the list can be indexed in two ways: from the front and from the back.

Another useful way to get into parts of lists is using slicing. Here is another example to give you an idea what they can be used for:

>>>things = [0, 'Fred', 2, 'S.P.A.M.', 'Stocking', 42, "Jack", "Jill"]>>>things[0]0>>>things[7]'Jill'>>>things[0:8][0, 'Fred', 2, 'S.P.A.M.', 'Stocking', 42, 'Jack', 'Jill']>>>things[2:4][2, 'S.P.A.M.']>>>things[4:7]['Stocking', 42, 'Jack']>>>things[1:5]['Fred', 2, 'S.P.A.M.', 'Stocking']

Slicing is used to return part of a list. The slicing operator is in the formthings[first_index:last_index]. Slicing cuts the list before thefirst_index and before thelast_index and returns the parts in between. You can use both types of indexing:

>>>things[-4:-2]['Stocking', 42]>>>things[-4]'Stocking'>>>things[-4:6]['Stocking', 42]

Another trick with slicing is the unspecified index. If the first index is not specified the beginning of the list is assumed. If the last index is not specified the whole rest of the list is assumed. Here are some examples:

>>>things[:2][0, 'Fred']>>>things[-2:]['Jack', 'Jill']>>>things[:3][0, 'Fred', 2]>>>things[:-5][0, 'Fred', 2]

Here is a (HTML inspired) program example (copy and paste in the poem definition if you want):

poem=["<B>","Jack","and","Jill","</B>","went","up","the","hill","to","<B>","fetch","a","pail","of","</B>","water.","Jack","fell","<B>","down","and","broke","</B>","his","crown","and","<B>","Jill","came","</B>","tumbling","after"]defget_bolds(text):true=1false=0## is_bold tells whether or not we are currently looking at## a bold section of text.is_bold=false## start_block is the index of the start of either an unbolded## segment of text or a bolded segment.start_block=0forindexinrange(len(text)):## Handle a starting of bold textiftext[index]=="<B>":ifis_bold:print("Error: Extra Bold")## print "Not Bold:", text[start_block:index]is_bold=truestart_block=index+1## Handle end of bold text## Remember that the last number in a slice is the index## after the last index used.iftext[index]=="</B>":ifnotis_bold:print("Error: Extra Close Bold")print("Bold [",start_block,":",index,"]",text[start_block:index])is_bold=falsestart_block=index+1get_bolds(poem)

with the output being:

Bold [ 1 : 4 ] ['Jack', 'and', 'Jill']Bold [ 11 : 15 ] ['fetch', 'a', 'pail', 'of']Bold [ 20 : 23 ] ['down', 'and', 'broke']Bold [ 28 : 30 ] ['Jill', 'came']

Theget_bold() function takes in a list that is broken into words and tokens. The tokens that it looks for are<B> which starts the bold text and</B> which ends bold text. The functionget_bold() goes through and searches for the start and end tokens.

The next feature of lists is copying them. If you try something simple like:

>>>a = [1, 2, 3]>>>b = a>>>print(b)[1, 2, 3]>>>b[1] = 10>>>print(b)[1, 10, 3]>>>print(a)[1, 10, 3]

This probably looks surprising since a modification tobresulted ina being changed as well. What happened is that thestatementb = a makesb areference toa.This means thatb can be thought of as another name fora.Hence any modification tob changesa as well. Howeversome assignments don't create two names for one list:

>>>a = [1, 2, 3]>>>b = a * 2>>>print(a)[1, 2, 3]>>>print(b)[1, 2, 3, 1, 2, 3]>>>a[1] = 10>>>print(a)[1, 10, 3]>>>print(b)[1, 2, 3, 1, 2, 3]

In this caseb is not a reference toa since the expressiona * 2 creates a new list. Then the statementb = a * 2 givesb a reference toa * 2 rather than a reference toa. All assignment operations create a reference.When you pass a list as an argument to a function you create areference as well. Most of the time you don't have to worry aboutcreating references rather than copies. However when you need to makemodifications to one list without changing another name of the listyou have to make sure that you have actually created a copy.

There are several ways to make a copy of a list. The simplest thatworks most of the time is the slice operator since it always makes anew list even if it is a slice of a whole list:

>>>a = [1, 2, 3]>>>b = a[:]>>>b[1] = 10>>>print(a)[1, 2, 3]>>>print(b)[1, 10, 3]

Taking the slice[:] creates a new copy of the list. However it only copies the outer list. Any sublist inside is still a references to the sublist in the original list. Therefore, when the list contains lists, the inner lists have to be copied as well. You could do that manually but Python already contains a module to do it. You use thedeepcopy function of thecopy module:

>>>import copy>>>a = [[1, 2, 3], [4, 5, 6]]>>>b = a[:]>>>c = copy.deepcopy(a)>>>b[0][1] = 10>>>c[1][1] = 12>>>print(a)[[1, 10, 3], [4, 5, 6]]>>>print(b)[[1, 10, 3], [4, 5, 6]]>>>print(c)[[1, 2, 3], [4, 12, 6]]

First of all notice thata is a list of lists. Then noticethat whenb[0][1] = 10 is run botha andb are changed, butc is not. This happens because the inner arrays are still references when the slice operator is used. However withdeepcopyc was fully copied.

So, should I worry about references every time I use a function or=? The good news is that you only have to worry aboutreferences when using dictionaries and lists. Numbers and stringscreate references when assigned but every operation on numbers andstrings that modifies them creates a new copy so you can never modifythem unexpectedly. You do have to think about references when you aremodifying a list or a dictionary.

By now you are probably wondering why are references used at all? Thebasic reason is speed. It is much faster to make a reference to athousand element list than to copy all the elements. The other reasonis that it allows you to have a function to modify the inputted listor dictionary. Just remember about references if you ever have someweird problem with data being changed when it shouldn't be.


Learning Python 3 with the Linkbot
 ← Using ModulesPrintable versionRevenge of the Strings → 


Revenge of the Strings

And now presenting a cool trick that can be done with strings:

defshout(string):forcharacterinstring:print("Gimme a "+character)print("'"+character+"'")shout("Lose")defmiddle(string):print("The middle character is:",string[len(string)//2])middle("abcdefg")middle("The Python Programming Language")middle("Atlanta")

And the output is:

Gimme a L'L'Gimme a o'o'Gimme a s's'Gimme a e'e'The middle character is: dThe middle character is: rThe middle character is: a

What these programs demonstrate is that strings are similar to lists in several ways. Theshout() function shows thatfor loops can be used with strings just as they can be used with lists. Themiddle procedure shows that that strings can also use thelen() function and array indexes and slices. Most list features work on strings as well.

The next feature demonstrates some string specific features:

defto_upper(string):## Converts a string to upper caseupper_case=""forcharacterinstring:if'a'<=character<='z':location=ord(character)-ord('a')new_ascii=location+ord('A')character=chr(new_ascii)upper_case=upper_case+characterreturnupper_caseprint(to_upper("This is Text"))

with the output being:

THIS IS TEXT

This works because the computer represents the characters of a string as numbers from 0 to 1,114,111. For example 'A' is 65, 'B' is 66 and א is 1488. The values are theunicode value. Python has a function calledord() (short for ordinal) that returns a character as a number. There is also a corresponding function calledchr() that converts a number into a character. With this in mind the program should start to be clear. The first detail is the line:if 'a' <= character <= 'z': which checks to see if a letter is lower case. If it is then the next lines are used. First it is converted into a location so that a = 0, b = 1, c = 2 and so on with the line:location = ord(character) - ord('a'). Next the new value is found withnew_ascii = location + ord('A'). This value is converted back to a character that is now upper case. Note that if you really need the upper case of a letter, you should useu=var.upper() which will work with other languages as well.

Now for some interactive typing exercise:

>>># Integer to String>>>22>>>repr(2)'2'>>>-123-123>>>repr(-123)'-123'>>># String to Integer>>>"23"'23'>>>int("23")23>>>"23" * 2'2323'>>>int("23") * 246>>># Float to String>>>1.231.23>>>repr(1.23)'1.23'>>># Float to Integer>>>1.231.23>>>int(1.23)1>>>int(-1.23)-1>>># String to Float>>>float("1.23")1.23>>>"1.23" '1.23'>>>float("123")123.0

If you haven't guessed already the functionrepr() can convert an integer to a string and the functionint() can convert a string to an integer. The functionfloat() can convert a string to a float. Therepr() function returns a printable representation of something. Here are some examples of this:

>>>repr(1)'1'>>>repr(234.14)'234.14'>>>repr([4, 42, 10])'[4, 42, 10]'

Theint() function tries to convert a string (or a float) into an integer. There is also a similar function calledfloat() that will convert a integer or a string into a float. Another function that Python has is theeval() function. Theeval() function takes a string and returns data of the type that python thinks it found. For example:

>>>v = eval('123')>>>print(v, type(v))123 <type 'int'>>>>v = eval('645.123')>>>print(v, type(v))645.123 <type 'float'>>>>v = eval('[1, 2, 3]')>>>print(v, type(v))[1, 2, 3] <type 'list'>

If you use theeval() function you should check that it returns the type that you expect.

One useful string function is thesplit() method. Here's an example:

>>>"This is a bunch of words".split()['This', 'is', 'a', 'bunch', 'of', 'words']>>>text = "First batch, second batch, third, fourth">>>text.split(",")['First batch', ' second batch', ' third', ' fourth']

Notice howsplit() converts a string into a list of strings. The string is split by whitespace by default or by the optional argument (in this case a comma).You can also add another argument that tellssplit() how many times the separator will be used to split the text. For example:

>>>list = text.split(",")>>>len(list)4>>>list[-1]' fourth'>>>list = text.split(",", 2)>>>len(list)3>>>list[-1]' third, fourth'

Slicing strings (and lists)

[edit |edit source]

Strings can be cut into pieces — in the same way as it was shown for lists in the previous chapter — by using theslicing "operator"[]. The slicing operator works in the same way as before: text[first_index:last_index] (in very rare cases there can be another colon and a third argument, as in the example shown below).

In order not to get confused by the index numbers, it is easiest to see them asclipping places, possibilities to cut a string into parts. Here is an example, which shows the clipping places (in yellow) and their index numbers (red and blue) for a simple text string:

012...-2-1
text ="STRING"
[::]

Note that the red indexes are counted from the beginning of the string and the blue ones from the end of the string backwards. (Note that there is no blue -0, which could seem to be logical at the end of the string. Because-0 == 0, -0 means "beginning of the string" as well.) Now we are ready to use the indexes for slicing operations:

text[1:4]"TRI"
text[:5]"STRIN"
text[:-1]"STRIN"
text[-4:]"RING"
text[2]"R"
text[:]"STRING"
text[::-1]"GNIRTS"

text[1:4] gives us all of thetext string between clipping places 1 and 4, "TRI". If you omit one of the [first_index:last_index] arguments, you get the beginning or end of the string as default:text[:5] gives "STRIN". For bothfirst_index andlast_index we can use both the red and the blue numbering schema:text[:-1] gives the same astext[:5], because the index -1 is at the same place as 5 in this case. If we do not use an argument containing a colon, the number is treated in a different way:text[2] gives us one character following the second clipping point, "R". The special slicing operationtext[:] means "from the beginning to the end" and produces a copy of the entire string (or list, as shown in the previous chapter).

Last but not least, the slicing operation can have a second colon and a third argument, which is interpreted as the "step size":text[::-1] istext from beginning to the end, with a step size of -1. -1 means "every character, but in the other direction". "STRING" backwards is "GNIRTS" (test a step length of 2, if you have not got the point here).

All these slicing operations work with lists as well. In that sense strings are just a special case of lists, where the list elements are single characters. Just remember the concept ofclipping places, and the indexes for slicing things will get a lot less confusing.

Examples

[edit |edit source]
# This program requires an excellent understanding of decimal numbers.defto_string(in_int):"""Converts an integer to a string"""out_str=""prefix=""ifin_int<0:prefix="-"in_int=-in_intwhilein_int//10!=0:out_str=str(in_int%10)+out_strin_int=in_int//10out_str=str(in_int%10)+out_strreturnprefix+out_strdefto_int(in_str):"""Converts a string to an integer"""out_num=0ifin_str[0]=="-":multiplier=-1in_str=in_str[1:]else:multiplier=1forcinin_str:out_num=out_num*10+int(c)returnout_num*multiplierprint(to_string(2))print(to_string(23445))print(to_string(-23445))print(to_int("14234"))print(to_int("12345"))print(to_int("-3512"))

The output is:

223445-234451423412345-3512
Learning Python 3 with the Linkbot
 ← More on ListsPrintable versionFile IO → 


File IO

File I/O

[edit |edit source]

Here is a simple example of file I/O (input/output):

# Write a filewithopen("test.txt","wt")asout_file:out_file.write("This Text is going to out file\nLook at it and see!")# Read a filewithopen("test.txt","rt")asin_file:text=in_file.read()print(text)

The output and the contents of the filetest.txt are:

This Text is going to out fileLook at it and see!

Notice that it wrote a file calledtest.txt in the directory that you ran the program from. The\n in the string tells Python to put anewline where it is.

A overview of file I/O is:

  • Get a file object with theopen function
  • Read or write to the file object (depending on how it was opened)
  • If you did not usewith to open the file, you'd have to close it manually

The first step is to get a file object. The way to do this is to use theopen function. The format isfile_object = open(filename, mode) wherefile_object is the variable to put the file object,filename is a string with the filename, andmode is"rt" toread a file astext or"wt" towrite a file astext (and a few others we will skip here). Next the file objects functions can be called. The two most common functions areread andwrite. Thewrite function adds a string to the end of the file. Theread function reads the next thing in the file and returns it as a string. If no argument is given it will return the whole file (as done in the example).

Now here is a new version of the phone numbers program that we made earlier:

defprint_numbers(numbers):print("Telephone Numbers:")fork,vinnumbers.items():print("Name:",k,"\tNumber:",v)print()defadd_number(numbers,name,number):numbers[name]=numberdeflookup_number(numbers,name):ifnameinnumbers:return"The number is "+numbers[name]else:returnname+" was not found"defremove_number(numbers,name):ifnameinnumbers:delnumbers[name]else:print(name," was not found")defload_numbers(numbers,filename):in_file=open(filename,"rt")whileTrue:in_line=in_file.readline()ifnotin_line:breakin_line=in_line[:-1]name,number=in_line.split(",")numbers[name]=numberin_file.close()defsave_numbers(numbers,filename):out_file=open(filename,"wt")fork,vinnumbers.items():out_file.write(k+","+v+"\n")out_file.close()defprint_menu():print('1. Print Phone Numbers')print('2. Add a Phone Number')print('3. Remove a Phone Number')print('4. Lookup a Phone Number')print('5. Load numbers')print('6. Save numbers')print('7. Quit')print()phone_list={}menu_choice=0print_menu()whileTrue:menu_choice=int(input("Type in a number (1-7): "))ifmenu_choice==1:print_numbers(phone_list)elifmenu_choice==2:print("Add Name and Number")name=input("Name: ")phone=input("Number: ")add_number(phone_list,name,phone)elifmenu_choice==3:print("Remove Name and Number")name=input("Name: ")remove_number(phone_list,name)elifmenu_choice==4:print("Lookup Number")name=input("Name: ")print(lookup_number(phone_list,name))elifmenu_choice==5:filename=input("Filename to load: ")load_numbers(phone_list,filename)elifmenu_choice==6:filename=input("Filename to save: ")save_numbers(phone_list,filename)elifmenu_choice==7:breakelse:print_menu()print("Goodbye")

Notice that it now includes saving and loading files. Here is some output of my running it twice:

1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. Load numbers6. Save numbers7. QuitType in a number (1-7):2Add Name and NumberName:JillNumber:1234Type in a number (1-7):2Add Name and NumberName:FredNumber:4321Type in a number (1-7):1Telephone Numbers:Name: Jill     Number: 1234Name: Fred     Number: 4321Type in a number (1-7):6Filename to save:numbers.txtType in a number (1-7):7Goodbye
1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. Load numbers6. Save numbers7. QuitType in a number (1-7):5Filename to load:numbers.txtType in a number (1-7):1Telephone Numbers:Name: Jill     Number: 1234Name: Fred     Number: 4321Type in a number (1-7):7Goodbye

The new portions of this program are:

defload_numbers(numbers,filename):in_file=open(filename,"rt")whileTrue:in_line=in_file.readline()ifnotin_line:breakin_line=in_line[:-1]name,number=in_line.split(",")numbers[name]=numberin_file.close()defsave_numbers(numbers,filename):out_file=open(filename,"wt")fork,vinnumbers.values():out_file.write(k+","+v+"\n")out_file.close()

First we will look at the save portion of the program. First it creates a file object with the commandopen(filename, "wt"). Next it goes through and creates a line for each of the phone numbers with the commandout_file.write(x + "," + numbers[x] + "\n"). This writes out a line that contains the name, a comma, the number and follows it by a newline.

The loading portion is a little more complicated. It starts by getting a file object. Then it uses awhile True: loop to keep looping until abreak statement is encountered. Next it gets a line with the linein_line = in_file.readline(). Thereadline function will return an empty string when the end of the file is reached. Theif statement checks for this andbreaks out of thewhile loop when that happens. Of course if thereadline function did not return the newline at the end of the line there would be no way to tell if an empty string was an empty line or the end of the file so the newline is left in whatreadline returns. Hence we have to get rid of the newline. The linein_line = in_line[:-1] does this for us by dropping the last character. Next the linename, number = in_line.split(",") splits the line at the comma into a name and a number. This is then added to thenumbers dictionary.

Advanced use of .txt files

[edit |edit source]

You might be saying to yourself, "Well I know how to read and write to a textfile, but what if I want to print the file without opening out another program?"

There are a few different ways to accomplish this. The easiest way does open another program, but everything is taken care of in the Python code, and doesn't require the user to specify a file to be printed. This method involves invoking the subprocess of another program.

Remember the file we wrote output to in the above program? Let's use that file. Keep in mind, in order to prevent some errors, this program uses concepts from the Next chapter. Please feel free to revisit this example after the next chapter.

importsubprocessdefmain():try:print("This small program invokes the print function in the Notepad application")#Lets print the file we created in the program abovesubprocess.call(['notepad','/p','numbers.txt'])exceptWindowsError:print("The called subprocess does not exist, or cannot be called.")main()

Thesubprocess.call takes three arguments. The first argument in the context of this example, should be the name of the program which you would like to invoke the printing subprocess from. The second argument should be the specific subprocess within that program. For simplicity, just understand that in this program,'/p' is the subprocess used to access your printer through the specified application. The last argument should be the name of the file you want to send to the printing subprocess. In this case, it is the same file used earlier in this chapter.

Storing and loading music saved in a text file

[edit |edit source]

This section will demonstrate how we can store simple melodies in a file. We can then write a program that reads the file and plays the melody on a Linkbot.

A little music theory

[edit |edit source]

To fully understand the sample program, we will need a little knowledge about music theory. If you don't care about music theory and you just want to get the Linkbot to play music, you can skip to the next section.

What is music? Music is a series of notes played in a certain order. Sometimes, more than one note is played together. Each note is played for a certain duration. Notes themselves are vibrations in the air that we can hear. Each note has a certain frequency of vibration; when the frequency changes, the perceived pitch of the note changes too.

Each note has a name. If you know it's name, you can find it on a piano keyboard, and vice versa. You may have heard the term "Middle-C", or the phrase "Do-Re-Mi". These are both ways to refer to notes. If you are familiar with a piano keyboard, you will know that the "C" note appears more than once on the keyboard. When you play the C notes, you'll notice that they don't sound the same, but they are all called "C". It turns out that there are 12 tones that repeat over and over again. Starting at C, they are:

  • C
  • C# (Db)
  • D
  • D# (Eb)
  • E
  • F
  • F# (Gb)
  • G
  • G# (Ab)
  • A
  • A# (Bb)
  • B

The "#" symbol is pronounced "sharp", so C# is pronounced "See-Sharp". The "sharp" indicates that the tone is one step higher than the normal note. For instance, "A#" is one step higher than "A". You might also be familiar with another symbol that looks like a lowercase b. That symbol is pronounced "flat", so "Bb" is pronounced "B-flat". It has the opposite meaning of sharp, indicating that the note is one step lower than the un-flatted note. This means that the note "G#" is actually the same note as "Ab". For now, we will only use sharps to avoid confusion. On a piano keyboard, all of the sharp/flat notes are the black keys and the rest of the notes are the white keys.

On a piano keyboard, these notes repeat over and over again, so we must devise a way to specifically refer which A or B or C we are referring to. To do this, we introduce the concept of an octave number. The lowest note a piano can play is called "A0", where 0 is the octave number. Going from left to right on a piano keyboard, the octave number increases every time you encounter the C note. Thus, the first several white keys on a piano keyboard from left to right are:

  • A0
  • B0
  • C1
  • D1
  • E1
  • F1
  • G1
  • A1
  • B1
  • C2
  • etc...

Now, we have a way to specifyexactly what key on a keyboard we are referring to using a string such as "F#5".

We also have an equation where we can calculate the frequency of a note depending on how many steps away it is from our "A0" note.The equation is:

frequency=27.52steps/12{\displaystyle \mathrm {frequency} =27.5*2^{\mathrm {steps} /12}}

For instance, G0 is -2 steps away from A0, and B0 is 2 steps away from A0. For notes in the same octave, we can simply count the number of black and white keys to find the distance away from A, but how about different octaves? For instance, how many keys away is A0 from B4?

First, lets consider how many notes away A4 is from A0. When we count the keys, each octave is 12 notes. Since A4 is 4 octave away from 0 (4-0 = 4), A4 is 4*12=48 keys away from A0.

How about A0 and B4? A0 is 2 keys away from B0, and B0 is 4*12 keys away from B4, so in total, A0 is 2+4*12 = 50 keys away from B4. Now, we can write an equation to figure out exactly how many keys away any note is from A0. Lets use the variablen{\displaystyle n} for the note name we want, andv{\displaystyle v} for the octave of the note. Then,

offset(n,v)=n(A0)+12v{\displaystyle \mathrm {offset} (n,v)=n-\mathrm {(} A0)+12*v}

Reading and playing a melody from a file

[edit |edit source]

First, let us write a function that takes a string describing a note such as "A4" and gives us a frequency for that note. Here is our strategy:

  • We receive a string describing the note. The first character is the letter name of the note. We calculate the offset of that letter name from the "A" note. For instance, "B" would have an offset of +2 and "E" would have an offset of -5. We find these offsets simply by counting the keys on a keyboard.
  • The next character in the string might be a "#" sharp or a "b" flat. If it is sharp, increase the offset by one. If it is flat, decrease it by one. If it is neither, don't do anything.
  • The final character is the octave number. We multiply this number by 12 and add it to our offset.
  • The result is the number of keys away the note is away from A0. We can now use the equationf=27.52offset/12{\displaystyle f=27.5*2^{\mathrm {offset} /12}} to find the frequency based on the key offset from A0.

Next, lets talk about our file format. Since the Linkbot can only play one note at a time, the file should specify single notes for the Linkbot to play. Also, the file should specify how many seconds to play each note. We choose to have our file such that each line contains a note name such as "C4" or "Bb3", along with a note duration in seconds.

Here is a file that we have created for you:

fur_elise.txt

E5  0.125                                                                        D#5 0.125                                                                        E5  0.125                                                                        D#5 0.125                                                                        E5  0.125                                                                        B4  0.125                                                                        D5  0.125                                                                        C5  0.125                                                                        A4  0.375                                                                        C4  0.125                                                                        E4  0.125                                                                        A4  0.125                                                                        B4  0.375                                                                        G#3 0.125                                                                        G#4 0.125                                                                        B4  0.125                                                                        C5  0.375                                                                        E4  0.125                                                                        E5  0.125                                                                        D#5 0.125                                                                        E5  0.125                                                                        D#5 0.125                                                                        E5  0.125                                                                        B4  0.125                                                                        D5  0.125                                                                        C5  0.125                                                                        A4  0.375                                                                        C4  0.125                                                                        E4  0.125                                                                        A4  0.125                                                                        B4  0.375                                                                        E4  0.125                                                                        C5  0.125                                                                        B4  0.125                                                                        A4  0.375

Go ahead and copy-paste the text into a file called "fur_elise.txt". Lets write our function and program that will read this file and play a tune.

importtimeimportbarobodongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot()defnoteToFreq(note):# First, we need to figure out where the note is relative to 'A'.# For instance, 'B' is 2 half-steps above A, 'C' is 9 half-steps# below 'A'. Lets create a dictionary called "note-offset" and store# all of our offsets from A in the dictionary.noteOffsets={'C':-9,'D':-7,'E':-5,'F':-4,'G':-2,'A':0,'B':2}# Find our offsetoffset=noteOffsets[note[0].upper()]# 1# See if there is a sharp or flatifnote[1]=='#':offset+=1elifnote[1]=='b':offset-=1# Calculate the offset based on the octaveoctave=int(note[-1])# 2offset+=(octave)*12# Calculate the note frequencyfreq=2**((offset)/12)*27.5returnfreqmusicFile=open('fur_elise.txt','r')forlineinmusicFile:# 3data=line.split()# 4myLinkbot.setBuzzerFrequency(noteToFreq(data[0]))time.sleep(float(data[1]))myLinkbot.setBuzzerFrequency(0)
  1. note[0].upper() takes the first character and uppercases it. We want to uppercase anything that comes in just in case the user used a lowercase note name, like "e4". Since we wrote our dictionary with uppercase note names, we need to make sure the incoming note names are upper-case too so that it can be matched with the ones in our dictionary.
  2. The "-1" index means the last item of a list. Since all of the items in our list are strings, we need to convert it to an integer withint.
  3. This loop goes through every single line in the music file, line by line. Each time, it stores the text of the line in theline variable.
  4. Thesplit() function splits lines of text based on whitespace. For instance,"Hello there".split() becomes the list ["Hello", "there"]. Since each line in our text file has 2 "words", the first part (the note name) is stored into our variabledata[0], and the second part (the note duration) is stored intodata[1].

Exercises

[edit |edit source]

Now modify the grades program from sectionDictionaries so that is uses file I/O to keep a record of the students.

Solution

Now modify the grades program from sectionDictionaries so that is uses file I/O to keep a record of the students.

assignments=['hw ch 1','hw ch 2','quiz   ','hw ch 3','test']students={}defload_grades(gradesfile):inputfile=open(gradesfile,"r")grades=[]whileTrue:student_and_grade=inputfile.readline()student_and_grade=student_and_grade[:-1]ifnotstudent_and_grade:breakelse:studentname,studentgrades=student_and_grade.split(",")studentgrades=studentgrades.split(" ")students[studentname]=studentgradesinputfile.close()print("Grades loaded.")defsave_grades(gradesfile):outputfile=open(gradesfile,"w")fork,vinstudents.values():outputfile.write(k+",")forxinv:outputfile.write(x+" ")outputfile.write("\n")outputfile.close()print("Grades saved.")defprint_menu():print("1. Add student")print("2. Remove student")print("3. Load grades")print("4. Record grade")print("5. Print grades")print("6. Save grades")print("7. Print Menu")print("9. Quit")defprint_all_grades():ifstudents:keys=sorted(students.keys())print('\t',end=' ')forxinassignments:print(x,'\t',end=' ')print()forxinkeys:print(x,'\t',end=' ')grades=students[x]print_grades(grades)else:print("There are no grades to print.")defprint_grades(grades):forxingrades:print(x,'\t',end=' ')print()print_menu()menu_choice=0whilemenu_choice!=9:print()menu_choice=int(input("Menu Choice: "))ifmenu_choice==1:name=input("Student to add: ")students[name]=[0]*len(assignments)elifmenu_choice==2:name=input("Student to remove: ")ifnameinstudents:delstudents[name]else:print("Student:",name,"not found")elifmenu_choice==3:gradesfile=input("Load grades from which file? ")load_grades(gradesfile)elifmenu_choice==4:print("Record Grade")name=input("Student: ")ifnameinstudents:grades=students[name]print("Type in the number of the grade to record")print("Type a 0 (zero) to exit")fori,xinenumerate(assignments):print(i+1,x,'\t',end=' ')print()print_grades(grades)which=1234whilewhich!=-1:which=int(input("Change which Grade: "))which-=1if0<=which<len(grades):grade=input("Grade: ")# Change from float(input()) to input() to avoid an error when savinggrades[which]=gradeelifwhich!=-1:print("Invalid Grade Number")else:print("Student not found")elifmenu_choice==5:print_all_grades()elifmenu_choice==6:gradesfile=input("Save grades to which file? ")save_grades(gradesfile)elifmenu_choice!=9:print_menu()


Write a program that reads a text file containing motor angles, such as

90 45 20180 22 -1805 32 0

Each triplet of numbers represents three motor angles. Write a program that moves the Linkbot's joints to those positions with themoveTo() function for each line in the data file.

Learning Python 3 with the Linkbot
 ← Revenge of the StringsPrintable versionDealing with the imperfect → 


Dealing with the imperfect

...or how to handle errors

[edit |edit source]

closing files with with

[edit |edit source]

We use the "with" statement to open and close files.[1][2]

withopen("in_test.txt","rt")asin_file:withopen("out_test.txt","wt")asout_file:text=in_file.read()data=parse(text)results=encode(data)out_file.write(results)print("All done.")

If some sort of error happens anywhere in this code(one of the files is inaccessible,the parse() function chokes on corrupt data,etc.)the "with" statements guarantee that all the files will eventually be properly closed. Closing a file just means that the file is "cleaned up" and "released" by our program so that it can be used in another program.


Clipboard

To do:
Is the "closing files with with" section too much detail for a non-programmers tutorial?If so, move it to some other Python Wikibook (Subject:Python programming language)


catching errors with try

[edit |edit source]

So you now have the perfect program, it runs flawlessly, except for one detail, it will crash on invalid user input. Have no fear, for Python has a special control structure for you. It's calledtry and it tries to do something. Here is an example of a program with a problem:

print("Type Control C or -1 to exit")number=1whilenumber!=-1:number=int(input("Enter a number: "))print("You entered:",number)

Notice how when you enter@#& it outputs something like:

Traceback (most recent call last): File "try_less.py", line 4, in <module>   number = int(input("Enter a number: "))ValueError: invalid literal for int() with base 10: '\\@#&'

As you can see theint() function is unhappy with the number@#& (as well it should be). The last line shows what the problem is; Python found aValueError. How can our program deal with this? What we do is first: put the place where errors may occur in atry block, and second: tell Python how we wantValueErrors handled. The following program does this:

print("Type Control C or -1 to exit")number=1whilenumber!=-1:try:number=int(input("Enter a number: "))print("You entered:",number)exceptValueError:print("That was not a number.")

Now when we run the new program and give it@#& it tells us "That was not a number." and continues with what it was doing before.

When your program keeps having some error that you know how to handle, put code in atry block, and put the way to handle the error in theexcept block.

Generating Errors: Controlling a Linkbot's Speed

[edit |edit source]

We've seen in previous examples that we can write a function that makes a wheeled robot travel a certain distance. We can also control the rotational velocity of the motors with thesetJointSpeed() function. ThesetJointSpeed() function expects a rotational speed with units of degrees/sec, but it would be nice if we could have a function where we could set the robot speed using inches/sec. The math equation to convertv{\displaystyle v} inches/sec toω{\displaystyle \omega } degrees/sec is

ω(deg/sec)=v(inches/sec)r(inches)180(degrees)π(radians){\displaystyle \omega \mathrm {(deg/sec)} ={\frac {v\mathrm {(inches/sec)} }{r\mathrm {(inches)} }}*{\frac {180\mathrm {(degrees)} }{\pi \mathrm {(radians)} }}}

wherer{\displaystyle r} is the wheel radius. Lets expand our example from theLearning Python 3 with the Linkbot/Defining Functions section:

Template:Message box

importbaroboimportmath# So that we can use math.pidongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('abcd')# Change abcd to your Linkbot's serial IDdefdriveDistance(linkbot,distance):r=3.5/2# If you have a wheel that's not 3.5 inches in diameter, change "3.5" to the diameter of your wheeldegrees=(360)/(2*math.pi*r)*distancelinkbot.move(degrees,0,-degrees)defsetSpeed(linkbot,speed):r=3.5/2omega=(speed/r)*(180/math.pi)linkbot.setJointSpeed(1,omega)linkbot.setJointSpeed(3,omega)setSpeed(myLinkbot,2.5)# Sets the speed to 2.5 inches/secdriveDistance(myLinkbot,10)# Drives the Linkbot 10 inches forwarddriveDistance(myLinkbot,-5)# Drives the Linkbot 5 inches backward

This example is all well and good. We define a new functionsetSpeed() that sets the speed of a Linkbot wheeled vehicle and we use it to set the speed to 2.5 inches per second.

What if the programmer tries to set the speed to 1,000 inches/second? Or 1,000,000 inches/second? Although it would be cool to see a Linkbot compete with a Formula One race car, there are physical limitations that prevent the Linkbot's motors from moving more than 200 degrees/second. If the speed is too high, we should set an error the user can see and possibly deal with. This is called "raising an exception". The code to raise an exception looks like this:

defsetSpeed(linkbot,speed):r=3.5/2omega=(speed/r)*(180/math.pi)ifomega>200:raiseException('The speed is too high!')linkbot.setJointSpeed(1,omega)linkbot.setJointSpeed(3,omega)

When an exception is raised, the function immediately returns with the exception. These raised exceptions can be caught by try/except blocks. If the exception occurred outside of a try/except block, the entire program will quit and display the error message of the exception. In thesetSpeed() function, this means that if theraise is executed, the twosetJointSpeed() statements will be skipped.

When I run the new program and I try to set the speed to 1000 inches a second, I get this output:

Traceback (most recent call last):  File "./linkbot_speed.py", line 20, in <module>    setSpeed(myLinkbot, 1000)     # Sets the speed to 1000 inches/sec  File "./linkbot_speed.py", line 16, in setSpeed    raise Exception('The speed is too high!')Exception: The speed is too high!

Now you can use try/catch blocks to deal with possible errors. Lets try writing a program that tries to set the speed to 10 inches per second again, except every time it encounters an exception, in reduces the requested speed by 1 inch/second and tries again.

importbaroboimportmath# So that we can use math.pidongle=barobo.Dongle()dongle.connect()myLinkbot=dongle.getLinkbot('ABCD')# Change ABCD to your Linkbot's serial IDdefdriveDistance(linkbot,distance):r=3.5/2# If you have a wheel that's not 3.5 inches in diameter, change "3.5" to the diameter of your wheeldegrees=(360)/(2*math.pi*r)*distancelinkbot.move(degrees,0,-degrees)defsetSpeed(linkbot,speed):r=3.5/2omega=(speed/r)*(180/math.pi)ifomega>200:raiseException('The speed is too high!')linkbot.setJointSpeed(1,omega)linkbot.setJointSpeed(3,omega)requestedSpeed=10# 1whileTrue:# 2try:print('Trying to set speed to: '+str(requestedSpeed)+'inches/sec')setSpeed(myLinkbot,requestedSpeed)# 3print('Success!')break# 4except:print('Failed.')requestedSpeed-=1# 5# 6driveDistance(myLinkbot,10)# Drives the Linkbot 10 inches forwarddriveDistance(myLinkbot,-5)# Drives the Linkbot 5 inches backward

The output is

Trying to set speed to: 10inches/secFailed.Trying to set speed to: 9inches/secFailed.Trying to set speed to: 8inches/secFailed.Trying to set speed to: 7inches/secFailed.Trying to set speed to: 6inches/secSuccess!

Lets step through this program together to make sure we fully understand what is happening.

  • # 1 : When we first get to this line, we create a new variable calledrequestedSpeed and set its value to "10".
  • # 2 : Enter an infinite loop
  • # 3 : Try to set the speed.requestedSpeed is currently 10, which is too high. ThesetSpeed() function raises an exception. Since we are in a try/except block, we immediately go to the except block since an exception was thrown. Proceed to # 5
  • # 5 : DecreaserequestedSpeed by one.requestedSpeed is now 9. This is the end of ourwhile loop, which means that Python goes back to the beginning of the loop.
  • # 3 : We end up at # 3 again, exceptrequestedSpeed is now 9. Still too high, exception is thrown.
  • # 5 : Again, we decreaserequestedSpeed to 8.
  • # 3 : Still too high...
  • # 5 : Reduce to 7...
  • # 3 : Still too high...
  • # 5 : Reduce to 6.
  • # 3 : Now it succeeds. Since it succeeded, no exception was raised. Continue to # 4
  • # 4 : Thisbreak statement pops us out of the loop. Proceed to # 6 and the rest of the program.

Exercises

[edit |edit source]

Update at least the phone numbers program (in sectionDictionaries) so it doesn't crash if a user doesn't enter any data at the menu.

Learning Python 3 with the Linkbot
 ← File IOPrintable versionRecursion → 


Recursion

Recursion

[edit |edit source]

In Python, a recursive function is a function which calls itself.

Introduction to recursion

[edit |edit source]

So far, in Python, we have seen functions which call other functions. However, it is possible for a function to call itself. Lets look at a simple example.

# Program by Mitchell Aikens# No Copyright# 2010num=0defmain():counter(num)defcounter(num):print(num)num+=1counter(num)main()

If you were to run this program in IDLE, it would run forever. The only way to stop the loop would be to interrupt the execution by pressing Ctrl + C on your keyboard. This is an example of an infinite recursion. (Some users have reported a glitch in the current IDLE system causing the exception raised by Ctrl + C to start looping as well. If this happens, press Ctrl + F6, and the IDLE shell should restart.)

It is arguable that recursion is just another way to accomplish the same thing as a while loop. In some cases, this is absolutely correct. Though, there are other uses for Recursion that are very valid, wherewhile loops orfor loops may not be optimal.

Recursion can be controlled, just like loops. Lets look at an example of a controlled loop.

# Program by Mitchell Aikens# No copyright# 2012defmain():loopnum=int(input("How many times would you like to loop?\n"))counter=1recurr(loopnum,counter)defrecurr(loopnum,counter):ifloopnum>0:print("This is loop iteration",counter)recurr(loopnum-1,counter+1)else:print("The loop is complete.")main()

The above uses arguments/parameters to control the number of recursions. Simply use what you already know about functions and follow the flow of the program. It is simple to figure out. If you are having trouble, please refer back toNon-Programmer's Tutorial for Python 3/Advanced Functions Example.

Practical Applications of Recursion

[edit |edit source]

Often, recursion is studied at an advanced computer science level. Recursion is usually used to solve complex problems, that can be broken down into smaller, identical problems.Recursion isn't required to solve a problem. Problems that can be solved with recursion, most likely can be solved with loops. Also, a loop may be more efficient than a recursive function. Recursive functions require more memory, and resources than loops, making them less efficient in a lot of cases. This usage requirement is sometimes referred to asoverhead.You might be thinking, "Well why bother with recursion. I'll just use a loop. I already know how to loop and this is a lot more work." This thought is understandable, but not entirely ideal. When solving complex problems, a recursive function is sometimes easier, faster, and simpler to build and code.

Think of these two "rules":

  • If I can solve the problem now, without recursion, the function simply returns a value.
  • If I cannot solve the problem now without recursion, the function reduces the problem to something smaller and similar, and calls itself to solve the problem.

Let's apply this using a common mathematical concept, factorials. If you are unfamiliar with factorials in mathematics, please refer to the following reading.Factorials

The factorial of a numbern, is denoted asn!.

Here are some basic rules of factorials.

If n = 0 then n! = 1If n > 0 then n! = 1 x 2 x 3 x ... x n

For example, let's look at the factorial of the number 9.

9! = 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9

Let's look at a program which calculates the factorial of any number entered by the user, by method of recursion.

defmain():num=int(input("Please enter a non-negative integer.\n"))fact=factorial(num)print("The factorial of",num,"is",fact)deffactorial(num):ifnum==0:return1else:returnnum*factorial(num-1)main()

Recursion is also useful in an advanced topic called generators. To generate the series 1,2,1,3,1,2,1,4,1,2... we would need this code:

defcrazy(min_):yieldmin_g=crazy(min_+1)whileTrue:yieldnext(g)yieldmin_i=crazy(1)

to get the next element you would call next(i)

Learning Python 3 with the Linkbot
 ← Dealing with the imperfectPrintable versionIntro to Object Oriented Programming in Python 3 → 


Intro to Object Oriented Programming in Python 3

Object Oriented Programming

[edit |edit source]
Up until now, the programming you have been doing has been procedural. However, a lot of programs today are Object Oriented. Knowing both types, and knowing the difference, is very important. Many important languages in computer science such as C++ and Java, often use OOP methods.
Beginners, and non-programmers often find the concept of OOP confusing, and complicated. This is normal. Don't be put off if you struggle or do not understand. There are plenty of other resources you can use to help overcome any issues you may have, if this chapter does not help you.
This chapter will be broken up into different lessons. Each lesson will explain OOP in a different way, just to make sure OOP is covered as thoroughly as possible, becauseIT IS VERY IMPORTANT. Before the lessons, there is an introduction which explains key concepts, terms, and other important areas of OOP, required to understand each lesson.

Introduction

[edit |edit source]

Think of a procedure as a function. A function has a specific purpose. That purpose may be gathering input, performing mathematical calculations, displaying data, or manipulating data to, from, or in, a file. Typically, procedures use data which is separate from code for manipulation. This data is often passed between procedures. When a program becomes much larger and complex, this can cause problems.For example, you have designed a program which stores information about a product in variables. When a customer requests information on a product, these variables are passed to different functions for different purposes. Later on, as more data is stored on these products, you decide to store the information in a list or dictionary. In order for your program to function, you must now edit each function that accepted variables, to now accept and manipulate a list or dictionary. Imagine the time that would take for a program that was hundreds of megabytes, and hundreds of files in size! It would drive you insane! not to mention, errors in your code, are almost guaranteed, just because of the large volume of work and possibilities to make a typo or other error. This is less than optimal.Procedural programming is centered on procedures or functions. But, OOP is centered on creating Objects. Remember how a procedural program has separated data and code? Remember how that huge program was hundreds of files and would take FOREVER to edit? Well, think of anobject as a sort of "combination" of those files and data into one "being". In a technical sense, an Object is an entity which contains data, AND procedures (code, functions, etc.).

Data inside an object is called adata attribute.

Functions, or procedures inside the object are calledmethods.


Think ofdata attributes as variables.

Think ofmethods as functions or procedures.

Let's look at a simple, everyday example. The light and light switch in your bedroom.The data attributes would be as follows.

  • light_on (True or False)
  • switch_position (Up or Down)
  • electricity_flow (True or False)

The methods would be as follows.

  • move_switch
  • change_electricity_flow

The data attributes may or may not be visible. For example, you cannot directly see the electricity flowing to the light. You only know there is electricity, because the light is on. However, you can see the position of the switch (switch_position), and you can see if the light is on or off (light_on). Some methods areprivate. This means that you cannot directly change them. For example, unless you cut the wires in your light fixture (please don't do that, and for the sake of this example, assume that you don't know the wires exist), you cannot change the flow of electricity directly. You also cannot directly change if the light is on or off (and no, you can't unscrew the bulb! work with me here!). However, you can indirectly change these attributes by using themethods in the object. If you don't pay your bill, thechange_electricity_flow method will change the value of theelectricity_flow attribute to FALSE. If you flip the switch, themove_switch method changes the value of thelight_on attribute.

By now you're probably thinking, "What does this have to do with Python?" or, "I understand, but how do I code an Object?" Well, we are almost to that point! One more concept must be explained before we can dive into code.

In Python, an object's data attributes and methods are specified by aclass. Think of a class as a blueprint to an object. For example, your home - the object that you live in - you can also call it your pad, bungalow, crib, or whatever, was built based on a set of blueprints; these blueprints would be considered the class used to design your home, pad, crib, ahem, you get the idea.

Again, a class tells us how to make an object. In technical terms, and this is important here, a class defines the data attributes and methods inside an object.

To create a class, we code aclass definition. A class definition is a group of statements which define an object's data attributes and methods.

Lesson One

Below is a Procedural program that performs simple math on a single number, entered by a user.

# Program by Mitchell Aikens# No Copyright# 2012# Procedure 1defmain():try:# Get a number to maniuplatenum=float(input("Please enter a number to manipulate.\n"))# Store the result of the value, after it has been manipulated# by Procedure 2addednum=addfive(num)# Store the result of the value, after it has been manipulated# by Procedure 3multipliednum=multiply(addednum)# Send the value to Procedure 4display(multipliednum)# Deal with exceptions from non-numeric user entryexceptValueError:print("You must enter a valid number.\n")# Reset the value of num, to clear non-numeric data.num=0# Call main, again.main()# Procedure 2defaddfive(num):returnnum+5# Procedure 3defmultiply(addednum):returnaddednum*2.452# Procedure 4defdisplay(multi):# Display the final valueprint("The final value is ",multi)# Call Procedure 1main()

If we were to enter a value of "5", the output would be as shown below.

Please enter a number to manipulate.5The final value is  24.52

If we were to enter a value of "g", and then correct the input and enter a value of "8", the output would be as shown below.

Please enter a number to manipulate.gYou must enter a valid number.Please enter a number to manipulate.8The final value is  31.875999999999998

Below, is a Class, and a program which uses that class. This Object Oriented Program does the same thing as the procedural program above. Let's cover some important OOP coding concepts before we dive into the Class and program. To create a class, we use theclass keyword. After the keyword, you type the name you want to name your class. It is common practice that the name of your class is capitalized.If I wanted to create a class named dirtysocks, the code would be:

classDirtysocks

The Class is shown first. The program which uses the class is second.

# Filename: oopexample.py# Mitchell Aikens# No Copyright# 2012# OOP Demonstration - ClassclassNumchange:def__init__(self):self.__number=0defaddfive(self,num):self.__number=numreturnself.__number+5defmultiply(self,added):self.__added=addedreturnself.__added*2.452

The program which uses the class above, is below.

# Filename: oopexampleprog.py# Mitchell Aikens# No Copyright# 2012# OOP Demonstration - Programimportoopexamplemaths=oopexample.Numchange()defmain():num=float(input("Please enter a number.\n"))added=maths.addfive(num)multip=maths.multiply(added)print("The manipulated value is ",multip)main()

After looking at that program, you are probably a bit lost. That's OK. Lets start off by dissecting the class.The class is named "Numchange"There are three methods to this class:

  • __init__
  • addfive
  • multiply

These three methods each have a similar code.

def__init__(self):defaddfive(self,num):defmultiply(self,added):

Notice how each method has a parameter named "self". this parameter must be present in each method of the class. This parameter doesn't HAVE TO be called "self", but it is standard practice, which means you should probably stick with it. This parameter is required in each method because when a method executes, it has to know which object's attributes to operate on. Even though there is only one Object, we still need to make sure the interpreter knows that we want to use the data attributes in that class. So we play it safe...and use the "self" parameter.

Lets look at the first method.

def__init__(self):

Most Classes in python have an__init__ which executes automatically when an instance of a class is created in memory.(When we reference a class, aninstance (or object)of that class is created). This method is commonly referred to as theinitializer method. When the method executes, the "self" parameter is automatically assigned to the object. This method is called the initializer method because is "initializes" the data attributes. Under the __init__ method, we set the value of thenumber method to 0 initially.We reference the object attribute using dot notation.

def__init__(self):self.__number=0

Theself.__number = 0 line simply means ""the value of the attribute "number", in the object, is 0"".

Let's look at the next method.

defaddfive(self,num):self.__number=numreturnself.__number+5

This method is named "addfive. It accepts a parameter called "num", from the program using the class. The method then assigns the value of that parameter to the "number" attribute inside the object. The method then returns the value of "number", with 5 added to it, to the statement which called the method.

Let's look at the third method.

defmultiply(self,added):self.__added=addedreturnself.__added*2.453

This method is named "multiply". It accepts a parameter named "added". It assigns the value of the parameter to the "added" attribute, and returns the value of the "added" attribute multiplied by 2.452, to the statement which called the method.

Notice how the name of each method begins with two underscores? Let's explain that.Earlier we mentioned that an object operates on data attributes inside itself using methods. Ideally, these data attributes should be able to be manipulated ONLY BY METHODS IN THE OBJECT. It is possible to have outside code manipulate data attributes. To "hide" attributes, so only methods in the object can manipulate them, you use two underscores before the object name, as we have been demonstrating. Omitting those two underscores in the attribute name, allows for the possibility of manipulation from code outside the object.

Lets look at the program which uses the class we just dissected.

Notice the first line of non comment code.

importoopexample

This line of code imports the class, which we have saved in a separate file (module). Classes do not have to be in a separate file, but it is almost always the case, and thus is good practice to get used to importing the module now.

The next line:

maths=oopexample.Numchange()

This line creates an instance of the Numchange class, stored in the module named "oopexample", and stores the instance in the variable named "maths".The syntax is:modulename.Classname()Next we define the main function.Then, we get a number from the user.

The next lineadded = maths.addfive(num) sends the value of the "num" variable to the method named "addfive", which is part of the class we stored an instance of in the variable named "maths", and stores the returned value in the variable named "added".

The next linemultip = maths.multiply(added) sends the value of the variable "added", to the method named "multiply", which is part of the class we stored an instance of in the variable named "maths", and stores the returned value in the variable named "multip".

The next line prints "The manipulated value is <value of multip>". The last line calls the main function which executes the steps outlined above.

Object Oriented Inheritance: Extending the Linkbot Class

[edit |edit source]

Throughout all of our code examples, you've been seeing these lines of code over and over again:

...myLinkbot=dongle.getLinkbot('ABCD')...myLinkbot.move()# etc etc

If you guessed that themyLinkbot variable is actually a Python object, you are correct! ThegetLinkbot() function returns an object of theLinkbot class, which is defined inside of thebarobo package. An extremely powerful and important concept that object-oriented languages use is a concept called "inheritance". Sometimes, a programmer may want to create a new object that is very similar to or related to objects that have already been written.

For instance, theLinkbot class contains a variety of functions that move the motors, beeps the buzzer, etc. However, it would be nice if I could write my own object for controlling a Linkbot-I that has 2 wheels and a caster attached. I could call the new object "LinkbotCar", and it could have member functions that make it drive forward, drive backward, turn, etc. At the same time, I still want theLinkbotCar class to do everything that the originalLinkbot class did, such as changing LED colors and beeping the buzzer. Furthermore, it would be nice if the programmer didn't have to re-implement all of those methods that already exist inside theLinkbot class.

The solution to this situation is to write ourLinkbotCar class such that it "extends", "inherits from", or "derives from" (all of these terms are more-or-less interchangeable) the originalLinkbot class. Lets start by a quick example. Here is a program that creates a newLinkbotCar class based on the originalLinkbot class, makes a new function calleddriveForwardDistance which drives the wheeled robot forward a certain distance, and then beeps the buzzer for half a second.

importbaroboimportmath# for math.piimporttime# for time.sleep()classLinkbotCar(barobo.Linkbot):# 1defdriveForwardDistance(self,inches):# 2wheelRadius=3.5/2.0degrees=(360.0/(2.0*math.pi*wheelRadius))*inchesself.move(degrees,0,-degrees)# 3dongle=barobo.Dongle()dongle.connect()myLinkbotCar=dongle.getLinkbot('ABCD',LinkbotCar)# 4myLinkbotCar.driveForwardDistance(5)# 5myLinkbotCar.setBuzzerFrequency(440)# 6time.sleep(0.5)myLinkbotCar.setBuzzerFrequency(0)
  1. This line begins the process of making a new class called "LinkbotCar" based on the existing class "barobo.Linkbot".
  2. Here, we define a new function called "driveForwardDistance" for the LinkbotCar class. The first argument for member functions represents the object itself. Although you can name this first variable whatever you want, all Python programmers use the name "self" by convention. The second argument is the number of inches we want the robot to travel.
  3. This is the line that actually makes the Linkbot move. Notice that we use themove() function on theself variable here.
  4. Here, we gain control of the Linkbot through the dongle. Notice that the format of this function call is slightly different from what we've seen before. Not only is the requested Linkbot ID 'ABCD' specified, we also specify that we want a "LinkbotCar" object instead of a vanilla "Linkbot" object. Vanilla "Linkbot" objects do not have the newdriveForwardDistance member function that we just defined.
  5. At this line, we actually use our new function that we defined above. This makes the robot represented by the variablemyLinkbotCar drive forward 5 inches.
  6. Next, we make the Linkbot beep its buzzer. Notice thatsetBuzzerFrequency() was originally a function inside thebarobo.Linkbot class. Because our object inherits from the originalbarobo.Linkbot class, we can also call any member function that is in thebarobo.Linkbot class.

While this style of programming may seem cumbersome at first, there are many reasons to motivate this type of organization. For instance,

  • Why don't we just hard-code all of the Linkbot movements withmove() andmoveJoint() functions? This might be feasible for smaller programs, but imagine if you had to write a program where a wheeled Linkbot had to travel through a complex maze. If we need the Linkbot to accurately turn and travel more than 10 times, it is probably worth the time to write a function or class to make it easier on ourselves. In the long run, we would probably save time by writing the derived class.
  • Why is writing a class better than writing helper functions? One of the main benefits of writing a class is that someone else (or you) can inherit from your new class too. Lets say for instance you wrote aLinkbotCar class that moves the Linkbot like a car and your buddy wrote a class calledLinkbotMelody that could make the Linkbot play complex songs using the buzzer. You could take the two classes and inherit fromboth of them to create a new class that can drive the Linkbot like a carand play melodies!

Exercises

[edit |edit source]

Continue extending theLinkbotCar class by adding functionsturnLeft() andturnRight().

Solution
classLinkbotCar(barobo.Linkbot):defdriveForwardDistance(self,inches):wheelRadius=3.5/2.0degrees=(360.0/(2.0*math.pi*wheelRadius))*inchesself.move(degrees,0,-degrees)defturnLeft(self):self.move(-30,0,-30)defturnRight(self):self.move(30,0,30)


Learning Python 3 with the Linkbot
 ← RecursionPrintable versionIntro to Imported Libraries and other Functions → 


Intro to Imported Libraries and other Functions

Intro to Imported Libraries and other Functions

[edit |edit source]
In this chapter, we will cover some functions from various imported libraries that are commonly asked about, or used in Python. This chapter is not required to fully understand basics of Python. This chapter is meant to show further capability of Python, which can be utilized with what you already know about the language.

math

[edit |edit source]
The math library has many functions that are useful for programs that need to perform mathematical operations, that cannot be accomplished using the built in operators.
This section assumes you have math training up to and including Trigonometry.

The following list, shows all the functions in the math library:

  • math.ceil
  • math.copysign
  • math.fabs
  • math.factorial
  • math.floor
  • math.fmod (Not the most ideal for its purpose. Will not be explained.)
  • math.frexp (Outside the scope of this tutorial. Will not be explained.)
  • math.fsum
  • math.isfinite
  • math.isinf
  • math.isnan
  • math.ldexp
  • math.modf (Outside the realm of this tutorial. Will not be explained.)
  • math.trunc (Outside the realm of this tutorial. Will not be explained.)
  • math.exp
  • math.expm1
  • math.log
  • math.log1p
  • math.log10
  • math.pow
  • math.sqrt
  • math.acos
  • math.asin
  • math.atan
  • math.atan2
  • math.cos
  • math.hypot
  • math.sin
  • math.tan
  • math.degrees
  • math.radians
  • math.acosh
  • math.asinh
  • math.atanh
  • math.cosh
  • math.sinh
  • math.tanh
  • math.erf
  • math.erfc
  • math.gamma
  • math.lgamma
  • math.pi
  • math.e
Of course we wont cover every one of these functions. But we will cover a good chunk of them.

Lets start off by covering the two constants in the math library.math.pi is the mathematical constant "π", to available precision on your computer.math.e is the mathematical constant "e", to available precision on your computer.Here is an example of both constants when entered in interactive mode in the Python shell.

>>>math.e>>>math.pi

These constants can be stored in a variable just like any other number. Below is an example of such, and shows simple operations on those variables.

>>> conste = math.e>>> (conste + 5 / 2) * 2.21>>> constpi = math.pi>>> (((7 /2.1) % constpi) * 2)>>>

Now, lets look at the functions. Lets start at the top of the list, and work our way down. Some of the functions will be skipped.At this point in the tutorial, you should be able to look at each of these examples to follow, and easily figure out what the example does. A simple sentence or two about what the function does will be provided.

Below is an example of everymath module function, and how it is used. (Excluding functions noted above as not to be explained)

>>> import math>>> math.ceil(4.5) ** Rounds the number up to the nearest non decimal number **5>>> math.ceil(4.1)>>> math.copysign(4, -.4)  ** Returns the numberx with the sign ofy in the context of(x,y)>>> math.copysign(-4, 4)>>> math.fabs(-44)  ** Return the absolute value of the number **>>> math.factorial(4)  **  Returns the factorial of a number **>>> math.floor(4.3)  ** Rounds the number down to the nearest non decimal number. **>>> math.floor(4.99999)>>> math.fsum([.1,.2,5,45.2,-.054,.4]) **  Returns the sum of all the numbers in the brackets. Not always precise **>>> math.isfinite(3) ** ReturnsTrue if the value is infinity or NaN. ReturnsFalse otherwise. **
Learning Python 3 with the Linkbot
 ← Intro to Object Oriented Programming in Python 3Printable versionThe End → 


The End

So here we are at the end, or maybe the beginning. This tutorial is on Wikibooks, so feel free to make improvements to it. If you want to learn more about Python,The Python Tutorial byGuido van Rossum has more topics that you can learn about. If you have been following this tutorial, you should be able to understand a fair amount of it. ThePython Programming wikibook can be worth looking at, too. Here are few other books which cover Python 3:

Hopefully this book covers everything you have needed to get started programming. Thanks to everyone who has sent me emails about it. I enjoyed reading them, even when I have not always been the best replier.

Happy programming, may it change your life and the world.

Learning Python 3 with the Linkbot
 ← Intro to Imported Libraries and other FunctionsPrintable versionFAQ → 


FAQ

How do I make a GUI in Python?
You can use either TKinter athttp://www.python.org/topics/tkinter/ or PyQT4 athttp://www.riverbankcomputing.co.uk/ or PyGobject athttp://live.gnome.org/PyGObject For really simple graphics, you can use the turtle graphics modeimport turtle
How do I make a game in Python?
The best method is probably to use PyGame athttp://pygame.org/
How do I make an executable from a Python program?
Short answer: Python is an interepreted language so that is impossible. Long answer is that something similar to an executable can be created by taking the Python interpreter and the file and joining them together and distributing that. For more on that problem seehttp://www.python.org/doc/faq/programming/#how-can-i-create-a-stand-alone-binary-from-a-python-script
(IFAQ) Why do you use first person in this tutorial?
Once upon a time in a different millennia, (1999 to be exact), an earlier version was written entirely by Josh Cogliati, and it was up on his webpagehttp://www.honors.montana.edu/~jjc/easytut and it was good. Then the server rupert, like all good things than have a beginning came to an end, and Josh moved it to Wikibooks, but the first person writing stuck. If someone really wants to change it, I will not revert it, but I don't see much point.
My question is not answered.
Ask on the discussion page or add it to this FAQ, or email one of theAuthors.

For other FAQs, you may want to see the Python 2.6 version of this pageNon-Programmer's Tutorial for Python 2.6/FAQ, or thePython FAQ.

Learning Python 3 with the Linkbot
 ← The EndPrintable version


  1. "The 'with' statement"
  2. 'The Python "with" Statement by Example'
Retrieved from "https://en.wikibooks.org/w/index.php?title=Learning_Python_3_with_the_Linkbot/Printable_version&oldid=4372861"
Categories:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp