You are on page 1of 12

RHEA JOY B. CELZO BSGE-5 FEB.

6, 2018

What is Python?
Python is an interpreted, object-oriented, high-level programming
language with dynamic semantics. Its high-level built in data structures,
combined with dynamic typing and dynamic binding; make it very attractive for
Rapid Application Development, as well as for use as a scripting or glue
language to connect existing components together. Python's simple, easy to
learn syntax emphasizes readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages program
modularity and code reuse. The Python interpreter and the extensive standard
library are available in source or binary form without charge for all major
platforms, and can be freely distributed.

Python Syntax
The syntax of the Python programming language is the set of rules that
defines how a Python program will be written and interpreted (by both the
runtime system and by human readers).

A Python program is read by a parser. Python was designed to be a


highly readable language. The syntax of the Python programming language is
the set of rules which defines how a Python program will be written.

Python Line Structure:

A Python program is divided into a number of logical lines and every


logical line is terminated by the token NEWLINE. A logical line is created
from one or more physical lines.

A line contains only spaces, tabs, formfeeds possibly a comment, is


known as a blank line, and Python interpreter ignores it.
A physical line is a sequence of characters terminated by an end-of-line
sequence (in windows it is called CR LF or return followed by a linefeed and
in Unix, it is called LF or linefeed). See the following example.
Comments in Python:

A comment begins with a hash character(#) which is not a part of the string
literal and ends at the end of the physical line. All characters after the #
character up to the end of the line are part of the comment and the Python
interpreter ignores them. See the following example. It should be noted that
Python has no multi-lines or block comments facility.

Joining two lines:

When you want to write a long code in a single line you can break the logical
line in two or more physical lines using backslash character(\). Therefore
when a physical line ends with a backslash characters(\) and not a part of a
string literal or comment then it can join another physical line. See the
following example.
Multiple Statements on a Single Line:

You can write two separate statements into a single line using a semicolon
(;) character between two line.

Indentation:

Python uses whitespace (spaces and tabs) to define program blocks


whereas other languages like C, C++ use braces ({}) to indicate blocks of
codes for class, functions or flow control. The number of whitespaces (spaces
and tabs) in the indentation is not fixed, but all statements within the
block must be the indented same amount. In the following program, the block
statements have no indentation.
This is a program with single space indentation.

This is a program with single tab indentation.

Here is another program with an indentation of a single space + a single tab.


Python Coding Style:

 Use 4 spaces per indentation and no tabs.

 Do not mix tabs and spaces. Tabs create confusion and it is recommended
to use only spaces.

 Maximum line length: 79 characters which help users with a small


display.

 Use blank lines to separate top-level function and class definitions


and single blank line to separate methods definitions inside a class
and larger blocks of code inside functions.

 When possible, put inline comments (should be complete sentences).

 Use spaces around expressions and statements.

Python Reserve words:

The following identifiers are used as reserved words of the language,


and cannot be used as ordinary identifiers.

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as el if or yield

assert else import pass

break except in raise


Python Lists and Functions

A list is a sequence of values. You could visualize a list as a


container that holds a number of items, in a given order.

To create a list in Python, simply add any number of comma separated


values between square brackets. Like this:

In Python, a list can contain items of varying data types. For


example, here's a list that contains a string, an integer, and another
list.

When we print both of those lists we get this:

Return the Number of items in a List

You can use the len() function to return the number of items in a list.

Adding the len() function to the print() function will print that number out.

Accessing a List Item:

You can pick out a single list item by referring to its index.
Remember, Python uses zero-based indexing, so start the count at 0 when doing
this.

So to find out what the second item in the planet list is, do this:
You can also select a range of items by specifying two indexes

separated by a colon. Like this:

Functions are a fundamental part of Python (and most other


programming languages). Python includes a large number of built -in
functions, but you can also create your own functions.

You use functions in programming to bundle a set of instructions


that you want to use repeatedly or that, because of their complexity,
are better self-contained in a sub-program and called when needed. That
means that a function is a piece of code written to carry out a
specified task. To carry out that specific task, the function might or
might not need multiple inputs. When the task is carried out, the
function can or cannot return one or more values.

There are three types of functions in Python:

 Built-in functions, such as help() to ask for help, min() to get


the minimum value, print() to print an object to the terminal,… You can
find an overview with more of these functions here.
 User-Defined Functions (UDFs), which are functions that users
create to help them out; And
 Anonymous functions, which are also called lambda functions because
they are not declared with the standard def keyword.

Here's an example of a basic function.

This function simply multiplies a number by itself. The number is provided as


an argument when the function is called.
Here's a rundown of each line:

1. The def keyword introduces a function definition. It must be followed


by the function name and the parenthesized list of formal parameters.
In this case, the function name is multiplyMe and there's one parameter
(x). This means that the user must pass one argument when calling the
function.
2. The next line is where the body of the function begins. The function's
body must be indented. In our example, we simply multiply the argument
by itself and assign it to a variable called y.
3. The return statement is used to return a value from a function. In this
case, we return the value of y.
So we can now call the above function like this:

Built-In Python Functions

Before you decide to sit down and write a wonderful function, ask
yourself "is there already a build-in function for this?".

Python includes a number of functions built right into the interpreter


that you can use straight away. Sometimes you might find that there's already
a function that does what you want, or at least part of it.

For example, Python includes a sum() function that could be used


instead of calculation.sum that we used in the above example. In fact, the
built-in sum() function does more, as it allows you to provide a list of
numbers (i.e. it can add more than two numbers at a time).

The following functions are always available, as they're built right in to


the Python interpreter. If you're familiar with other programming languages,
you'll probably recognize some of these and guess how they work. In any case,
see the official docs for more information about how each one works.

 abs()  bytearray()  complex()


 all()  bytes()  delattr()
 any()  callable()  dict()
 ascii()  chr()  dir()
 bin()  classmethod()  divmod()
 bool()  compile()  enumerate()
 eval()  iter()  repr()
 exec()  len()  reversed()
 filter()  list()  round()
 float()  locals()  set()
 format()  map()  setattr()
 frozenset()  max()  slice()
 getattr()  memoryview()  sorted()
 globals()  min()  staticmethod()
 hasattr()  next()  str()
 hash()  object()  sum()
 help()  oct()  super()
 hex()  open()  tuple()
 id()  ord()  type()
 input()  pow()  vars()
 int()  print()  zip()
 isinstance()  property()  __import__()
 issubclass()  range()

How to use Loops in Python


To keep a computer doing useful work we need repetition, looping back over
the same block of code again and again. This post will describe the different
kinds of loops in Python.

Python programming language provides following types of loops to handle


looping requirements.

Sr.No. Loop Type & Description

1 while loop

Repeats a statement or group of statements while a given


condition is TRUE. It tests the condition before executing the
loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates


the code that manages the loop variable.

3 nested loops

You can use one or more loop inside any another while, for or
do..while loop.
Loop Control Statements
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that
scope are destroyed.

Python supports the following control statements. Click the following links
to check their detail.

Sr.No. Control Statement & Description

1 break statement

Terminates the loop statement and transfers execution to the


statement immediately following the loop.

2 continue statement

Causes the loop to skip the remainder of its body and


immediately retest its condition prior to reiterating.

3 pass statement

The pass statement in Python is used when a statement is


required syntactically but you do not want any command or code
to execute.
UAV PROGRAMMING
Basics Of Programming A Drone

Drone technology is incredible and advancing quickly. It is currently


at the point where every man, woman or child could program a drone to do
unthinkable things using nothing more than a drone and a laptop. This guide
will teach you how to have an AR Parrot Drone 2.0 fly autonomously in just 15
minutes. The reason to use a Parrot Drone (you can certainly use a different
drone) is because it makes an excellent entry level drone that is sturdy,
stable and reasonably priced for hobbyists and professionals alike.

This method of programming your drone uses the Felixge Node Library and is
available as free code for anyone to use. Before getting started, it is
recommended to understand the laws around flying your drone. For example, you
can fly your drone around some landmarks, but not others. You can fly your
drone in the outback or on a deserted beach, but not on Fraser Island or in
the Daintree Rainforest (in Australia). The rules can be complicated and
change often, so please ensure you read before flying.

Step 1: Have A Drone


Of course, this is the first step. It is recommended, to begin with an
AR Parrot Drone 2.0, the 1.0 model may work but this is not guaranteed, the
technology advances quickly! Next is to download the AR.FreeFlight 2.4 app on
your smartphone or tablet. And if you are a beginner, please leave the indoor
bumper hull on to minimise damage. Usually best to begin flying in an open
field or park too.

Step 2: Node JS
Download Node JS to your computer. This isn’t a hard one. Please note,
there are a great many programming languages that can be used to interface
with your drone including Node JS, Java, C#/.Net, Python, Scala, Ruby,
Clojure as well as apps such as flyver.co, Dronekit and Tickle. For this
project, we are using Node JS.

Step 3: Code Line/Prompt


On your PC or laptop open Command Prompt. Enter “npm install ar-drone”
without the quotation marks. This is how we will access the Felixege node.js
library for high-level commands. Meaning, you can control your drone from
your PC.

Step 4: Testing
To be sure this has set up correctly so far, turn the drone on then connect
your laptop to the wifi from your drone. Likely called something along the
lines of “drone####.” Open the node.js program and type in the next four
lines of code, hitting enter after each line. Please note that the drone will
take off and hover after the third line.

 Var arDrone = require(‘ar-drone’);


 Var client = arDrone .createClient();
 Client.takeoff();
 Client.land();

This allows us to ensure the drone is connected, can take off and land.

Step 5: Autonomous Program


This is the step at which we will make autonomous programs. The advantage of
this over what we did in step 4 (manual entry) is that we can send a whole
program to the drone instead of typing one command at a time. This is
achieved by writing programs in JavaScript.

Open a text editor, such as Sublime Text, open a new file and type the lines
of code in and be sure to save the file with .js at the end. This ensures it
is created as a JavaScript file. For now, we are only entering this code
(each number is a new line). We will save it as test.js

1. Var arDrone = require(‘ar-drone’);


2. Var client = arDrone .createClient();
3.
4. Client.takeoff();
5. Client.land();
6.
7.
8. Client
9.
10. .after(5000, function() {
11. This.land();
12. });

Step 6: Running Programs


To run the program ‘test.js’ we have just created navigate to where it was
saved and using the command prompt. Turn your drone on, connect it and the
laptop to the wi-fi connection. Type the following line of code and hit enter
(for example, if you saved it to a folder named Drone on your C drive.

1. Node c:\Drone\test.js

You will know if this ran successfully if the drone takes off, hovers and
then lands automatically.

By now you should begin to understand the power a laptop and a drone
can have. In less than 15 minutes we have implemented a program to take off,
hover and land a drone. All of which can be done by simply pressing “enter”
after the program is written. It’s likely you will be excited and wanting to
learn and implement ever more complicated and amazing functions for your
drone. Before you do, though, bear in mind the constantly changing laws
around drone flying, as mentioned above. With that in mind, have fun and
explore the incredible capabilities of your drone.

You might also like