Python - ncsurobotics/SW8S-ROS GitHub Wiki

Table of Contents

Python

Welcome, this is the Python New Member Project! This will allow you to practice very basic concepts in python.

What is Python?

Python is an object-orientated programming language or in other words a programming language that is heavily reliant on classes and objects. You will learn more about what classes and objects are at the end of this activity.

Data, Strings, and Boolean

A data type is an attribute of data that tells your computer or compiler how to interpret it. The five common data types are integers, strings, floating points, bools, characters.

  • Integers: this data type represents negative and positive whole number and not fractional.
0,1,2,-3,
  • Floating Point: this data type represents decimal/fractional numbers.
1.25,0.4444,-0.25
  • Strings: this data types represents information that may take the form of text. Text includes both words/phrases and even numbers that you maye want too take string form.
Hello, (910)754-8673
  • Boolean: this data type represents values true or false, where true equals 1 and false equals 0.
True, False
  • Characters: this data type is used to store a single letter, digit, blank space, symbol, or punctuation mark.

Printing, Variables, and Inputs

Printing

Printing is a function that allows us to display information communicated in the script to the terminal which enables us (the users) to view any desired information in a more user-friendly way.

Let’s run through some easy exercises to show you how you can use the print function.

My name is Tajah Trapier, I want to make a script that prints a greeting with my name into the terminal, “Hello, my name is Tajah Trapier.”.
We first start by writing the “Print” function. The print function consists of the statement “print” followed by a set of parenthesis (you do not have to include parenthesis in newer versions of Python). In other words, the print function looks like this, print() or print.
Inside the parenthesis, will be the information you want to print. So if I were to print my greeting, I would do this…
print(“Hello, my name is Tajah Trapier.”)
As a result, I would see this in my python IDE terminal.
Hello, my name is Tajah Trapier.
Checkpoint 1: Let’s say you want to print the sentence, “Why am I doing this?”. How would you do this?

Answer: You would place this string inside a print() function.
print(“Why am I doing this?”)
You may have noticed that all of my strings have quotations(“”) around them. This is important if you want your script to know that it is printing a string, if you do not have quotations around the text you want to print, Python will not recognize what you are trying to print as a string. As a result, unless the information you are trying to print is a numerical data type, there will be an error because words, unless “True” (1) or “False” (0), do not correlate as numbers. It is important to note that if you want to print text or a string, then you should place the desired information between quotation marks.

Variables

In python, variables exist. Variables serve as a way for you to save information so that it may be easily recalled without having to rewrite that information. For example, you want to print a greeting whenever you want without having to write out the entire greeting. The variable can be any name but for future reference your variable should be specific to the task it does or data it takes and it is recommended that you use camelCase.

camelCase is a formatting method for variables where the first word of your variable is lowercase and the words that follow are uppercase.

For example you want to make a variable called data collector, you would format it like this... dataCollector. If you wanted to make a variable called ::send integer data, you would format it like this... sendIntegerData.
First let’s consider the variable we will use, let’s use greeting.
You would set the string equal to this variable using an equal sign (=). We will use the string “Hello, how are you?”. What we want would look like this…
greeting = “Hello, how are you?”

We have created the variable, but at this time the string we want to view will not print itself if the script we are using is ran. In order to ::ensure our string will be printed in the terminal we would have to print the variable. This is done like this…
print(greeting)
You can also print whatever your variable is set to by calling the variable. You can call the variable by typing it into the terminal.

Let's try another exercise. Say you want to print a string that says hello to someone but you want to be able to change the name of the person you are talking to without rewriting your entire greeting. How could you do this?
We want to print "Hello (name)". We would first start by creating our variable. We will use the variable name and set it equal to the name we want to include.
name=“Tajah”
Afterwards, we will type in the print function followed by the words you want to be read before the name we want to include.
print(“Hello”
We then want to append the variable we are interested to the string we just wrote. There are two ways this can be done, using commas (,) or plus signs (+).
  • It is important to keep in mind that when using commas (,) spaces will be added before and after the variable, when using plus signs (+) there will be no spaces included before and after the variable.
Using comma(,) --> print(“Hello”, name, “.”)
Output: Hello Tajah .
Using plus sign(+) --> print(“Hello ” + name +“.”)
  • Notice how a space was placed after "Hello" in the plus sign scenario because without this space there would be no space between the name and "Hello".
Output: Hello Tajah.
Without the space after "Hello" your output would look like this...
Output: HelloTajah.

Inputs

What if you want to ask a question and save the answer as a variable? You can use the "input" function for that. The input function input() is a function that allows you to save a string that will be prompted in the terminal to be answered to.

For example, you want to ask someone "How's the weather?" and what the user to respond. You would first start by writing out the input function input( followed by your question prompt and a closing parenthesis input(“How’s the weather?”) .

As a result you will see your terminal prompt you for a response to which you can type any input to.

What if you want to save the input and apply it elsewhere? Easy, set your input function equal to a variable.

if, elif, and else Statements

What are if, elif, and else statements? These are conditional statements, conditional statements are a method that allows for the computer to perform an action or make a decision based on whether a condition is met/holds True. For example, if the traffic light is green (True) then go if the traffic light is not green (False) stop.

if/else

If, elif, and else statements are common conditional statements that use the logic that ‘’’if’’’ a condition is found to be true then it will perform the following action and ‘’’else’’ or if it is not to be true but false then it will perform a different action. The typical structure of a if else statement is like this is...
if condition:

action
else:
action
Let’s use the previous example regarding the traffic light. We want to make a program that tells the user to go when the light is green but stop when the light is not green. How could we do this?
We would first consider the conditional statements we want to use. We could create a variable that can be set to either "green" or "red" and if the that variable is "green" the condition holds true otherwise the condition holds false. Let's call our variable trafficLight.
Before we begin, we should move from operating in the terminal or python shell and to a file. In your IDE create a new file and name it new_member_project. We start by setting our variable, for now we will set it equal to "green". trafficLight=“green”

Afterwards we will write our if statement, if else statements always begin with an if statement. Our condition will be if trafficLight equals "green".
if trafficLight == “green”
  • Notice that instead of using "=" we used "==". This is because we use "=" when setting a variable equal to a value, using "==" for comparison creates less confusion for the computer.
If we were to write this condition in our script file followed the enter key, we should see this.

On the next line, we will enter the action we wish the computer to perform for the given condition. In our case, we want to tell the user to go which can be done using a print statement. print(“Go”)

Now we want to implement our else statement. This is done by entering else on the next line.


On the next line we will enter the action we want implemented given that the condition is proven false. We want our script to print "Stop". print(“Stop”)

Try running the program, you should see this if trafficLight is equal to "green"...

and this if trafficLight is equal to "red".

elif

We have successfully made a program that tells the user to go when the traffic light is green and stop when the traffic light is red, but what about when the traffic light it yellow? Fear not, that is what elif is for.


elif is short for else if. elif allows for the computer to check for multiple conditions where if the elif statement isn't met the program will continue to the next elif or else statement. In our case, we want to write an elif statement that checks if our variable trafficLight is equal to "yellow". If our variable does, we will print "slow down" to the user. Between our if and else statement we will type elif trafficLight:==“yellow”

On the blank line, we will write our action in case the condition is found true. We want to print "Slow Down". print(“Slow Down”)


Set your variable equal to "yellow" and try running the program now. Your program should output this...

It seems like we're done but we're not, there is a scenario which we have not considered that could happen. What if the value our variable is set to isn't "green", "yellow", or "red"? Right now, our program would just tell the user to "Stop" but we only want the user told "Stop" if trafficLight is "red", how could we fix this?
Another elif statement!
We can place another elif statement after our first elif which functions to "Stop" the user when trafficLight is equal to "red".

We still have to add our else statement. We can use the else statement to output an error anytime our variable is equal to anything other than "green", "yellow, or "red". We can do this by adding else: to the line below our last line of code. After the else statement, we can have our program print "Error: Value Unrecognized".

Set your variable equal to "red" and run the program...

Try setting your variable to a random value and run the program...

Congratulations, you have written your first Python if/elif/else statement! :)

For and While Loops

We have already covered if/elif/else conditional statement but there are two more common conditional statements called for and while loops.

For

for loops are a type of conditional statement that performs the actions listed within in it for the amount of times specified by the user. It is structured like the following for i in number , where for is the calling of the conditional statement, i is the iteration or the current number of times you have ran your loop, and number is the number of times you want your loop ran. So if we were to say number is equal to 10 and we were to run for i in number for the first time. This line of code would mean running the first iteration of this loop of the 10 times it is intended to run.

Let's try an exercise, we want to make a script that takes a variable equal to 0 called digit and adds 1 to it each time for a total of 10 times. We could do this by writing out "digit = digit+1" ten times or by using a for loop. We should first determine how to structure our for loop. Our for loop would begin with for i in and we would want to set number so that it is iterable 10 times. In order to do this we can set number equal to range(1,10). We use range because it will create a list of numbers from 1 to 10 and since lists are iterable this works! Note that you cannot set your number variable equal to an integer because integers are not iterable. Inside the for loop is what we want performed 10 times, in our case it is "digit = digit+1"

While

Functions and Parameters

Classes and Arguments

Accessing Python from the Terminal

Sources

https://www.python.org/
https://dataled.academy/guides/data-types/

⚠️ **GitHub.com Fallback** ⚠️