Learning Python 3 with the Linkbot/Who Goes There?

From Wikibooks, open books for an open world
Jump to navigation Jump to search
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]

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? Linkbot
You 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 the input() 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 of input. 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 a variable. In the previous program user_input is a variable. 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.4
b23 = 'Barobo'
first_name = "Linkbot"
b = 432
c = a + b
print("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.4
first_name is Linkbot
The 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 are a, b23, first_name, b, and c. The two basic types of variables are numbers and strings. Numbers are simply a mathematical, numerical number, such as 7 or 89 or -3.14. In the above example, a, b, and even c 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 example b23 and first_name are variables that store strings. Barobo, Linkbot, a + b is, first_name is, and The 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 actual value, you must use those punctuation marks. See the next example.

value1 == Pim
value2 == "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 variable value1 is the same as the value stored in the variable Pim. In the second one, Python checks if the string (the actual letters P,i, and m) are the same as in value2 (More explanation about strings and about the == come later).

Assignment[edit]

In review, there are boxes called variables, and data goes into those boxes. Recall the previous examples. The computer sees a line such as first_name = "Linkbot", and it reads it as "put the string Linkbot into the box, or variable, first_name". Then the computer sees the statement c = a + b, and it reads it as "put the sum of a + b or 123.4 + 432 which equals 555.4 into c". The right hand side of the statement a + b is evaluated, meaning that the two terms are equal, and the result is stored in the variable on the left hand side c. In other words, one side of the statement is assigned to the other side. This process is called assignment.

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 = 1
print(a)
a = a + 1
print(a)
a = a * 2
print(a)

Here is the output:

1
2
4

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.34
Type in an integer: -3
Type in a string: Hello
number = 12.34
number is a <class 'float'>
number * 2 = 24.68
integer = -3
integer is a <class 'int'>
integer * 2 = -6
text = Hello
text is a <class 'str'>
text * 2 = HelloHello

Notice that number was created with float(input()) while text was created with input(). input() returns a string while the function float 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 use float(input()), if you want the user to type in an integer use int(input()), but if you want the user to type in a string use input().

The second half of the program uses the type() function which identifies a variable's type. Numbers are of type int or float, which are short for integer and floating point (mostly used for decimal numbers), respectively. Text strings are of type str, short for string. Integers and floats can be worked on by mathematical functions, strings cannot. Notice how when python multiplies a number by an integer the expected thing happens. However when a string is multiplied by an integer the result is that multiple copies 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 examples to 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:

Operation Symbol Example
Repetition * "i" * 5 == "iiiii"
Concatenation + "Hello, " + "World!" == "Hello, World!"

Moving a Linkbot's Motor[edit]

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 user
import barobo
myDongle = 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]

Rate_times.py

# This program calculates rate and distance problems
print("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 distance
Rate: 5
Distance: 10
Time: 2.0
Input a rate and a distance
Rate: 3.52
Distance: 45.6
Time: 12.9545454545

Area.py

# This program calculates the perimeter and area of a rectangle
print("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 rectangle
Length: 4
Width: 3
Area: 12.0
Perimeter: 14.0
Calculate information about a rectangle
Length: 2.53
Width: 5.2
Area: 13.156
Perimeter: 15.46

Temperature.py

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

Sample runs:

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


Exercises[edit]

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

Solution

Write a program that gets 2 string variables and 2 number variables from the user, concatenates (joins them together with no spaces) and displays 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 user
import barobo
myDongle = 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, World Who Goes There? Count to 10 →