-
Notifications
You must be signed in to change notification settings - Fork 1
Python Crash Course
The official Python 3 documentation can be found here.
Python itself may be used as an imperative, object-oriented, or functional programming language. Projtrack3 uses almost entirely object-oriented and imperative programming conventions. Projtrack body code is almost entirely class-based, while the various scripts are subroutine- and function-based.
A Python class has the general structure
class ClassName (InheritsFrom):
def __init__(self):
stuff_to_do_when_insantiated()
InheritsFrom is the name of a class, such as object, that the class should inherit its base attributes from. All classes directly or indirectly inherit from object. If you're familiar with object inheritance from a language like Java, this is essentially identical to public class ClassName extends InheritsFrom.
The method __init__(self) is implicitly called by the constructor. x = ClassName() instantiates the object and runs everything in the __init__ function. The first argument, self, is implicitly passed by the constructor and can effectively be ignored when creating class objects. All non-static methods of any class should always take self as their first argument.
A subroutine or function has the syntax
def functionName(arguments):
do_stuff()
(a subroutine is simply a function with no return value) and is called simply by invoking the function name: functionName(arguments) (or x = functionName(arguments) in the case of a function).
Whitespace is strongly involved in the organization of Python code. If not indented properly, the source will not run. Each code block must be indented exactly as in the last two examples. Loops and conditionals are similar, with the syntax:
for x in range(100):
print(x)
if x:
print("True.")
while !x:
print("x is true now.")
x = True
Note that if x: do_stuff() will work, but
if x:
do_stuff()
will not.
Python is a dynamically-typed language, which means that the source code requires no type declaration, and duck-typed, which means that types are inferred and determined at runtime. For example, in C,
int x = 1;
x = 'c';
will fail during compilation, but in Python
x = 1
x = 'eggs'
x = 1.232
x = 'spam'
is perfectly valid and working code. However, Python does have runtime type checking which ensures that something like
x = 'string'
x += 1 # 'x += 1' is syntactic sugar for 'x = x + 1'
will fail, since the types str and int cannot be operated on together.
Variable assignment is affected with the syntax x = 1 with no other keywords necessary.
University of Scranton Technical Consultants Documentation under Construction