# learn python programming for robotics
We believe you already have basic concept of programming
or you have been already familiar with one programming language like c
.
In this tutorial, we’ll introduce the basic concepts of python
programming, which will be central to the programs that you will run on your robot.
# Why Python ?
There are many different languages in which computers can be programmed, all with their advantages and disadvantages. Python dispenses with a lot of the usual things which take up time in programming, such as defining and casting variable types. Also, there are a huge number of free libraries
for it, which means you don't have to "reinvent the wheel" when you need to implement some basic functionality.
# Disclaimer
Before we begin: a word on learning. The way that you learn to code is by doing it; make sure you try out the examples, fiddle with them, break them, try at least one exercise from each section. So, on with the tutorial!
You will not be a programmer when you finish reading this page or even when you finish reading the final chapter. Programming proficiency takes practice and training beyond the scope of this guide.
Learning to code is a process. Sure, you can learn programming faster with a few key steps, but it's going to take regular practice. You have to begin somewhere, so let's get started!
# Using an interpreter
To run Python programs you need a something called an interpreter. This is a computer program which interprets human-readable Python code into something that the computer can execute.
For this course you don't require any interpeter install in computer. You can go to directly to programming section without doing any installation
things , We have embedded interpreter with each section
# Installing & Running
# 1. Installing python
This simulator work with python 2.7.X.
# Linux, BSD and Unix users
You are probably lucky and Python is already installed on your machine. To test it type python on a command line.
If you have to install Python, just use the operating system's package manager or go to the repository where your packages are available and get Python.
# Windows users
Python doesn’t come prepackaged with Windows.
- Go to Python Download page .
- Download python 2.7.x version
- Double-click the icon labeling the file python-2.7.x.exe.
# 2. Running code
In order to run code , Just move to code directory and type
python filename.py
# Your First Program
Hit the run button. The text Hello World! should appear in the output box.
Tasks
- Change the output with your name.
# Statements
A statement is a line of code that does something. A program is a list of statements. For example:
The statements are executed one by one, in order. This example would give the output
Number of bees: 12.
As you may have guessed, the print
statement displays text on the screen, while the other two lines are simple algebra
.
Tasks
- Find Remainder and Module of given two number .
# Strings
When you want the interpreter to treat something as a text value (for example, after the print statement above), you have to surround it in quotes. You can use either single (') or double (") quotes, but try to be consistent. Pieces of text that are treated like this are called ‘strings’.
# Comments
Placing a hash (#
) in your program ignores anything after the hash.
For example:
# This is a comment
print "This isn't." # But this is!
2
Tasks
- Describe above program with suitable comment.
# Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
To set a variable, simply give its name , followed by =
and a value.
# For example:
# User Input
You can ask the user to put some text into a variable with the raw_input function (we’ll cover functions in more detail later):
name = raw_input("What is your name?")
Tasks
- Average calculator
The first two lines of this program put two numbers entered by the user into variables a and b. (The input function is like raw_input
, but returns a number (e.g. 42) when you enter one, rather than a string (like "42").) Replace the comment with code that averages the numbers and puts them in a variable called average.
- Write a program which uses input to take an X and a Y coordinate, and calculate the distance from (0, 0) to (X, Y) using Pythagoras’ Theorem.
Hint: you can find the square root of a number by raising it to the power of 0.5, for example, my_number ** 0.5.
# Python Conditions and if statements
Python supports the usual logical conditions from mathematics:
- Equals: a
==
b - Not Equals: a
!=
b - Less than: a
<
b - Less than or equal to: a
<=
b - Greater than: a
>
b - Greater than or equal to: a
>=
b
Here is an example of if statement :
# Concept: Code blocks and indentation
In the previous section, you probably noticed that the statements ‘inside’ the if statements were indented relative to the rest of the code. Python is reasonably unique in that it cares about indentation
, and uses it to decide which statements are referred to by things like if statements.
Python relies on indentation, using whitespace, to define scope in the code. Other programming languages often use curly-brackets ({}
) for this purpose
A group of consecutive statements that are all indented by the same distance is called a block. if statements, as well as functions and loops, all refer to the block that follows them, which must be indented further than that statement.
To find the limits of an if statement, just scan straight down until you encounter another statement on the same indent level. Play around with this example until you understand what’s happening.
Python doesn’t mind how you indent lines, just so long as you’re consistent. Some text editors insert indent characters when you press tab; others insert spaces (normally four). They’ll often look the same, but cause errors if they’re mixed. If you’re using an on-line interpreter, you probably don’t need to worry. Otherwise, check your editor’s settings to make sure they’re consistent. Four spaces per indent level is the convention in Python. We’ll now move on from this topic before that last sentence causes a flame war.
Tasks
Write a program that asks the user for their age, and prints a different message depending on whether they are under 18, over 65, or in between.
# Python Array
There are four collection data types in the Python programming language:
- List is a collection which is
ordered
andchangeable
. Allows duplicate members. - Tuple is a collection which is
ordered
andunchangeable
. Allows duplicate members. - Set is a collection which is
unordered
andunindexed
. No duplicate members. - Dictionary is a collection which is
unordered
,changeable
andindexed
. No duplicate members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.
# Lists
Lists store more than one value in a single variable, and allow you to set and retrieve values by their position (‘index’) in the list. For example:
You can find out the length of a list with the len function, like so:
print ("There are", len(thisList), "items on your list.")
Finally, you can add a value to the end of a list with the append method:
thislist.append("xyz")
The values in a list can be of any type, even other lists. Also, a list can contain values of different types.
# while loops
The while loop is the most basic type of loop. It repeats the statements in the loop while a condition is true.
For example:
The condition is the same as it would be in an if statement, and the block of code to put in the loop is denoted in the same way, too.
# for loops
The most common application of loops is in conjunction with lists. The for loop is designed specifically for that purpose. For example:
Tasks
Write a program which calculates the average of a list of numbers. You can specify the list in the code.
# Defining functions
Of course, you’ll want to make your own functions. To do this, you precede a block of code with a def statement, specifying an [identifier] for the function, and any parameters you might want. For example:
To return a value, use the return statement.
Tasks
Write a program that takes as input an angle (in radians) and the length of one side (of your choice) of a right-angled triangle. Print out the length of all sides of the triangle.
You can return multiple values from a function like so:
def foo():
return 1, 2, 3
x, y, z = foo()
2
3
4
# Create N * N Matrix filled with Zero
You should make a list of lists, and the best way is to use nested comprehensions:
Tasks
Try to change size and value of matrix.
Print first row.
# Size of Column
It is equal to number of element in first row.
print (len(matrix[0]))
2
3
# Size of Row
It is equal to number of element in list.
print (len(matrix))
2
3
# Range Function
It generates a list of numbers, which is generally used to iterate over with for loops. There's many use cases. Often you will want to use this when you want to perform an action X number of times.
# Python's range() Parameters
The range() function has two sets of parameters, as follows:
# range(stop)
- stop: Number of integers (whole numbers) to generate, starting from zero. eg. range(3) == [0, 1, 2]
0-index based
.
# range([start], stop[, step])
- start: Starting number of the sequence.
- stop: Generate numbers up to, but not including this number.
- step: Difference between each number in the sequence.
Note that:
- All parameters must be integers.
- All parameters can be positive or negative.
# Math built-in Function
In order to use built in function , you have to import the module using
import mudule_name
The math module is a standard module in Python and is always available. To use mathematical functions under this module, you have to import the module using
import math
# List of Function
Function | Description |
---|---|
fabs(x) | Returns the absolute value of x |
factorial(x) | Returns the factorial of x |
floor(x) | Returns the largest integer less than or equal to x |
fmod(x, y) | Returns the remainder when x is divided by y |
frexp(x) | Returns the mantissa and exponent of x as the pair (m, e) |
fsum(iterable) | Returns an accurate floating point sum of values in the iterable |
isfinite(x) | Returns True if x is neither an infinity nor a NaN (Not a Number) |
isinf(x) | Returns True if x is a positive or negative infinity |
modf(x) | Returns the fractional and integer parts of x |
trunc(x) | Returns the truncated integer value of x |
exp(x) | Returns e**x |
expm1(x) | Returns e**x - 1 |
pow(x, y) | Returns x raised to the power y |
sqrt(x) | Returns the square root of x |
acos(x) | Returns the arc cosine of x |
asin(x) | Returns the arc sine of x |
atan(x) | Returns the arc tangent of x |
atan2(y, x) | Returns atan(y / x) |
cos(x) | Returns the cosine of x |
hypot(x, y) | Returns the Euclidean norm, sqrt(x*x + y*y) |
sin(x) | Returns the sine of x |
tan(x) | Returns the tangent of x |
degrees(x) | Converts angle x from radians to degrees |
radians(x) | Converts angle x from degrees to radians |
acosh(x) | Returns the inverse hyperbolic cosine of x |
asinh(x) | Returns the inverse hyperbolic sine of x |
atanh(x) | Returns the inverse hyperbolic tangent of x |
cosh(x) | Returns the hyperbolic cosine of x |
sinh(x) | Returns the hyperbolic cosine of x |
tanh(x) | Returns the hyperbolic tangent of x |