<<

PARC VLP PROGRAMMING CURRICULUM With Python

WWW.PARCROBOTICS.ORG

Overview

Study of programming languages, paradigms and data structures.

Chapter 1: Programming

Sections A. What is programming? . What is a ? . Writing source code . Running your code E. Using IDE

Chapter 2: Programming Syntax

Sections

A. Why Python?A. Why Python? B. Basic statementsB. Basic statements and expressions and expressions C. Troubleshooting issues C. Troubleshooting issues Chapter 3: Variables and Data Types

Sections

A. IntroductionA. to Introductionvariables and to data variables types and data types B. WorkingB. Working with variables with variables across Languages across Languages C. Working with numbers C. Working with numbers D. Working with strings E. WorkingD. with commentsWorking with strings E. Working with comments

Chapter 4: Conditional Code

Sections:

A. Making decisions in code B. Exploring conditional code C. Working with simple conditions D. Conditionals across languages

PAN-AFRICAN ROBOTICS COMPETITION 1

Chapter 1

SECTION A

What is programming?

Programming is the process of converting ideas into instructions that a computer can understand and execute. These instructions are specific and sequential. You can think of it as a recipe. Let's you want to prepare your favorite food; you would need first a list of ingredients and then a of instructions as to which ingredients go in first. If you have ever cooked before or watched someone cook before you will know that the amount of each ingredient can dramatically affect the outcome. Computers are very literal. They try to execute our commands exactly. When we give them bad instructions, we might introduce bugs or even make the computer crash. In programming, a bug is when something unexpected happens, whereas a crash is when your program stops early or freezes, just like if you use the wrong ingredients in your cake. Instead of a fluffy, moist cake, you could have a flat, runny disaster. The other characteristic of computer instructions is that they're sequential, just like the steps in a recipe. The order of the steps will impact your final product. It's all about giving computers the right instructions and the correct sequence of steps to produce the desired result. This is important because programming is just as much about finding errors and preventing crashes as it is about writing the instructions or code that the computer understands. So, to recap, programming is how we communicate with the digital world. It's characterized by having instructions that are specific and sequential. And when we get our code right, just like in a recipe, the end result is a program that helps us to enjoy a bit more of our world.

Programming is an increasingly important skill, whether you aspire to a career in software development, or in other fields.

PAN-AFRICAN ROBOTICS COMPETITION 2

Programming involves activities such as analysis; developing understanding; generating algorithms; verifying the requirements of algorithms, including their correctness and resources consumption; and implementation (commonly referred to as coding) of algorithms in a target programming language.

PAN-AFRICAN ROBOTICS COMPETITION 3

SECTION B

What is a programming language?

When you want to provide instructions to a computer, you use what's called a programming language. There are hundreds, if not thousands, of programming languages available, each made up of its own syntax, or rules, and semantics, or meaning. Let me give you an analogy. In English, we would write, "Good morning”, but in French, we would write, Bonjour. Semantically, they mean the same thing. Likewise, programming languages also have unique syntax rules. Let's look at a few examples of the Hello, world program. Maybe you've already heard of it before. It's the most program used for decades to get started with a new programming language. It helps to highlight the differences in syntax between languages. First, let us look at a language called C++. This is how we would get the program to display Hello, world when run.

#include

Int main()

{

std::cout<<”Hello World”;

Return 0;

}

Now, it may look strange to you, but that's okay. Soon you'll be able to understand exactly what's happening. For now, I want you to just notice the syntax used in the language. This consists of double quotes around the words Hello, world, the use of a semicolon at the end of statements, and there's a return keyword right before a closing curly brace. All of these things are part of the syntax, or rules, of the C++ programming language. Let's look at a few more examples. This language is called JavaScript. It's a very popular language used in virtually every website these days. This is how we would display Hello, world using JavaScript.

document.write(‘Hello, world’)

PAN-AFRICAN ROBOTICS COMPETITION 4

Notice the use of different syntax. First, the words Hello, world are now inside of single quotes. We don't have any curly braces. Instead, we see something about document.write. And finally, here's Hello, world in Python

print(“Hello world”)

Similar syntax to JavaScript, you see the use of parentheses and the use of double quotes has returned, just like we saw with C++. Now you may be wondering, what's the point of having so many different languages, especially if they do the same thing? Why not just have one programming language and we all use it? The main reason why we have so many languages is that each comes with its own set of strengths and weaknesses. Some are ideal for programming small devices with limited memory, whereas other were made to handle complex mathematical computations. Regardless of the language you choose, ultimately, that language has to be broken down into the only one that computers understand, machine language. Machine language is extremely complex for us to write directly because it's mostly just a series of numbers. Professor Mike DeHaan compared machine code to DNA molecules. Can you imagine trying to read a DNA sequence atom by atom? That would take you forever, and this is why we have these other languages that we call high-level languages. They're closer to human languages, comprised of keywords, structure, and syntax that's easier for us to learn and understand.

PAN-AFRICAN ROBOTICS COMPETITION 5

SECTION C

Writing source code Writing source code is what programmers do all day. It's the instructions we have for the computer, and it's written in plain text. In other words, we write it without special formatting, like bold, italic, or different font types. It's mostly just the actual characters. This means that word processing applications aren't suitable for writing code, because by default, they insert bits of information in files that prevent them from being plain text. Instead, you can use a text editor. If you're on windows, you already have a text editor available to you. Notepad. And for Mac users, there's TextEdit. Both applications allow you to write source code.

Let's look at an example. I'll be using Notepad since I'm on a windows. We're going to go ahead and open up Notepad, when using TextEdit the first thing that you'll notice is this formatting bar. By default, TextEdit stores files in Rich Text Format. That means you can do things like bold or italics, or even underline. But this is not suitable for writing source code. To change it, we're going to go over to TextEdit, choose Preferences, and then we're going to choose plain text under the Format section. Also, make sure you uncheck all of the options down below. Great. We can close our Preferences pane, and let's restart TextEdit to make sure that our changes are still present. Perfect. Now that formatting bar is no longer here. If you're on a PC and you're using Notepad, you don't have to worry about this. It uses plain text by default. So, let's start off by doing our favorite program, Hello World. We're going to do the Python version. I'm going to type print, open parentheses, double quotes, hello world, exclamation mark, double quotes, and a closing parenthesis.

We did it. We've written some source code. Source code can either be one line, like you see here, or thousands. It just depends on the needs of your program. Let's go ahead and save this file. By default, TextEdit and Notepad saves files with a .txt extension. This is because it's plain text. But it's a best practice to use an extension that corresponds to the programming language that's inside of your file. Since this code was written in Python, we're going to use the Python extension, which is ".py”. So let's save this as myFirstCode.py.

PAN-AFRICAN ROBOTICS COMPETITION 6

Perfect. Each programming language has its own file extensions. For JavaScript, it's .js, , .pl, whereas a language like Kotlin uses .kt. Now that we know how to write our code, we need to learn how to translate it into the language that the computer speaks. Machine language. This is a vital step to get it running on any device.

SECTION D

Running your code

If we were to double click our Python file, it would just open in an editor, but it wouldn't do anything with the code that we put inside. Why is that? Well, it's because Python is an interpretive language. This means we have to interpret it into machine code and we haven't run the interpreter yet. There are three main ways to translate source code into machine code: compile it, interpret it, or a combination of both. Compile, interpret? Let me give you a real- world example. Say you need to write a letter to someone who speaks Mandarin, but doesn't speak English. What would you do? You could first write it in English then use a translation service to convert your letter into Mandarin and mail it. The other person would never see your original letter, only the one that was in Mandarin. That's basically what compilers do. They take

PAN-AFRICAN ROBOTICS COMPETITION 7

your high-level programming language and turn it into an executable program that contains low level machine code. This way, users can run your code on their machine without every needing your original source code. Now the second option for sending out a letter is to send it to them in English, then they could have a friend who speaks English read each line of the letter first and tell them what it means in Mandarin. Every time our Chinese friend needs to read the letter, the interpreter will need to come back over and reinterpret the letter. This is essentially what computer interpreters do: they process your source code each times its run, line by line, and it's up to the other user to have the needed interpreter available on their machine. Now this is of course an over simplification of both compilers and interpreters. They perform complex functions that help to optimize the size, speed, and security of your source code, but it helps to convey the general idea of how they differ. Typically, languages like C, C++, and Objective-C are known as compiled languages, whereas PHP and JavaScript are known as interpretive languages. And finally, Java, C# and Python use the combination approach. Nowadays, the line between compiling and interpreting is a bit blurry, as many languages have some variants of both. The key thing to keep in mind, is that you may need to perform additional steps to get your code to run on your, or someone else's machine.

SECTION E

Using IDE

You can write entire programs in simple text editors, but in practice few programmers do. They use enhanced text editors called integrated development environments, or IDEs. IDEs provide features that speed up code development. When you want to write a letter, an essay, or a resume what tool would you use? You'd probably use a word processor such as Word, or Google Docs. They have special tools that help you check grammar, spelling, and add nice formatting. For programming we use an IDE in the same way. An IDE is an application that provides the special tools needed to write, debug, and compile code. Let's take a look at two popular IDEs to see what they have to offer. Don't worry about downloading anything right now, we're just going to check them out together. We'll start with Xcode, or Visual studio code. Xcode

PAN-AFRICAN ROBOTICS COMPETITION 8

is used to develop applications for Apple products, like the iPhone, iPad, or Mac. Right away you would be able to see a difference between our simple text editor and a more sophisticated IDE. We have line numbers on the left side of our source code editor. This allows us to more quickly reference individual statements in our code. There's also the use of color, known as syntax highlighting, to aid in pointing out important keywords and improve the readability of our code. And finally, notice how you can even preview what your code will look like when compiled and run on a real device. Definitely a great tool to improve your coding process. Now although Xcode is really nice, let's look at one more example, Visual Studio Code. Visual Studio Code, or VS Code for short, is a more lightweight editor than Xcode and it was initially designed for scripting languages, such as JavaScript and TypeScript.

However, it gradually came to support many more languages through powerful extensions. You'll find developers using it to develop apps in dozens of languages. One of its unique features is called IntelliSense. This allows you to get code suggestions while you're typing. It works a lot like auto-complete, when you're sending a text or when you search in Google and it guesses the rest of the phrase you're typing. And unlike a simple text editor, we can actually run our Python code from within the IDE. It's really cool. And there are many more IDEs out there. Programmers love to argue, I mean talk, about which IDE is their favorite. If you have an hour or two to spare, just ask any programmer what IDE they think is best. Then get ready to pull up a chair. IDEs can ease the burden of software development by providing tools to help you write, debug, and run your source code more easily. Ultimately, it's up to you to find one that meets your needs, and you don't mind using it for hours a day.

PAN-AFRICAN ROBOTICS COMPETITION 9

Chapter 2

SECTION A

Why Python?

When choosing the language for this course, I had two main requirements. It needed to be popular and easy to learn. As far as being popular, right now, the top five programming languages are Java, Python, JavaScript, C++ and C#. That narrowed down the list considerably. But when it comes to ease of learning, both Python and JavaScript have fewer Syntax requirements than the other languages, so let's look at those two. Both Python and JavaScript tend to be more concise. This means it takes fewer lines of code to get things done. They're also easier to understand, as both languages use structuring and wording that are closer to human language. But which one to choose? Well, JavaScript was designed to work with and manipulate webpages, and it continues to be widely used for that very reason, although, it can also be used for non-web applications. Python, on the other hand, was designed to be a general-purpose language. You can use Python to create web apps, internal company tools, perform scientific analysis, as well as create games. The Python language has been around for decades, and it's available on multiple platforms including Mac, Windows, Linux and more. It's a great choice for exploring the various concepts that we're going to cover. So, for this course, Python is the winner. We've already seen some Python code. Remember our simple, "Hello world!" program?

PAN-AFRICAN ROBOTICS COMPETITION 10

SECTION B

Basic statements and expressions

You could have all of the ingredients to bake a cake, but if you don't have a recipe, then there's no cake. It's the same way with statements. Statements are the building blocks of any program and are the individual actions that you want your program to take. Without statements, there's no program. Each statement can be made up of keywords, expressions, and operators. We'll talk more about keywords later. For now, we'll focus on expressions and operators. Operators are symbols that tell the computer to perform an action with some input, and the good news is, you're already familiar with many of the operators that are used in programming from your primary school education. In this table, you can see a partial listing of some operators that should be familiar to you.

Symbol Operation Usage + 10+2 - Subtraction 10-2 * 10*2 / Division 10/2

The plus used for addition, minus for subtraction, an asterisk or a star to represent multiplication, and finally, a forward for division. These are known as arithmetic operators, as they take numbers for their input and perform an arithmetic operation. Flash back to primary school. When we have three plus two (3+2), the plus sign is the operator and three and two are the input, also known as . In programming, the combination of operators and operands that break down to a single value are called expressions. Let's look at a few examples. If we take the following, ten plus two (10+2), what does that equal? 12, correct. 10 plus two is our expression and the 12 is what our expression evaluated to or equaled. Let's try another one. 10 divided by two plus three. What does this expression evaluate to? Yes, it's eight. Now let's look at another expression where the answer may surprise you. Two plus three times six. What do

PAN-AFRICAN ROBOTICS COMPETITION 11

you think this expression evaluates to? It's 20. Now if you thought 30, that's understandable. But in programming, the default is the same as in mathematics. The plus or addition operator in our example is evaluated after the asterisk or multiplication operator. That's why we get 20 instead of 30. A way of remembering the order of operations or PEMDAS. That stands for P, parentheses first, E, exponents, MD, multiplication and division from left to right, and finally, AS, addition and subtraction, left to right. It's important to keep the order of operations in mind as your program could behave unexpectedly based on how an expression is evaluated. If we go back to our last expression, it evaluated to 20 because of the order of operations. But what if we, as the programmer, wanted it to process the addition first? In that case, we would add in the parentheses around our addition operation and then we would get the result that we wanted, 30. Computer programs are made up of statements, statements that can perform a mathematical calculation, display something to the screen, or even make a choice between two code paths. As we continue to explore the fundamentals of programming, you'll see just how powerful this concept really is.

PAN-AFRICAN ROBOTICS COMPETITION 12

SECTION C

Troubleshooting issues

One of my favorite quotes about programing is from Alan Perlis, who said, "There are two ways to write error free programs, "only the third one works." This play on words is meant to highlight the fact that programs tend to have bugs, and you're not doomed as a programmer if you run into issues when writing and running your code. But when you're first getting started, what can you do to figure out why your code is acting up? Well, first, you need to understand what type of bug or error you're dealing with. Errors tend to fall into three categories; Syntax, Runtime, Semantic/Logic Syntax, you somehow broke the rules of the language. Runtime, the computer was unable to execute a portion of your code. And finally semantic, the output of the program is not what you expected. Let's look at an example of each type of error. We'll go to the command line and start our Python Shell.

And finally enter. Uh-oh, we didn't get our familiar hello world like we expected. This is because the quotes were missing, the Python interpreter didn't understand what we wanted it to do. When you come across these types of errors, it's best to slowly review each line of code to see

PAN-AFRICAN ROBOTICS COMPETITION 13

where you have missed providing a set of quotes, parentheses or a colon. The next type of error is a runtime error. This happens when your program is actually running. Let's look at an example. We're going to create a new statement, this is going to use the expression 10 times two divided by zero.

Now let's hit enter, and we receive a zero division error. But why? This is because division by zero was attempted. From mathematics, we know that division by zero is undefined. The Python interpreter has no idea what to do with that expression, so it just fails. When you come across runtime errors that you don't understand, the best thing to do is look it up. My preferred website for doing so is stackoverflow.com. You can copy and paste the error message and then look for similar questions to what you're experiencing. When you click on the question, you'll often find a suitable answer. Now, the final type of error is a semantic one. This is when the output of the program is not what you expected. Let's take a look at an example. We're going to print out hello Alice. We'll start by creating a variable called name, and we'll set it equal to Alice. And hit enter. Next, we're going to use our print statement, and we're going to include hello and then name, and enter. Oh no, look what happened, we have hello name instead of hello Alice.

PAN-AFRICAN ROBOTICS COMPETITION 14

That's because we didn't use the proper variation of the print method. Python didn't understand that we wanted it to use the name variable. Semantic errors are the most challenging to troubleshoot, it's best to make tiny changes and then run your code. That makes it easier to figure out where you introduced the error. Also, I find going for a short walk helps me to clear my head and come back to the problem with fresh ideas. Ultimately, you need to have a good sense of humor. Sometimes these issues pop up from the smallest of mistakes, just laugh it off and keep moving forward. It's all part of the process.

PAN-AFRICAN ROBOTICS COMPETITION 15

Chapter 3

SECTION A

Introduction to variables and data types

Writing code typically involves the handling of information. If we're making a game, we need to store the user's score. If we're creating a banking application, we'll need to have their current balance and so forth. We've already seen a few variables in the course so far, but now we're going to go into more detail about what they are and how they work. A variable is simply a container for a value. When we run our programs, the computer gives us space in its memory where we can put data that we want to use as a reference for later. This data is called a variable. Much like how we label jars in our kitchen so we know where to go for our favorite cookies. We declare variables in Python by giving them a name and then setting their value. This is called assigning the value. And this assignment is done with the assignment operator, which is the , (=). For example;

age = 36

As we see here, age is the name of our variable, and because of the equals sign, we are assigning it the value of 36. That means that somewhere in the computer's memory, it's made space for our variable and stored our value in it. Later, when we ask the computer to print what's inside the age variable, it prints out 36, the value that we assigned previously. Although we're using an equals sign, try not to think of it the same way you did in high school algebra. In programming, the equals sign means I want to take the value on the right and store it in the variable on the left. It doesn't mean the two sides are equal. That's important to keep in mind. Okay, let's look at another example.

email_address = “John.doe@example”

PAN-AFRICAN ROBOTICS COMPETITION 16

This time, we've created a variable named email address, and we've assigned it to the following value. [email protected]. If we run this program, we can see that the values of our variables are printed out. Now even though we've created both of these variables by giving them a name, there's something different about the value that we assigned them. With the first value, we are only using numbers, and for the second value, we have double quotes with letters and symbols inside. This is because we want the variables to represent different data types. A allows us to put our variable in a particular category so that the computer knows how much space to give us in its memory. And it generally knows how we plan to use our variable later on in the program. In this example, the 36 is an integer, like what we're already familiar with from math class. In case you've forgotten, an integer is a whole number, no decimal places, and the letters and symbols inside of the double quotes is called a string because it's made up of a string of characters. In fact, you can check the type of any value or variable in Python by using the type function. Let's take a look. We'll print out the type of the age and then the email address variables.

And look, the age is in INT, or short for integer. And the email address is STR, short for string. There are many other types of values available in Python, as well.

PAN-AFRICAN ROBOTICS COMPETITION 17

SECTION B

Variables across languages

Depending on the programming language that you're working with, variables can behave in different ways. Some languages require that you define your variables and their types before you can use them, like Java, C#, and C++. For example, if we want to store the name of a cookie in Java, we would have to first declare that it's going to be of type string and then give our variable a name, cookie.

String cookie = “Sugar”;

System.out.println(cookie);

When we run this code, we get sugar as our output. Since we've defined our variable as type string, we can't then later decide to set this variable to a different type. Let's say an integer. When we compile our program, we'll receive an error because Java is a strict programming language. It doesn't allow you to reassign data types in this way. But if we were to compare this to a more relaxed language like Python, we don't need to declare a variable's type before using it.

cookies = “Sugar”

print(cookies)

Here, we declare the variable and use it at the same time. Notice how we only provide the name, not the type. But when we run this code, the Python interpreter was able to figure out the type based on the value that we provided. What's more? If we wanted to provide a value of a different type, Python has no issues with that, either. It just figures it out and keeps on moving. There are pros and cons to both styles. The more relaxed languages tend to be more flexible and result in less code, whereas with more strict languages, you have fewer surprises when the code is actually run. If you created an account balance variable as an integer, you don't have to worry about it later being set to fill, for example. Like all things in programming, there are a few rules that we have to follow when working with variables in Python.

PAN-AFRICAN ROBOTICS COMPETITION 18

First, variable names should contain only letters, numbers, and underscores. And even though numbers are allowed, the name shouldn't start with a number. For example, 3blindmice would not be a valid name, for instance. Second, spaces are not allowed in the name. Account space balance would be invalid, but account_balance would be just fine. Third, it's important to know that names are case sensitive. Capital C Cookies is not the same as lowercase c cookies. Python considers them to be two different locations in memory. And finally, variables cannot be keywords. These are reserved words that mean something special to the Python interpreter, like and, break, or try. We'll learn more about keywords shortly. In general, you want to use short, descriptive names that make your code easy to understand. Naming things takes practice. In fact, it's often cited as one of the hardest problems in computer science. Keep that in mind and be patient with yourself as you get used to working with variables.

PAN-AFRICAN ROBOTICS COMPETITION 19

SECTION C

Working with numbers

And before you start to have flashbacks to high school algebra, I'm not talking about complex mathematical calculations. We use numbers to store a person's high score in a game, or even the number of likes on a picture. Python treats numbers in a few different ways depending on how they're being used and the difference is largely based on whether it's a whole or fractional one. Let's look at a few examples. We can use the command line for this as we just want to do some basic math. So, let's go to the command line and start our Python prompt. We'll start out easy, two plus three. Let's try another one. Two, asterisk and then three. When we hit Enter, we get six. An asterisk or star is used for multiplication in Python. Let's go to another one. This is used for exponents. It's exactly the same as two times two, times two. Let's try another one. This is how we do division inside of Python. Now, what if we didn't want to have a remainder as a result of our division. Then, we could take advantage of a separate operator called the floor division operator. Let's see that one now. We'll use a three with a space and two forward slashes and then our two. This time, we only get one as a result. And the converse is also available to you. If you only wanted the remainder, For that one, we're going to do five, the percent sign This is going to give us two because three only goes into five one time and has a remainder of two.

PAN-AFRICAN ROBOTICS COMPETITION 20

Now, here's a table of the most common operators that you'll work with.

Symbol Operation + Addition - Subtraction * Multiplication / Division So far, we've only been using whole numbers or integers to do our calculations but in the real world, fractional numbers are a daily part of our lives. Let's say you earn $24.75 a day; would you be okay if we just drop the 75 cents and only paid you $24? Of course not. That extra 75 cents has value to you. In some programming languages like JavaScript, There's no distinction between numbers with and without decimal places. Whereas in most programming languages, numbers with decimal places are considered special numbers and they're typically called floats. A float is any number with a decimal point. A float is any number with a decimal point. It's short for a floating-point number. It's used for when more precision is required like in the case of our hourly rate. Let's look at how Python works with floats. First, we're going to try 0.2 plus 0.3. And when we hit Enter, we get 0.5. We use two floats and we get back a float in our answer. Let's try another one. 0.2 divided by 0.3. Whoa, it's a huge number. That's because Python tries to be as precise as possible. You may notice lots of extra decimal places when working with floats. Just ignore them for now. Later, we'll learn how to tweak it to our own liking.

PAN-AFRICAN ROBOTICS COMPETITION 21

SECTION D

Working with strings

Let's talk about strings. In programming, whenever we have to deal with text, be it an email address, someone's name, or even an emoji, we use strings. The name comes from the fact that it's a string of characters one after the other. The characters can be letters, numbers, symbols, and even spaces. They're typically represented by beginning and ending quotes. Strings can be passed directly to functions or they can be stored in variables. For example, we can use the print function in Python to display a message on the screen, like, print("Hi, there!") Notice that we have the opening and closing double quotes. These let Python know it should print out the characters in between the quotes just as we've typed them. We could also define a variable which contains the same string and we'd get the same result. In fact, with Python, we could use single quotes to create a string as well. But you might be wondering why would I want to use the double quotes version over the single quotes' version of strings? Well, it depends on the contents of your string. Let's see what happens when we print out the following string that's wrapped in double quotes.

print( "She said," double quotes, "Unbelievable," double quote, "to him." )

We receive a syntax error because we've confused Python with our nested double quotes. Instead, we will want to use single quotes to open and close our string. This way, Python knows just what we mean. And the inverse is also true. If we want to use single quotes, or an apostrophe inside of our string, like, "Let's get started," then we would use double quotes at the beginning and end. But keep in mind you don't want to mix single and double quotes together.

print(“Let’s play’)

Something like this print statement where we have an opening double quote and a closing single quote will also lead to a syntax error. When you're first starting out with programming, I recommend using the double quotes version of strings as your go to. Now that you've got a handle on strings, let's put 'them to work in our programs.

PAN-AFRICAN ROBOTICS COMPETITION 22

SECTION E

Working with comments Comments are notes to your future self and others to describe what your code does. Right now, we have small programs. We can keep the flow of it all in our heads, but over time as you continue to grow your programming skills, you'll be writing much longer programs. Some may even be thousands of lines of code spread over dozens of files. It would be impossible to keep all of that in your head. By adding comments to your code, you can document the purpose of the different variables, functions, and classes. You can think of them as virtual sticky notes. In python comments are started with hash marks. For example

#This is an expression that does addition ---->commented section

Age= 1 +3 ---> working code

print(Age) ---> working code

So, when Python sees this hash mark, it knows that it can ignore the rest of the line. Other than serving as reminders for us, we can also use comments to help temporarily ignore some code. Programmers use this technique all of the time. It's called commenting out code. Comments are a powerful tool for programmers, and as you've seen, we can use them to serve as reminders, provide explanations for other developers, and even help us with debugging code.

PAN-AFRICAN ROBOTICS COMPETITION 23

Chapter 4

SECTION A

Making decisions in code Have you ever received a note from someone that read, "Would you like to go out?" And the options were yes, no, or maybe. As humans, maybe is often a valid response to a question. It's not quite yes, but not exactly no. However, computers are different. Things are absolute. There's only yes or no, true or false, one or zero. Any expression that breaks down to either true or false is called a Conditional or Boolean expression. For example, does the number 4 equal to 2 times 2 Yes, that would evaluate to true. But is 4 greater than five? No, then it will be false. And finally, here's an example that doesn't involve numbers. Is my name Frank? Nope, it's Kwame. This would evaluate a false as well. These are Boolean expressions. But as we've learned, computers don't speak our language. We can't just ask a question directly the way we have it here. And that's where relational operators come into play. We've already worked with several operators, we've used arithmetic operators, like the plus for addition, or the percent sign for modulo. We've also used the equal sign for assignments. Relational operators work with two operands, and they return a value, true or false, based on their to each, thus the name. The first we'll look at is the operator. It's represented by a double equal sign (==), and it's used to evaluate the equality of the operands. As an example,

4 == 2 * 2

will be true. The left side of the operator equals the right side of the operator. Here's another example.

name = "Kwame”

Name == “Frank” -----> false

We have a variable called name. And we've said it to equal to the string Kwame. Then we use the operator to compare it to the string Frank. The result will be false because these two strings

PAN-AFRICAN ROBOTICS COMPETITION 24

are not the same. Let's come over to our python shell, and we'll do a rapid-fire round of conditional checks. Let's start out easy.

We got back false, because of course, five is not the same as four. But what If we wanted to check the fact that they are not the same? Then we would use the not equal sign. That looks like this.

Let's try another one. Let's check for five being greater than four. that you already know from mathematics. So we'll put our five, space, the greater than sign, and then the number four. When we hit Enter, Now if you forget which way to place the angle bracket, just remember the hungry alligator opens his mouth to the bigger number. Okay, let's look at another example. then

PAN-AFRICAN ROBOTICS COMPETITION 25

we're checking for five being less than four. So let's do that now. Five, space, less than sign, and then the number four. And of course, we get back false

Are you starting to get the hang of relational operators now? Let's do a few more. This time, we're going to create some variables. Ex.1 First, we're going to create a variable named age, and we'll set it equal to 15. Then, we'll create another variable named age_to_drive. Now, let's do some comparisons with these two variables. Now, let's do some comparisons with these two variables. First, we'll check if age is equal to, First, we'll check if age is equal to, using the double equal sign, age to drive. using the double equal sign, age to drive. What did you get?

Here the Python interpreter is comparing the values of the two variables, is comparing the values of the two variables, and yes, the value 15 is equal to the value 15. and yes, the value 15 is equal to the value 15. There are a few other relational operators available in Python as well. available in Python as well. Here's a listing of them and how they're used.

Symbol Operation Examples == Equal to 4 == 4 //True != Not Equal to 4 != 4 //False < Less than 4 < 5 //True > Greater than 4 > 5 //False >= Greater than or Equal to 4 >= 4 // True <= Less than or Equal to 4 <= 5 //True

PAN-AFRICAN ROBOTICS COMPETITION 26

SECTION B

Exploring conditional code

In the real world, we make decisions based on current conditions all of the time. If it's raining, I'll take my umbrella. If I'm sleepy, I'll grab a cup of coffee and so forth. The most common way for a computer to make decisions is by means of an if statement. . An if statement has this general structure.

If (condition)

do work

end if

It starts with the word if, that's where it gets its name from, then it checks some condition, and if that condition is true, then it will do the work that you've placed inside of it. To visualize this, think of it as a flow chart with only one check, if it's true, then the program will proceed to execute the statements. If not, then it just ignores those statements as if they don't exist. Here's a simple if statement in Python.

If 5 < 6:

print (“Yes, 5 is less than 6”)

It starts with the word if, then we have our condition, or boolean expression, five less than six. Next we have a colon, this is part of the syntax, or rules, of the Python if statement. And on the next line we have an indented line of code. This contains a print statement that will run if our condition is true. The indentation in Python is very important because that's how the interpreter knows which statements belong to the if. In fact, we have a name for statements that are grouped together this way in programming. It's called a block. In this example,

If 5 < 6:

print (“Yes, 5 is less than 6”) ----> block

PAN-AFRICAN ROBOTICS COMPETITION 27

there's only one statement in our block, but we could easily extend it like this.

If 5 < 6:

print (“Yes, 5 is less than 6”) ----> block

print(“Everyone knows that”) ----> block

And now we have two statements in our block. In Python, the block is ended as soon as we come to a line that's not indented anymore. It's standard in Python to use four spaces for doing some indenting. When we click tab, the IDE automatically converts this to spaces for us, which is pretty handy. If statements allow a program to take different paths while it's running. So far, we've just gone from top to bottom processing every single line only one path, but that's boring and it doesn't give us much opportunity to interact with the user. Now, we know how to switch things up based on some condition and we can start to write much more interesting programs.

PAN-AFRICAN ROBOTICS COMPETITION 28

SECTION C

Working with simple conditions With if statements, we've discovered a way to add a bit more flexibility and excitement to our programs, but so far, if the condition is false, then we just don't do anything. But typically, we'll want to take some action in this case as well. This is done with the if-else statement. It looks very similar to our normal if statement, except that it has the else keyword along with a colon, followed by a code block. In programming, this is called the else clause, because you never find it without an accompanying if statement. Just like in English, if I said, every morning before I go to work, and that's it, that would be an incomplete thought. It's just a clause. I'd have to add something like, every morning before I go to work, I enjoy a cup of coffee. Now and the thought is complete. Similarly, we don't use the else clause without an if statement. Let's look at an example.

If 5 > 6:

print(“5 is greater than 6. Weird!”)

else :

print(“5 is not greater than 6”)

If five is greater than six, then we're going to print five is greater than six, weird! Otherwise, if it's not true that five is greater than six, then we're going to print five is not greater than six. When this code is run, first the condition of the if statement will be checked, and since five is not greater than six, then it'll evaluate to false. Since the condition is false, it's going to skip over the if's code block and drop down to the else clause. With if-else statements, we will always execute one of the code blocks depending on the result of the condition test. This makes it perfect for when we need some action to take place in our programs.

PAN-AFRICAN ROBOTICS COMPETITION 29

SECTION D

Conditionals across languages By now you're pretty familiar with conditionals in Python. We start with an if, followed by our condition, then we end the condition with a colon. Then on the next line we indent the block of code that we want executed. And the else is very similar, except there's no condition to check. In the Java programming language, the if else statement has a slightly different syntax.

if(5 > 6) {

--->block

}

Remember, syntax is just the same thing as saying rules for how a programming language expects its code to be written. After the if keyword, there's a set of opening and closing parentheses. Inside these parentheses is where you put the condition you want to be tested. And instead of a colon after the condition, a pair of opening and closing curly braces are used to denote the code block for the if. The same thing is true for the else clause. Now although it's customary to indent the statements in the code blocks, it's not a requirement the way it is for Python. Let's look at one final example with the Ruby programming language. Ruby is known for its ease of use and flexibility. But just like the other languages, the structure of the if else statement is the same, but the syntax differs.

If 5 > 6

puts “nope”

else

puts “yes”

end

With Ruby there are no parentheses or a colon to separate the condition. Even the else clause just stands on a line all alone. The one thing that's more noticeably different is the addition of

PAN-AFRICAN ROBOTICS COMPETITION 30

the end keyword. This is how Ruby notes that it's done with this if else statement. Not based on indentation or a curly brace like Python and Java. The cool thing about learning the basics of programming is that once you grasp the structure of the core statements and principles, you can more readily recognize them across all languages.

PAN-AFRICAN ROBOTICS COMPETITION 31

References https://en.wikibooks.org/wiki/Programming_Fundamentals https://www.linkedin.com/learning/programming-foundations-fundamentals-3/what-is-a- programming-language

PAN-AFRICAN ROBOTICS COMPETITION 32