Title: Python Basics
1Python Basics
Tom LeFebvre
2Python Language
- Very High-Level Language
- Scripting Language (no compiling)
- Simple syntax
- Easy to Learn/Use
- Slow execution
3Indentation
- Python uses indentation to identify blocks of
code - Might be difficult to get used to
- Code is more readable
4Code Comments
- Code comments are identified with the
symbol - Example
Print the value print The value is, value
5Statements
- The if statement has the syntax
if condition1 doSometing elif condition2
doSomethingDifferent elif condition3
doAnotherThing else doSomethingElse
6Statements (cont.)
- The for loop has the syntax
- The range statement is very useful
for iterator in list doSomethingWithTheIterat
or
range(0,10) is the same as 0, 1, 2, 3, 4,
5, 6, 7, 8, 9 for i in range(10) print i
7The def Statement
- The def statement starts a method.
def myMethod print myMethod executing.
8Data Structures - Lists
- List a (mixed) collection of objects
- Lists are mutable
- Lists may be nested 1, 2, 3 , 6, 7
myList hello, 2, 10.24
myList2 20.48 print myList hello, 2,
20.48
9Data Structures - Tuples
- Tuple an immutable (mixed) collection of objects
cityInfo (Boulder, (40.0, -105.0)) cityName,
location cityInfo copy out components print
cityName Boulder print location (40.0, -105.0)
10Data Structures - Dictionaries
- Dictionary non-ordered collection referred to by
a key.
key data
myDict joe (Joseph Smith, Private,
5226677), sam(Samuel
Jones, Sergeant, 5124989),
bob(Robert Doe, General, 7689098),
11Other Peoples Code
- Much code has already been written that can
greatly help you. - Two types of outside code
- Modules loose collection of methods
- Classes tightly-coupled, coherent collection of
data and methods
12Modules
- Modules are a collection of Python methods
- You can access modules by using import
import math print math.pi --- 3.14159265358
OR from math import
print pi --- 3.14159265358
13Classes
- Python is an Object-Oriented language
- Class a collection of data and methods
- Data - things
- Methods - actions
class MyClass def DoSomething() def
printSomething()
14Inheritance
- Code can inherit from classes
- myTool inherits from class SmartScript
- myTool has access to the data and methods in
SmartScript - To access data or methods in any class use
myTool(SmartScript.SmartScript)
self.
15Where to use self.
- When calling method
- When accessing data
- When defining a new function
self.method()
a self.dataVariable
def myNewMethod(self, arg1, arg2)
16Good Programming Practices
- Modularization
- Break up code into smaller pieces each of which
performs some small task - avoids long methods
- improves readability
- easier to understand/maintain
- easier to find bugs
17Good Programming Practices
- Documentation
- Should be short
- Include one sentence for each method
- In-line documentation where necessary
- Choose names well
- For methods use verbs
- For data variables use nouns
18Troubleshooting
- Use print statements
- Add code incrementally test