Programming a Driverless Car Chapter 1 : Getting Started with Python

 INTRODUCTION

WHAT ARE DRIVERLESS CARS?

An autonomous car (also known as a driverless car, autoself-driving car, robotic car) is a vehicle that is capable of sensing its environment and navigating without human input. Many such vehicles are being developed, but as of May 2017 automated cars permitted on public roads are not yet fully autonomous. They all require a human driver at the wheel who is ready to take control of the vehicle immediately at any time.
Autonomous cars use a variety of techniques to detect their surroundings, such as radar, laser light, GPS, odometry, and computer vision. Advanced control systems interpret sensory information to identify appropriate navigation paths, as well as obstacles and relevant signage. Autonomous cars have control systems that are capable of analyzing sensory data to distinguish between different cars on the road, which is very useful in planning a path to the desired destination.
Who are Currently Working on Driverless Cars?
Right from Internet Giants like Google, Baidu to Tesla, Ford BMW, everyone who want to get in on the trend are working towards the change.
 

CHAPTER I

GETTING STARTED WITH PYTHON

 
Python is a great foundation because it has some cool features like readability, no parenthesis, type interfaces, duct typing, modular programming. Object oriented, extensible all these features make Python the obvious choice for Machine Learning.
Python uses less lines of code to express the concepts. Over the years, we’ve seen Self Driving Cars  become one of the greatest cutting edge technology which has become the forefront of future. Where Machine Learning and Artificial Intelligence have been used practically to make the driverless concept work and it is still progressing.
You can use Python for Data Analysis, building an Interface, Web development, financial transaction etc
This course will help you understand python programming language and how to get started with it, where we teach the fundamentals of it. This section is more like a refresher on Python.
By the end of this course, you’ll be familiar with Python syntax, will be able to practise what you have learnt. You’ll need to know the basics of programming though.
In this tutorial, we’ll talking about brief introductions and the modules related to machine learning. 
To begin with you’ll need to install Python
What is Python?
Python is a Programming language that is more geared towards scripting, used in companies where you have machine learning, artificial Intelligence and various other aspects of different projects. It is easy, dynamic and open source. The syntaxes are easy to understand, readable and easy to write. Overall Python is well structured, even if you have to take up a software written by someone else, you’d be able to understand it and start working from where they left quickly.

BASICS OF PYTHON

We’re going to learn the basics of Python, which acts as a building block for Artificial Intelligence and machine learning. We’ll be learning about defining Data Types, list dictionaries, various operators, defining functions etc. We’ll then learn about how classes, modules and inheritance works.
Why Should you use Python?

  • Python is Object Oriented.
  • Structure supports concepts such as Polymorphism, operator overloading and Multiple Inheritance
  • Python  is free (Open Source ) doesn’t require license.
  • Python is Portable & Powerful
  • Runs On every major platforms used today
  • Dynamics Typing, Built-in types & tools, library utilities, automatic memory management

Who uses Python
Python forms as a base for various technology products like Google, Disqus, Quora etc.
Understanding the syntax
Let’s take this example; In Java to print a Hello World, you see that there are 3 lines of code with the print statement to get the output. Whereas in Python the same printing of an output would require only a Print command to get it. It’s compact and intuitive, isn’t it?
Java:

public class HelloWorld {
Public static void main (String [], args) {
System.out.printIn(“Hello, World!”)
}
}

Python:
Print “Hello World”

There are two versions of Python currently available
Python 2.x
Python 3.x
Let’s see the basic differences
Python 2.x is legacy, Python 3.x is the current version
The most visible difference is probably the way the “print” statement works.
In Python 2 it’s a simple statement
 Print “Hello World” – it’s simple
In Python 3 it’s a function
   print(“Hello World.”) – You’ll have to write it as a function, you’ll have to pass in the string as an input argument as to whatever you’d want to print.
The main difference between Python 3 and 2 is that Python 3 is cutting edge, it’s new and most of the latest development happen on PY3. Most of the new features will be implemented in there rather than being added to 2.x
Python 3 is a nicer and more consistent language, BUT, there is a very limited third-party module support for it. This is likely to be true for at least a couple of years more. So, all major frameworks still run on python 2, because that is the version you are going to end up actually using.
We’ll be using Python 2 for this course.
Let’s start with the Installation
Installing Python
Assuming you have a Windows operating system. We’ll show you how to install it on that particular system.

  • Open a Web browser and go to https://www.python.org/downloads
  • Follow the link for the windows installer python-versionxxx.msi
  • To use this installer python-versionxxx.msi, the windows system must support Microsoft Installer 2.0 . Save the installer file to your local machine and then run it to find out if your machine supports MSI.
  • Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished and you are done.

For Linux Operating system

  • Open a Web browser and go to https://www.python.org/downloads
  • Follow the link to download zipped source code available for Unix / Linux
  • Download and extract files
  • Editing the modules / Setup file if you want to customize some options

    • Run ./configure script
    • make
    • make install
  • This installs Python at standard location /usr/local/bin and it’s libraries at/usr/local/lib/pythonxxx where xxx is the version number of python

Getting Started with Python
Python Strings:
Strings in Python are identified as a contiguous set of characters in between quotation marks.
We can a define a string in any way or form, a string is a variable. First you associate a variable and then add a value to it. It is also possible to index characters inside particular strings.  
For example if you want the index of zero character, you write that string and enter the value And in parenthesis you enter 0, as it is the first index in a first array. Similarly, if you look below.
str=’Hello World!
print str # Prints complete string
print str[0] #Prints first character of the string
print str [2:5] #Prints characters starting from 3rd to 6th
print str[2:] #Prints string starting from 3rd character
Print str * 2 # Prints string two times
Print str + “TEST” #Prints concatenated string
If you want to set a particular characters and understand how to get the values out of it, you can also get multiple values out of it by adding a colon within a particular string.
For example, If you want to index a set of values from 2 to 5 , you’ll just mention 2:5 where the values at 3rd character and 5th characters will display.
In a similar way, you can use print statement where 2: will get you every character from the 3rd character till the end of the string.
You can also use, multiplication ( * ) which prints the strings the amount of times mentioned You can also use it in concatenation.
Let’s assign
Print “Hello World”
Hello World
print “Hello python!”
>>> x=”Hello Python”
>>> print x
Hello Python
>>> print x (0)
H
>>> print x[2] ( To print the 3rd character )
L
>>> print x[6] ( To print the 7th character)
P
>>> print x[2:4] ( To print the 3rd and 5th character )
Ll
>>> print x[2:6] ( To print the 3rd character and 7th character)
Llo
>>> print x[2:] ( If you want all the character after the 3rd character)
Llo python
>>> print x*2 ( Multiplication, If you want to print the same string twice)
Hello python Hello python
>>> print x*5 ( Repeat the same string 5 times )
Hello Python Hello  python Hello Python Hello Python Hello Python
>>> print x+’hi’ ( Concatenation, it’s taking two strings and combining it together)
Hello Python hi
>>> print x+ ‘ ‘ +’helloha’ (String manipulation)
Hello Python helloha
Python Lists
Lists are the most versatile of Python’s compound data types. A list contains items separated by commas and enclosed within square brackets ([]).
list1 = [‘hello’, 786, 4.1, ‘Ram’, 702 ]
list2 = [123, ‘Victor’]
print list1 # Prints complete list
print list1[0] # Prints first element of the list
print list1[1:3] # Prints elements starting from 2nd to 4th
print list1[2:] # Prints elements starting from 3rd element
print list2 * 2 # Prints list two times
print list1 + list2 # Prints concatenated lists
Lists work the same way, as the strings where the operators, functions work similarly.
Defining Lists
Let’s take this example, let’s define
a=[‘hello’,786,154,4.2,’howareyou’]
b=[45,56,7,’hi’]
print a (
[‘hello’, 786,154,4.2,’howareyou’]
>>> print b (
[45,56,7, ‘hi’]
>>> print a[0]
Hello
>>> print b[1]
56
>>> print a[:4]
[‘hello’, 786, 154, 4.2]
>>> print a[2:5]
[154, 4.2, ‘howareyou’]
>>> print b*2
[45, 56, 7, ‘hi’, 45, 56,7, ‘hi’, 45, ‘hi’]
>>> print b*5
[45, 56, 7, ‘hi’, 45, 56, 7, ‘hi’, 45, ‘hi]
>>> print a+b
[‘hello’, 786, 154, 4.2, ‘howareyou’, 4] (you’ll have to store it in the variable first)
>>> x=a+b
>>> print x
[‘hello’, 786, 154, 4.2, ‘howareyou’, 4]
The lists are always defined in the square brackets and the items that go inside the list, are separated by commas.
Positive and negative indices
>>> t= [23, ‘abc’, 4.56, [2,3], ‘def’]
Positive index: count from the left, starting with 0
>>> t[1]
‘abc’
Negative index: count from right, starting with -1
>>> t[-3]
4.56
>>> a[0]
‘Hello’
>>> a[-1]
‘Howareyou’
>>> a[-2]
4.2
>>> a [-3]
154
>>> x=”hello python”
>>> x[-1]
Now let’s manipulate a string from a particular variable to demonstrate negative indexes.
‘N’
>>> x[-3]
‘h’   
Python Tuples
A tuple is another sequence data type that is similar to the list. Unlike lists, however, tuples are enclosed within parentheses. They are immutable and you cannot mute it or add things to it. To manipulate is also easy.
tuple1 = (‘hello’ 786, 2.23, ‘victor’, 70.2)
tuple2 = (123, ‘jay’)
print tuple1 # Prints complete list
print tuple1[0] # Prints first element of the list
print tuple1[1:3] # Prints elements starting from 2nd to 4th
print tuple1[2:] # Prints elements starting from 3rd element
print tuple2 * 2 # Prints list two times
print tuple1 + tuple2 # prints concatenated lists
Lets define a Tuple A,
>>> a=(12, 45, 2.5, ‘hello’, ‘hi’)
Then, let’s define second tuple b.
>>> b=(4,4,4,’hi’)
>>> a+b  (Let’s concatenate both the Tuples)
And, this is the result you get.
(12, 45, 2.5, ‘hello’, ‘hi’, 4, 4.4, hi)
Let’s try extracting an element
As you can see the if you try extracting the element from index ‘0’,
>>> a[0]
You get
12
And other functions are similar to lists. Let’s move over to another important topic Dictionaries.
Python Dictionary
Dictionaries in Python are important and they are one of the most important data types in Python. They consists of key-value pairs. Every element in the dictionary has one key and one value. They are defined by commas.
A key value is separated by a colon.
Dict1 = {‘name’: ‘john’, ‘code’:6734, ‘dept’: ‘sales’}
print dict1[‘name’] # Prints value for ‘one’ key
print dict1[‘code’] # Prints value for 2 key
print dict1.keys() # Prints all the keys
print dict1.values() # Prints all the values
>>> d= [‘name’: ‘Mark’,’age’:45,’city’:Madras]
To access the keys,
>>> d.keys()
[‘city’, ‘age’, ‘name’]
>>> d.values()
[‘Madras’, 43, ‘Mark’]
>>> d[‘name’]
‘Mark’ d[‘age’]
43
>>>
Let’s look at slicing: Return copy of a subset
>>> t= [23, ‘abc’, 4.56, [2,3], ‘def’]
Return a copy of the container with a subset of the original members. Start copying at the first index and stop copying before second.
>> t[1:4]
(‘abc’, 4.56, (2,3))
Negative indices count from end
>>> t[1:-1]
(‘abc’,4,56, (2,3)
The ‘in’ Operator
In the previous sessions we’ve paid attention to other operators such as + operator, concatenation etc. Let’s talk about the ‘in’ operator in this section.
The ‘in’ operator works very well on a lists. First let’s define a list and then check if the particular elements are there in a list.
For example,
>>> x=[1,2,5,4]
To check if the particular item is there on the list, we write,
>>> 3 in x
Since the element ‘3’ is not there on the list, it will return false.
False
Now let’s check if element ‘1’ is there in the list.
>>> 1 in x
Since 1 is present, it will display ‘True’
True
Similarly, we can use ‘in’ operators to find if the items are there in the list or not. It searches for a particular value and searches if it is there in a particular container or not. It works for strings as well.
For example, if I have a string
>>> x=’Autonomous Car”
Now i’d like to extract and see if a particular character is there in the string.
>>> ‘s’ in x
The output would be
True
And if the character isn’t there, it displays False.
This is a good way to detect if a value is there in a particular string. It becomes more useful and powerful if used within the loops ( For and if loops)
 
PLUS OPERATOR
The Plus Operator is used to concatenate lists, tuples and strings. Let’s look at a quick example.
The Theory
The + operator produces a new tuple list or string whose value is the concatenation of its arguments.
>>> (1,2,3) + (4,5,6)
(1,2,3,4,5,6)
>>>[1,2,3] + [4,5,6]
[1,2,3,4,5,6]
It can also be used to concatenate two strings
>>> “Hello” + “” + “World”
‘Hello World’
Multiply Operator
The Multiply Operator produces a new tuple, list, or string that has the original content.
The multiply operator repeats the value which is present in the list.
For example,
>>> [1,2,4]* 2
[1,2,4,1,2,4]
If you want to repeat the characters again twice, * 2 makes that happen.
>>> (‘hello’, 50) * 2
This is the end result.
(‘hello’, 50, ‘hello’, 50)
Example 3
>>> ‘Hello’ * 3
‘Hello Hello Hello’
One other important thing to take note is that Lists are not mutable. You can change values inside lists.
>>>li =[‘abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]

  • We can change lists in place.
  • Name li still points to the same memory reference when we’re done,

Let’s take this example
>>> x=[45,78, 2.5,’how are you’]
>>> x[1] = 12
>>> x
[45,12,2.5. ‘How are you’]
>>> x[0] = 456
>>> x
[456, 12, , 2.5, ‘how are you’]
>>> y=(45, 56, 1.2)
>>> y=[0]=2
If you cannot change a particular item in a tuple, you can rename or reassign values in the tuple. If you use y again and reassign values to it, this will update the tuple.
 
Tuples are immutable
>> t= (23,’abc’,4.56(2,3),’def’)
>>> t[2] = 3.14
Traceback (most recent call last)
File “<pyshel#75>”, line1, in -toplevel-
tu[2]=3.14
TypeError:object doesn’t support item assignment

  • You cant change a tuple
  • You can make a fresh tuple and assign its reference to a previously used name

>>> t=(23, ‘abc’, 3.14,(2,3),’def’)

  • The immutability of tuples means they’re faster than lists.

Operations that work on Lists
Lists have many methods, including index, count, remove, reverse, sort
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of 1st occurence
1
>>> li.count(‘b’) #number of occurences
2
>>> li.remove(‘b’) #remove 1st occurence
>>> li
[‘a’,’c’,’b’]
If you want to add value to a list, you can use these commands.
Append command
Append is a function that lets you add an element at the end of the list.
>>> x
[45,56,11,’a’,’b’]
>>> x.append[‘hello’]
>>> x
[45,56,11,’a’,’b’,’hello’]
Inserting an element
>>> x.insert[3,’hi’]
[45,56,11,’a’, hi, ‘b’, ‘hello’]
Counting the elements
>>> x
[45,56,11,’a’, hi, ‘b’, ‘hello’, ‘b’]
>>> x.count(’b’)
2
>>>x.remove(‘hi’)
>>>x
[45,56,11,’b’,’hello’,’b’]\
When you are trying to get the inside elements of a sub list.
You can traverse between elements in the array

>>>x[2]

[1, ‘a’]

>>> x[2] [0]

1

>>> x[2] [1]

‘a’

Lets work
LABS
Now we’ll start with the control structure in python, the very basic loop we use, for loop and while loop. For conditional programming, we use if else structure.
If else structure , we don’t use brackets to define the syntax in a particular condition.  A typical if else structure would look like this:
If expression1:
statement(s)
elif expression2:
statement(s)
elif statement(s)
else:
statement(s)
Let’s try it out in the command prompt
We’re going to use the input command.
x.=input(‘Enter your weight’)
//Here you can see that the conditions are not defined in small brackets, after every loop, you’ll have to use a semicolon.      
After you press semicolon the cursor will appear after a certain indentation. This Indentation is important to the python format for loops. Once in the loop, use backspace to exit.  If you mess with it, it will throw errors.
If x>50 and x<75:
print ‘you seem to be fit’
print ‘great’
Elif x>75 and x<90:
Print ‘you are not fit’
print ‘We recommend exercise daily’
print ‘how are you?’
The ‘how are you?’ is out of the indentation and is out of the if loop. As soon you get out of the loop, you can write functions anew.
// Now Save the file.
In the terminal open the file.
You should see
Enter your weight
55  //your input
You seem to be fit.
Great.
how are you?
For a different value
Enter your weight
80
You are not fit
We recommend exercise daily
how are you?
===============
Let’s try and make a BMI calculator with what we’ve learned.
w=input(‘ Enter your weight in KG’)
h=input(Enter your height in CMs’)
h=float(h)/100;
bmi=w/(h*h)
print bmi
In the terminal
Enter your weight in KG 60
Enter your height in CMS 150
26.666666666
============================
We’ll see how we can extend this program a bit with if else structure
w=input(‘ Enter your weight in KGs’)
h=input(Enter your height in CMs’)
h=float(h)/100;
bmi=w/(h*h)
print bmi
If bmi<25:
   Print ‘ you are underweight’
   print ‘Eat More’
Elif bmi>25 and bmi<35:
   print ‘You look fine and fit’
   Print ‘go and party’
Else:
    print  ‘you are overweight’
    print  ‘You should exercise regularly’
Let’s run this in Terminal
Enter your weight in KGs 60
Enter your height in CMs 150
26.6666666
You look fine and fit
Go and party
//Let’s try With a different value
Enter your weight in KGs 80
Enter your height in CMs 150
35.5555555555
You are Overweight
You should exercise regularly
// Let’s try with weight as 50
Enter your weight in KGs 50
Enter your height in CMs 160
19.53125
You are underweight
Eat More

FOR LOOP

There are two ways to use a for loop, one them is similar to other language.
for i in range(0, 10):
    Print i*i
It should search for 0 to 10, starts at 1 and ends at  9.
In terminal
0
1
4
9
16
25
36
49
64
81
>>>
The another way would be to do it this way:
x=(‘hello’, ‘ how are you?,’Python’,’car’.’self driving car’, ‘robotic car’)
For i in x:
 //For every element in x, i counts every element of x .   
  If i==’python’:
       c=1
      print c
You can use the in operator as well.
If ‘car’ in i:
    print ‘Present’
While Loop
While True:
        Print ‘hello’
Let’s see in this example
x=45
While x<65:
      Print x
      x=x+1
In Terminal
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

DEFINING FUNCTIONS

Functions in Python can be used to repeat a set of code by using only a single statement. Functions in python also takes a lot of arguments and return one sort of output. Functions accept a lot of input arguments and return it in one output argument.
Let’s name a function called myfun, let’s leave the input parameters blank
De myfun():
     print “I am function’
     print  ‘how are you with python’
 
//Let’s call this function in the terminal.
>>>myfun()
I am function
How are you with python
Let’s try with an input argument with this function
Def myfun(x,y):
     # print ‘ I am function’
     # print ‘how are you with python’
      print x+y
      Print x*y
In terminal
>>> myfun(5,6)
11
30
>>> myfun (2,3)
5
6
Etc.
//If you want to return x
‘This is my function’
     # print ‘ I am function’
     # print ‘how are you with python’
      print x+y
      Print x*y
Return x
The first line in the function can be used as a parse statement and the compiler will ignore it.
In the Terminal,
>>> myfun(10, 12)
22
120
10

DEFINING CLASS

A Class is an object oriented operator that encapsulates a lot of operators and functions inside it.
All the functions and operators can be called using the class by defining an object an of type the class, you can call the functions inside the class.
The Structure:
>>> Class person:
    Def sayhi(self):
           print ‘Hello, How are you?’
>>> p =person()
>>> p.sayhi()
Hello, How are you?
Let’s take this example:
Class A:
       Def fun1(self):
           Print ‘how are you’
           print ‘i am class A and fun1’
In the terminal, define an object of the same class and then call the function inside it.
 
>>> x=A()
>>> x.fun1()
How are you
   I am class A and fun1

Inheritance

Classes can inherit the properties of another class.
>>> class A:
  Def hello(self):
              Print ‘I am Super Class’
>>> class B(A):
           Def bye(self):
                   print ‘I am Sub Class’
>>> p=B()
>>> p.hello()
I am Super Class
>>>p.bye()
I am Sub Class
Class A:
def fun1(self):
            Print ‘how are you’
            Print ‘i am class A and fun1’
Def fun2(self):
       print  ‘ I am Class A ut fun2’
Class B(A):       //When we have done now is we have inherited the functions of class A to class B
Class B(A):
       Def fun3 (self):
               Print ‘ i am Class B and function 3’   
In terminal
//Let me call class A
>>>X=A()
>>> x.fun1()      // let’s call fun1
How are you
   I am class A and fun1
>>> x.fun2()     // let’s call fun2
I am class A but fun2
We cannot access fun3, because fun3 is present in class B, class A will not be able access the properties of functions defined in class B.
Incase if we define objects of class B, i can call the functions that are defined under B, in this case, fun3.
>>> y=b()
>> y.fun3()
I am Class B and function 3
But also, we can also call the functions defined in class A, as functions defined in Class B is inheriting all the properties of class A.
>>>y.fun1()
How are you
 I am class A and fun1
>>> y.fun2()
I am class A but fun2

Using inbuilt modules in python

We use inbuilt modules in python to call functions that are pre-built into python, modules like time, numpy etc
>>> import time
>>> print ‘The sleep started’
The Sleep started
>>> time.sleep(3)
>>> print ‘The sleep Finished’
The sleep finished
Let’s try it out.
//If we want to import time
import time
print ‘time before’
time.sleep(5)
print ‘time finished’
In the terminal, we’ll see that the program sleeps for 5 seconds before  it displays the ‘time finished’ message
With this, we are at the end of Chapter One. In the next Chapter we discuss how Linear Algebra helps constructing the fundamentals of Machine Learning.
Recommended Reading: Chapter 2: Linear Algebra For Machine Learning
To start reading from a topic of your choice, you can go back to the Table of Contents here
This course evolves with your active feedback. Do let us know your feedback in the comments section below.

GET THE BEST APPS IN YOUR INBOX

Don't worry we don't spam

      LaunchToast
      Logo
      Enable registration in settings - general
      Compare items
      • Total (0)
      Compare
      0