wiki:ControlSystems/SoftwareTeam/IntroToPython

Back To Top
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.

Deep Thought 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.

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.

(A quick note: If you know all this already...CONGRATULATIONS! Here's some cute corgi puppy videos as your reward. Then, come back and dive into a later section--this is all self-paced. Regardless, we recommend you do this set of lessons if you haven't programmed in Python 3 before because we build on it later and you'll be lost. If you have programmed in Python 3 before, you can just skip to the Final Exam at the end, show your stuff, and help out your teammates.)

Python, like every programming language, has a structure. Here are the big parts:

  • Variables: https://mdn.mozillademos.org/files/13506/boxes.png Things you assign to and read from. Like in Algebra. a="Dump Truck" sets the variable a to the string "Dump Truck" (a string is just a sequence of letters and numbers strung together...hence the name). You can set them to strings/text, numbers or fancy things like lists. They're basically the nouns. You can think of variables as boxes you can store things in; you give each box a name like "student" for the box you'll store student names in or "isaMentor" for the box you'll store whether someone is a mentor (true/false) or "age" where you might store their age in years.
  • Control Structures: These are core programming language instructions like IF this is true THEN do that…. These are a lot like grammar rules, like: use active voice, or use punctuation. They're how you get stuff done. Control structures can let you do things selectively (conditionally), iteratively (repeatedly), and sequentially.
  • Functions: https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Function_machine2.svg/220px-Function_machine2.svg.pngThese do things. They take nouns as inputs (arguments), do something, and can output (return) nouns as well. They are like a black box with an input into which you can drop something and an output. In redCar = paintCarRed(blueCar), paintCarRed is a function that takes cars as inputs, paints them red, and outputs the altered car. Note that you can drop the contents of a variable (box) into a function and place the result into another box. Functions are verbs, they do things, and they take inputs and return outputs. Many functions are built in to Python, but you can (and should) create your own. The ability to create your own functions (new words!) is a big part of what makes programming languages so powerful.
  • Packages: A lot of other people have written new functions to do things. A lot of things. When these things are bundled together they're called packages or libraries which you can download and use. You can tell your program to use a package and save your self a lot of typing, and do things that would require 2 or 3 college degrees without all that study.

Much like in English, you blend all of these together to create stories, or programs. 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:

  1. Highlight the code above in your browser, right click and click Copy from the pop-up menu. This put the highlighted code on the clipboard so you can share it with another window.
  2. 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.
  3. On that page, highlight all the code already in the center window.
  4. Right click and pick Paste. This should replace everything in the window with the contents above.
  5. Finally click Execute right above the center window to run the program. You can see the results in the green box below (it scrolls, so look at the last lines)

(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. Its considered a best practice to name your variables as nouns.

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: Control Structures

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!

https://docs.oracle.com/cd/A58617_01/server.804/a58236/03_strua.gif Selective execution of portions of your program is done with conditionals. 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:

  1. The double equals in location=='HERE' on the first line. It is called an boolean expression. In this case, it tests equality (some kinds of boolean expressions in Python are listed here) . Boolean expressions return True when the condition evaluates to True, otherwise they return 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.
  2. 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.
  3. 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. https://www.quackit.com/python/reference/python_3_escape_sequences.cfm? are some other escape sequences you can use.

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 we were in Poughkeepsie, We'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 keyword 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 for yourself that the program doesn't see or run. The robotics team wants you to put comments in your code a lot--it makes the code easier for others 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!

Repeated execution of a portion of your program is done with a type of control structure called an iterator. The For loop control structure runs the same block of code for each item contained in 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 better understand what's going on here, pretend that the For Loop is basically a big arrow. The first time the For loop runs, this arrow (called the ''index variable'') points 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 arrow to the second value and so on. After the third fruit, the for loop knows there's nothing left in fruits so it stops and the prints the last line "That's alotta fruit!"

Note that the "Current fruit..." print statement is indented. Just like in the 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/or do the same thing over and over again. The less code you write, after all, 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 expression evaluates to True. This expression is evaluated at the start of each loop, so it possible to not even run the While loop at all if expression starts out False.

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

Since we're getting pretty far into these lessons, I'm not going to tell you the answer for this one. You should be seeing a pattern by now. What should it print? The 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?

Compound Control Structures: 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 even 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 extra characters could save your life someday.

Now, your turn: 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!
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 we bet you can do it. Ask a neighbor for help if you need to. I'll give you three hints:

  1. You can tell a print to not end with a new line by adding an end="" to the print statement like this print("I'm a teapot!",end="").
  2. An empty print statement print("") just prints a new line, basically the equivalent of having the program hit <enter>.
  3. 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 we didn't warn you.

The solution is here. This concludes Lesson 2.

Lesson 3: Functions

https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Function_machine2.svg/220px-Function_machine2.svg.png So are you tired of just printing stuff yet? In the last lesson, we introduced you to all sort of ways to make decisions and loop over code to make your program easier to read and shorter too.

Functions do things in your code. You've already used two: print (yes that's a function), and range (assuming you did the last exercise of the last less and didn't cheat).

The actual code run in these functions can be pretty big. Imagine if you had to type it out every time you wanted to use it. That would get old, confusing, and error prone fast.

Functions can take variables arguments as input, and may return variables as output.

Here's a few handy functions built in to Python:

  • input(prompt): Prompts the user for input by showing the prompt screen, returning whatever the user entered after they hit <enter>.
  • pow(x,y): Returns xy
  • round(x,[n]): Rounds a decimal number x to n digits after the decimal point. The [] means that the n is optional, if you don't include it, n=0.
  • sum(iterable): Sums all the numbers in the list iterable.
  • <string>.isdigit(): Strings and some other variable types like lists have some special functions just for them, called methods. This one returns true of all of the digits in the string are numbers, others are here. '123' would return True, "Cat" would return False. Handy for validation. You call them *on* the variable itself, and it has to have a value before you can call these methods.
  • int(string): Converts an string to a number (so you can do things like math on it).

Here's some examples of how they're used (don't forget to look at earlier lessons for range() and print().

a=input("Enter a number, any number-->")  # Enter something at the prompt.  Program will wait at this point.
print(a);

b = pow(2,2)
print(b) #Result is 4 (2 to the power of 2)

c = round(3.14159, 2)
print(c) #Result is 3.14

d = sum([1,2,3,4])
print(d) #Result is 10

e = "123"
f = e.isdigit()
print(f) #Result is True

g = int("123")
print(g) #Result is 123

Try running these yourself, making sure the results are as expected.

You can even combine these functions with control structures to do some interesting stuff, and even nest them. For example, try running this (entering values for x and why when prompted. Try putting in non-numeric or decimal values too):

x="" # Put a dummy string in x and y so both while-nots below work.  Pretty slick, eh?  Programming uses tricks like this all the time.
y="" 
while not x.isdigit():  # Note the "not"...in this case if x is not all digits, run the block of code in the while loop
   x=input("Enter x-->")
while not y.isdigit():
   y=input("Enter y-->")
z = pow(int(x),int(y))
if z > 100:
  print("That's-a big number!")
else:  
  print("Aw, its only",z)

But wait, there's more...you can create your own functions. That way, if you come up with cool way to do something you can reuse it and don't have to repeat yourself as much. For instance:

def singHappyBirthday(age, names): # a custom function
   for name in names:
      for count in range(0, age):
         print("Happy Birthday to You!")
         if count == age-2: 
           print("Happy Birthday, Dear", name)
       
singHappyBirthday(6,['Milla', 'Emma'])  # now use it.

Run this one. What does it output? A lovely happy birthday song for two kids? Now imagine if you had to write a program to print out a happy birthday for every single person in your grade without it. It'd get pretty ugly, fast.

The keyword def is used in Python to indicate a custom function, and you have to define it in your program before you use it. This function takes an argument of an age, and second argument of a list of names. The "singHappyBirthday" line at the end actually calls or runs the custom function, with the two arguments it needs. Its considered a best practice to name your functions as verb phrases.

A function can return a value too, by using the Python keyword return for example:

def isOver9000(power):
   if power>9000:   # you could also express this if-then-else statement as "return power>9000"
     return True
   else: 
     return False
 
isGokuPowerfulEnough = isOver9000(9001)
print(isGokuPowerfulEnough)

Now your turn... Modify the 'That's-a big number" exercise above, adding a custom function called called inputNumber to input one number, and use it instead of repeating the while-not stuff. Run it and verify the output is the same. Much easier to read, no?

By using functions, you can perform powerful operations that are built in the to the language, or someone created. These function in turn can use other functions and build on top of them to make more advanced programming commands. This concludes lesson 3.

Here's the solution

Lesson 4: Packages

Now that you seen the basics of the Python language, and have created your own functions. Its time to see what else is out there. It turns out there are A LOT of packages out there that contain custom functions for Python that do pretty much anything you'd want, from advanced machine intelligence, to 3D graphics, to yes, controlling robots. These packages were created by others and are offered for free, and others may be offered at a cost.

You can find these packages by googling for with the term "<subject> python library". For example "spell check python library". This turns up | PyEnchant which describes how to use and access the library. There are probably others. You can also go to the Python Package Index. What ever you do, make sure you use the correct version of the library for the version of Python you're using (in our case, Python 3)

To use the pyenchant external package in your program, you use the `import` keyword in Python at the beginning of your program like so:

import enchant 
d=enchant.Dict("en_US")  # Selects the US english dictionary 
bad=d.check("Helo") # Spell checks the given string, not correctly spelled, returns False 
good=d.check("Hello")  # Correctly spelled word returns True 

This makes the library known to your code once its installed.

It would be a enormous effort to create your own spell check library, so reusing one saves a lot of time. We'll be using this when we program robots because a lot of the work we need to do to communicate with the parts of a robot has already been done. And we want to spend time making robots do things, not figuring out how to communicate with then.

Unfortunately, you can't include external packages in your code in our web-based code runner and run them, so you'll have to use your imagination to see how this particular example works. You'll use them a lot in the intermediate training as the year goes on. This concludes Lesson 4.

Final Exam


Feeling like you got this? Awesome, then: Create a program in Python 3 that prints random fortune cookie sayings.

Here's what you need to do:
+ Randomly build the sayings from at least three different lists of nouns and verb phrases (Hint: Use the Python random functions, its available in the online editor).
+ Make the random sayings sound suitably cryptic and wise.
+ The program should prompt the user for the number of sayings they want output, validate that it is indeed a number, and print out that many.
+ Use functions and control structures to make the code manageable. Its best if you work in pairs for this exercise.
+ If you need help, refer to this lesson, the Official Python 3 Documentation, your teammates, and don't hesitate to ask the mentors.

(We'll only show you the answer to this one once you show us your solution. Its a final exam, after all...)


What's Next?

Well, that concludes the Software Programming Introduction. Thank you for participating, we welcome your feedback.

Software takes a lot of work and study to write well, and this is just a taste. For those of you who select the Software team, we'll begin intermediate training with the Raspberry Pi, and show you how to write programs that use external libraries to communcate with the outside world through motors, sensors and the like. Then we'll introduce you to the RoboRio?, the competition robotics platform.

Nyan cat


End Of Software Introduction

Last modified 4 years ago Last modified on Sep 26, 2017, 7:11:15 PM

Attachments (3)

Download all attachments as: .zip