Python Programming/Creating Python programs

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Self Help Index Next: Variables and Strings

Welcome to Python! This tutorial will show you how to start writing programs.

Python programs are nothing more than text files, and they may be edited with a standard text editor program.[1] What text editor you use will probably depend on your operating system: any text editor can create Python programs. It is easier to use a text editor that includes Python syntax highlighting, however.


[edit] Hello, World!

The first program that every programmer writes is called the "Hello, World!" program. This program simply outputs the phrase "Hello, World!" and then quits. Let's write "Hello, World!" in Python!

Open up your text editor and create a new file called hello.py containing just this line (you can copy-paste if you want):

print("Hello, world!")
or
def hello(message):
   message = "hello, world!"
   print(message)
   return message
print(hello("message"))

This program uses the print function, which simply outputs its parameters to the terminal. print ends with a newline character, which simply moves the cursor to the next line.

Now that you've written your first program, let's run it in Python! This process differs slightly depending on your operating system.

Note:
In Python 2.6, print is a statement rather than a function. As such, it printed everything until the end of the line, did not utilize parenthesis and required using a standalone comma after the final printed item to identify that the current line was not yet complete.

[edit] Windows

If it didn't work, make sure your PATH contains the python directory. See Getting Python.

[edit] Mac

[edit] Linux

Note:
If you have both python version 2.6.1 and version 3.0 installed (Very possible if you are using Ubuntu, and ran sudo apt-get python3 to have python3 installed), you should run python3 hello.py

[edit] An Alternative

There is a file called idle.py in your Python file. It is in the idlelib folder, located in the Lib folder. This is a Python programmer written in Python. You might find it a bit easier to use than cmd.

[edit] Result

The program should print:

Hello, world!

Congratulations! You're well on your way to becoming a Python programmer.

[edit] Exercises

  1. Modify the hello.py program to say hello to a historical political leader (or to Ada Lovelace).
  2. Change the program so that after the greeting, it asks, "How did you get here?".
  3. Re-write the original program to use two print statements: one for "Hello" and one for "world". The program should still only print out on one line.

Solutions

[edit] Notes

  1. Sometimes, Python programs are distributed in compiled form. We won't have to worry about that for quite a while.


Previous: Self Help Index Next: Variables and Strings
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export