Version 46 (modified by 8 years ago) (diff) | ,
---|
Prerequisites: Control Systems Overview
Lesson 1: Getting Started
If you want to tell a computer to do something, you have to communicate with the computer in a programming language. When we say language, we mean it. A language has words and grammar and everything else, just like French.
Computers, despite what you may think, are dumb. They do only exactly what you tell them to, and don't guess or interpret. If say to your Mom or Dad "Hey, can you bring me that thing?", there's a (slim) chance they may bring you the right "thing". A computer wont. Ever. Just a cold, unfeeling "ERROR". A programming language is very precise, and to tell a computer what you want, you have to be precise too. In this training session, we'll introduce programming to you, and make some things work. You know, those things.
Hang on, it gets harder from here.
(A quick note...If you know all this already and are getting bored...CONGRATULATIONS! Here's a link to some cute corgi puppy videos as your reward. Then, come back and dive into a later section. This is all self-paced.)
We'll be starting with a programming language called Python, specifically Python 3. There are a lot of programming languages. Some are created because they're better for solving certain problems, others because people are bored and want to try something new. Python has been around for a while, and its pretty popular because its easy to use. The team uses Java to control the robot but that language is a little trickier. We'll get to that one later once you get a handle on the basics.
Python, like every programming language, has a structure. Here are the big parts:
- Variables: Things you assign to and read from. Like in Algebra.
a="Dump Truck"
sets the variable A to the string "Dump Truck". You can set them to numbers to or fancy things like lists. They're basically the nouns. - Control Structures: These are instructions like IF this is true THEN do that…. These are like grammar rules, like use active voice, or use punctuation.
- Functions: These do things. They take nouns as arguments, do something, and can return nouns. In
redCar = paintCarRed(blueCar)
,paintCarRed
is a function. They're the verbs, they do things, and they take variables and return variables. Some functions are built in to Python, but you can create your own. - Libraries: A lot of other people have written functions to do things. A lot of things. When these things are bundled together they're called libraries. You can tell a computer to use a library and save your self a lot of typing.
Much like in English, you blend all of these together to create stories, or programs. Both have a beginning middle and end. So lets write the first program that all programmers start with: "Hello World"
a="Hello World" print(a)
This tells the computer to print, you guessed it, "Hello World"
Now you try it...Do the following:
- Then highlight the code above, right click and click {{{Copy}}. This put the code on the clipboard so you can share it with another window.
- Go here. This site is our code editor for training purposes, and its pretty cool. You can put code in the center section, and click Execute to run it. The lower window shows the results.
- On that page, highlight all the code already in the center window.
- Right click and pick {{{Paste}}}. This should replace everything in the window with the contents above.
- Finally click {{{Execute}}} right above the center window to run the program.
(From now on, we'll call this step "Go here and run the code above". (Just come back to these steps if ever you forget how to do that).
After a bit, you'll be rewarded with the following message in the bottom window:
Hello World!
The program told the computer to print the value of variable a on the screen.
And, boom, now you're a programmer. The rest of learning how to code is just more details. This is the end of Lesson 1.
Lesson 2: Making Decisions
In lesson 1, we had you create a program, "Hello World". Now, "Hello World" is not too exciting if you want to program robots, but its an important first step. We showed you how to run a function (or verb) print
, which does something (shows on the screen the value of its argument a
, where a
is assigned the value "Hello World".
If you want to do more in a program and actually make decisions in your code, we need to introduce control structures.
If-Then-Else: Decide, already!
Take the program below, it uses an If-Then-Else control structure to ask the program to make a decision, and run code based on that decision. You'll use these all the time.
location = 'HERE' print("Welcome to our store\n") if location == 'HERE': print("We're here! Come on in\n") print("Our ours are 11:00am-11:52am\n") else: print("Go away, we're out eating tacos\n") print("Hope you had a good time")
Go here and run the code above. It should print:
Welcome to our store We're here! Come on in Our ours are 11:00am-11:52am Hope you had a good time
Three things to note about this program:
- The double equals in location=='HERE' on the first line. It is called an expression. In this case it is an equals expression (other kinds of comparisons in python are listed here) . It returns True when the condition evaluates to True, otherwise its False. Note on that line the word 'HERE' is in quotes. That's to indicate its a string (a text value) not some variable (which doesn't exist). If you used = instead of == it wouldn't work as you expected because it would be a variable assignment. If a IF-THEN-ELSE statement ever behaves in an unexpected way, check for this problem first, its a really common mistake.
- Spacing and indents are important in Python. the line "We're here..." and the line below it are indented to indicate they are part of a statement block that runs when the condition evaluates to True. The second block on the else is run when the condition to False, and only contains one line. If you want to do stuff outside of the IF-THEN, don't indent it like the first and last print statements.
- You'll see that a few of the print statements end with a {{
n}}. This is called a escape sequence, and its shorthand for a newline. When the computer sees it in a print statement, it will add an extra line to the output. See here for other escape sequences you can add.
Now, in the editor replace the line with the if expression with
if location == 'Poughkeepsie, NY':
and run it again. What happens? It should print "Go away, we're out eating tacos". Why? If I was in Poughkeepsie, I'd be out eating tacos too. Yummmm, tacos.
If you're writing your own code, you don't want to provide an ELSE, just omit the word else: and the indented block you want to run with it. For example:
medianSalary=98260 #Median annual salary of a software engineer in the US. Yes, really. salary=90000 if salary > medianSalary: print("Whohoo! Dinner's on you!")
Go here and run the code above. It should print:
Yep, nothing was output. Nada. In this case, we used variables which were numbers, and a greater-than expression to compare them. Since the condition was False, nothing was printed.
(Also note the text in the code that starts with a # sign. The pound sign and everything after it on that line is called a comment, and its a way to put some notes in the code that the program doesn't run. The robotics team wants you to put comments in your code a lot--it makes the code easier to read and understand. And we like it when we can understand you.) Now for a couple of other control structures that you should know...
For Loop: Stop Hitting Yourself!
The For loop control structure runs code repeats over a variable. Try running this one:
fruits = ['banana', 'apple', 'mango'] for fruit in fruits: print("Current fruit :", fruit) print("That's alotta fruit!")
It should output:
Current fruit : banana Current fruit : apple Current fruit : mango
This example loops over an array (a fancy word for a list) of fruits, and prints each value out, each line starting with the text "Current fruit:". To understand this, pretend that the FOR loop has a big arrow in pointing to the first value in the fruits ''array''. The first time it runs, this arrow,{{{fruit}}} is pointing to the first value in the ''array'', {{{banana}}}, which it then sets to be the value of the index variable ''fruit''. After it prints the message, the for loop senses through arcane magic that there are other values in fruits, so it just moves the pointer to the second value and repeats. After the third fruit, the loop knows there's nothing left so FOR loop exits and prints "That's alotta fruit!"
Note that the "Current fruit..." print statement is indented. Just like in a IF-THEN-ELSE control structure, you can run a block of of multiple lines of code in a for loop, just indent all the lines.
For loops are handy if you want to avoid repeating yourself in code, and do the same thing over and over again. The less code you write, the less chance you can make a mistake. Not to mention its easier to read.
While Loop: One more time around the block, Alfred!
A While loop is the more charming cousin of the FOR loop, this one repeats as long as its condition is True. If the condition is false when it gets to the While loop, the While loop wont run at all.
count = 0 while (count < 9): print ("The count is:", count) count = count + 1 count = count + 1 # Yup, lets do it again because we're E-VIL print("Good bye!")
Go here and run the code above. It should print
Oh no, I'm tired, so I'm not going to tell you the answer for this one. You should be seeing a pattern by now. You tell me---what should it print? Count starts out at 0, and as long as count is less than 9 it will run the code in the block, then it will print "Good bye!". What else does it print out?
Here a Control Structure, There a Control Structure, Everywhere a Control Structure…
Lastly, you can combine all three of these in any sort of combination, and nest them. This is how you do real work in a program. For example, try running this one:
count=1 while (count<=7): if (count==4): print("more!") else: print(count, "potato,") count+=1 print("score!")
What does it output? See how the indenting works when nesting? Note that count+=1
is shorthand for count=count+1
because not typing those excess characters could save your life.
Now, modify the code to make it repeat the word potato each time based on the current value of count, and run it. When you're done, the output should look like:
1 potato 2 potato potato 3 potato potato potato more! 4 potato potato potato potato 5 potato potato potato potato potato 6 potato potato potato potato potato potato 7 potato potato potato potato potato potato potato score!
Yeah, this is a little harder, but I bet you can do it. Ask a neighbor for help if you need to. I'll give you three hints:
- You can tell a print to not end with a new line by adding an end="" to the print statement, like this
print("Im a teapot!",end="")
. - An empty print statement
print("")
just prints a new line, basically wrapping any line you're on. - If you want to loop over a set of numbers, use a
range()
. For example,for x in range(0,5)
will make x go from 0 to 4 incrementing 1 each time it loops. The first number is where x starts, and the second number is where x will stop minus 1. Don't ask why---its just the way computers and programs work. Don't believe me? Fine. Don't say I didn't warn you.
The solution is here.
Attachments (3)
- 1B6AA343-B7D4-49F7-88DA-2AB89A7A4E72-5482-00000452F115F905_tmp.png (42.6 KB) - added by 8 years ago.
-
tumblr_nzwkbcWeYP1qhjjeao1_500.gif (81.7 KB) - added by 8 years ago.
Nyan cat
-
deepthoughtcomputer-619-386.png (298.9 KB) - added by 8 years ago.
Deep Thought
Download all attachments as: .zip