21
Feb 12

First program

 

This is a short write up of how to create an actual python program file instead of typing commands into IDLE's command prompt.  

Python programs are really just text files full of commands that the Python interpretor recognizes.  Lets take what we have learned so far, put it into a python file (*.py file) and run it in IDLE as an actual python program.  We will use notepad to write our program and IDLE to execute it.  The most important thing to remember if you are a beginner is that white space matters.  I will elaborate more on this later.  Take the code below and paste it into a text file.  Save the text file as "test.py".  After this, run Idle and go to file -> open and open your 'test.py' file.  It will open in a new Idle window and once it does select Run -> Run Module.  You can also press F5 in the Idle text editor to run your code.


op1 = [5,6,7,8]
op2 = [1,2,3,4]
prod = op1[1] * op2[1]
sum = op1[2] + op2[3]
print(prod)
print(sum)

So in this example we take elements out of two lists and perform a simple math operation on them.  This is almost the same as what was done in Idle, but we use the print statement here and save all our values off to variables.  The print() statement is a print to console command in python.  If print isn't used then your code runs and all the instructions will be executed, but nothing will be printed to the screen for the user to see.

An example with strings and concatenation:


st = 'Hello World'
letter3 = st[2]
letter8 = st[7]
print(letter3, letter8)

section = st[3:9]
longString = st + ' Hello Again'
print(section)
print(longString)

The print statement is very useful for debugging so plan on getting used to using it.  Also, make sure you become comfortable with the idea of strings, lists and dictionaries because they are a large part of developing useful code.