Scripting Basics
Python is easy to learn, and with some understanding of its basic syntax, you can get started making your own scripts.
Hello World
Let's get right to everyone's favorite example, "Hello World." The following script will print out "
Hello World
"
to the Output Console.
The print
keyword is a handy tool in Python, allowing you to write text to the Output Console. This is useful for debugging your scripts. You can print multiple things by separating them with commas.
Variables
Variables are created by simply assigning a value to them. Variables do not need to be declared, because Python has a dynamic type system. That means Python figures out the type of the variable on the fly when the script is executed.
The following script would print out: 15
Strings
Strings are defined in Python with a matching pair of 1 or 3 single or double quotes. There are few times when the type of quotation mark you use matters - but one common reason to choose one or the other is for 'escaping' other quotes inside your content. Some of the rules are shown here:
print "This is my text" # Using double quotation marks
print 'This is my text' # Using single quotation marks
print "This is my text' # This will not work because Python does not allow mixing the single and double quotation marks
print "My name is 'David'" # This will print: My name is 'David'
print 'My name is "David"' # This will print: My name is "David"
print 'My name is Seamus O\'Malley' # This will print: My name is Seamus O'Malley
Triple quotes (single or double) can be used to make 'escaping' both single and double quotes inside your string easier, or to write multi-line comments:
'''
This is a lot of text
that you want to show as multiple lines of
comments.
Script written by Professor X.
Jan 5, 1990
'''
print 'Hello world'
Strings can also be prefixed with certain characters to change how they are interpreted - for instance, a leading u
character marks a string as Unicode, allowing for characters outside of the ASCII range to be used.
Whitespace
Perhaps Python's most unique feature is logical blocks which are defined by an indentation in Python. A colon (:) starts a new block, and the next line must be indented (typically using a tab or 4 spaces). The block ends when the indentation level returns to the previous level. For example, the following will print out "
5 4 3 2 1 Blast-off
" with each value on a new line. The final print is not part of the while loop because it isn't indented.
countdown = 5
while countdown > 0:
print countdown
countdown = countdown - 1
print "Blast-off!"