Embedded Programming and Robotics Lesson 14 Introduction to

Embedded Programming and Robotics Lesson 14 Introduction to

Embedded Programming and Robotics Lesson 14 Introduction to Python Programming Beginning Python 1 General Information Unlike C/C++ or Java, Python statements do not end in a semicolon In Python, indentation is the way you indicate the scope of a

conditional, function, etc. Look, no braces! Python is interpretive, meaning you dont have to write programs. You can just enter statements into the Python environment and theyll execute For the most part, well be writing programs Beginning Python 2 The Python Shell Because Python is interpretive, you can do simple things with the

shell In the graphical shell on Linux, double-click on LXTerminal At the prompt, type Python You should have a >>> prompt Type in: print(hello, world) You have written your first Python program Keep the shell up; well be using it Beginning Python 3 The Python Shell

This is good for simple calculations but not for real programming For programming, well use Idle There are two versions: Idle for Python 2.7 and Idle3 for Python 3.2 For most of what we do, well have to use 2.7 because Bluetooth doesnt seem to work with 3.2 Youll run as the superuser because otherwise you wont have access to the GPIO pins Idle will give you access to a shell but also to an IDE for writing and saving programs Beginning Python 4

Python Modules In practice, only the simplest programs are run in the shell You can create a module by going to the File->New Window menu option This brings up a text editor that lets you create a Python program and run it Write your first Hello World! program thus: print(Hello, World!) Beginning Python 5

Python Modules Press F5 It will ask you to save the file before you run it Save it to your home directory as HelloWorld.py You must provide the .py extension If you want to run it outside of the development environment simply type: python HelloWorld.py Note that Linux is case sensitive Beginning Python 6

Variables As in every language, a variable is the name of a memory location Python is weakly typed That is, you dont declare variables to be a specific type A variable has the type that corresponds to the value you assign to it Variable names begin with a letter or an underscore and can contain letters, numbers, and underscores Python has reserved words that you cant use as variable names Beginning Python 7

Variables At the >>> prompt, do the following: x=5 type(x) x=this is text type(x) x=5.0 type(x) Beginning Python 8

Printing Youve already seen the print statement You can also print numbers with formatting These are identical to Java or C format specifiers Beginning Python 9 Comments All code must contain comments that describe what it does In Python, lines beginning with a # sign are comment lines On American English keyboards, this is over the 3 key; I dont know

where it is on British English keyboards You can also have comments on the same line as a statement # This entire line is a comment x=5 # Set up loop counter Beginning Python 10 Operators Arithmetic operators we will use: + - * / addition, subtraction/negation, multiplication, division

% modulus, a.k.a. remainder ** exponentiation precedence: Order in which operations are computed. * / % ** have a higher precedence than + 1 + 3 * 4 is 13 Parentheses can be used to force a certain order of evaluation. (1 + 3) * 4 is 16 Beginning Python 11

Expressions When integers and reals are mixed, the result is a real number. Example: 1 / 2.0 is 0.5 The conversion occurs on a per-operator basis. 7 / 3 * 1.2 + 3 / 2 2 * 1.2 + 3 / 2

2.4 + 3 / 2 2.4 + 1 3.4 Beginning Python 12 Math Functions Use this at the top of your program: from math import *

Beginning Python 13 Relational Operators Many logical expressions use relational operators: Beginning Python 14 Logical Operators

These operators return true or false Beginning Python 15 The if Statement Syntax: if : x = 5 if x > 4: print(x is greater than 4)

print(This is not in the scope of the if) Beginning Python 16 The if Statement The colon is required for the if Note that all statement indented one level in from the if are within it scope: x = 5 if x > 4: print(x is greater than 4) print(This is also in the scope of the if)

Beginning Python 17 The if/else Statement if : else: Note the colon following the else This works exactly the way you would expect

Beginning Python 18 The for Loop This is similar to what youre used to from C or Java, but not the same Syntax: for variableName in groupOfValues: variableName gives a name to each value, so you can refer to it in the statements. groupOfValues can be a range of integers, specified with the range function. Example: for x in range(1, 6):

print x, "squared is", x * x Beginning Python 19 Range The range function specifies a range of integers: range(start, stop) - the integers between start (inclusive) and stop (exclusive) It can also accept a third value specifying the change between values. range(start, stop, step) - the integers between start (inclusive) and stop (exclusive) by step

Beginning Python 20 The while Loop Executes a group of statements as long as a condition is True. Good for indefinite loops (repeat an unknown number of times) Syntax: while : Example: number = 1 while number < 200:

print number, number = number * 2 Beginning Python 21 Exercise Write a Python program to compute and display the first 16 powers of 2, starting with 1 Do this in the Python shell Beginning Python

22 Strings String: A sequence of text characters in a program. Strings start and end with quotation mark " or apostrophe ' characters. Examples: "hello" "This is a string" "This, too, is a string. It can be very long!" A string may not span across multiple lines or contain a " character. "This is not a legal String." "This is not a "legal" String either."

Beginning Python 23 Strings A string can represent characters by preceding them with a backslash. \t tab character

\n new line character \" quotation mark character \\ backslash character Example: "Hello\tthere\nHow are you?" Beginning Python 24 Indexing Strings As with other languages, you can use square brackets to index a string as if it were an array:

name = Arpita Nigam print(name, starts with , name[0]) Beginning Python 25 String Functions len(string) - number of characters in a string str.lower(string)- lowercase version of a string str.upper(string)- uppercase version of a string str.isalpha(string) - True if the string has only alpha chars

Many others: split, replace, find, format, etc. Note the dot notation: These are static methods. Beginning Python 26 Byte Arrays and Strings Strings are Unicode text and not mutable Byte arrays are mutable and contain raw bytes For example, reading Internet data from a URL gets bytes Convert to string: cmd = response.read()

strCmd = str(cmd) Beginning Python 27 Other Built-in Types tuples, lists, sets, and dictionaries They all allow you to group more than one item of data together under one name You can also search them Beginning Python

28 Tuples Unchanging Sequences of Data Enclosed in parentheses: tuple1 = (This, is, a, tuple) print(tuple1) This prints the tuple exactly as shown Print(tuple1[1]) Prints is (without the quotes) Beginning Python

29 Lists Changeable sequences of data Lists are created by using square brackets: breakfast = [ coffee, tea, toast, egg ] You can add to a list: breakfast.append(waffles) breakfast.extend([cereal, juice]) Beginning Python

30 Dictionaries Groupings of Data Indexed by Name Dictionaries are created using braces sales = {} sales[January] = 10000 sales[February] = 17000 sales[March] = 16500 The keys method of a dictionary gets you all of the keys as a list Beginning Python

31 Sets Sets are similar to dictionaries in Python, except that they consist of only keys with no associated values. Essentially, they are a collection of data with no duplicates. They are very useful when it comes to removing duplicate data from data collections. Beginning Python 32

Writing Programs Bring up the Idle3 IDE The first line of your code should be this: #!/usr/bin/env python 3.1 Write the same code you wrote for the exercise of powers of 2 using the IDEs editor Press the F5 key to run the program It will ask you to save the program. Give it a name like PowersOf2.py The program will run in a Python shell from the IDE If there are errors, the shell will tell you Beginning Python 33

Writing Functions Define a function: def () The function body is indented one level: def computeSquare(x) return x * x # Anything at this level is not part of the function Beginning Python 34

Error Handling Use try/except blocks, similar to try/catch: fridge_contents = {egg:8, mushroom:20, pepper:3, cheese:2, tomato:4, milk:13} try: if fridge_contents[orange juice] > 3: print(Sure, lets have some juice!) except KeyError: print(Awww, there is no orange juice.) Beginning Python 35

Error Handling Note that you must specify the type of error Looking for a key in a dictionary that doesnt exist is an error Another useful error to know about: try: sock = BluetoothSocket(RFCOMM) sock.connect((bd_addr, port)) except BluetoothError as bt Print(Cannot connect to host: + str(bt)) Beginning Python 36

Using the GPIO Pins The Raspberry Pi has a 40-pin header, many of which are generalpurpose I/O pins Include the library: import RPi.GPIO as GPIO Set up to use the pins: GPIO.setmode(GPIO.BOARD) Beginning Python 37 Using the GPIO Pins

The GPIO.BCM option means that you are referring to the pins by the "Broadcom SOC channel" number, these are the numbers after "GPIO" in the green rectangles around the outside of the diagram: Beginning Python 38 Using the GPIO Pins This is from my home-control code: LAMP = 22 MOTION = 23 GPIO.setup(LAMP, GPIO.OUT)

GPIO.setup(MOTION, GPIO.IN) sensor # For turning on the lamp # For reading the motion Like the Arduino, we must set up the pins for input or output Beginning Python 39 Using the GPIO Pins

Reading from a GPIO pin: # If we detect motion, print that. if GPIO.input(MOTION): print( "Motion detected") Beginning Python 40 Using the GPIO Pins Output to GPIO: if cmd=='LAMPON': cmdlist["LAMPSTATUS"] = True;

GPIO.output(LAMP, True) # turn on the light Beginning Python 41 Programming Exercise Write a Python program that blinks an LED at a rate of 1 second on, one second off To do this, youll need to use the idle3 environment running as the superuser:

sudo idle3 Beginning Python 42 Python File I/O You can read and write text files in Python much as you can in other languages, and with a similar syntax. To open a file for reading: try: configFile = open(configName, "r") except IOError as err:

print(could not open file: + str(err)) Beginning Python 43 Python File I/O To read from a file: while 1: line = configFile.readline() if len(line) == 0: break

Beginning Python 44 Python File I/O You can also read all lines from a file into a set, then iterate over the set: lines = file.readlines() for line in lines: print(line) file.close()

Beginning Python 45 Python File I/O Writing to a text file file=open(test.txt,w) file.write(This is how you create a new text file) file.close() Beginning Python


Recently Viewed Presentations

  • Application of the &quot;UPCS Guidance and Protocol Clarifications ...

    Application of the "UPCS Guidance and Protocol Clarifications ...

    The media, politicians, and our own HUD staff, have raised questions concerning substandard repairs of inspectable items. To minimize the possibility of the H&S hazards that may result from substandard repairs. i.e. misaligned or improperly vented water heaters.
  • &quot;Preach the Word&quot; - parkviewcoc.org

    "Preach the Word" - parkviewcoc.org

    Timothy must be ready to preach whether personally convenient for him or not. 1 Timothy 4:14-16. Timothy must be ready - Could it be that having lived in the shadow of Paul and letting him take the lead that Paul...
  • The Outbreak of War - hudson.k12.oh.us

    The Outbreak of War - hudson.k12.oh.us

    Single worst atrocity during World War II. Japan, China, and the US. China in collapse. US aids Chinese . Flying Tigers. American pilots who fly for Chinese. Panay Incident - Dec 1937. Japanese fire on USS Panay, American ship anchored...
  • Prezentacja programu PowerPoint - UMK

    Prezentacja programu PowerPoint - UMK

    Why is the world green? With predators of herbivores. Without predators of herbivores. Terborgh et al. 2006, J. Ecol. Venezuela. Comparing the defoliation by herbivores on small (without predators), intermediate (some arthopod predators ) and large islands/mainlands (all types of...
  • Recognizing When Black Swans Arent : Holistically Training

    Recognizing When Black Swans Arent : Holistically Training

    M.C. Escher - Metamorphosis . www.mcescher.com. Patternist: someone who views patterns of information as the fundamental reality. What kind of person, educated and trained how is best at detecting patterns, and changes in patterns? Think of complex systems' states as...
  • Structures to Promote Student Engagement - April Capuder

    Structures to Promote Student Engagement - April Capuder

    PIES: Basic Principles of Kagan. All structures presented today incorporate these basic principles of PIES. Teach Kinesthetic movements to remember. So far we've used these structures: RallyRobin (What we know about Cooperative Learning) RallyCoach(Order of Operations Math) Timed Pair Share...
  • Higher Processing of Visual Information: Lecture I ---

    Higher Processing of Visual Information: Lecture I ---

    The receptive fields of LGN neurons are concentric with a stronger surround antagonism than that in RGCs, suggesting the LGN is not a simple relay station. (Hubel & Wiesel, 1962) LGN receptive fields Retinotopic Maps Adjacent neurons in the retina...
  • Grand Rounds The Great Imitator Patrick Burchell, PGY-3

    Grand Rounds The Great Imitator Patrick Burchell, PGY-3

    White dot syndrome due to the intraretinal lesions seen along the superotemperal arcade. Idiopathic. Pt was lost to follow up for 2 months but returned after an acute decrease in vision OD. Stated that vision had improved OS. Did not...